path
stringlengths
5
300
repo_name
stringlengths
6
76
content
stringlengths
26
1.05M
src/renderers/shared/reconciler/__tests__/ReactMockedComponent-test.js
stevemao/react
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; var React; var ReactTestUtils; var mocks; var OriginalComponent; var AutoMockedComponent; var MockedComponent; describe('ReactMockedComponent', function() { beforeEach(function() { mocks = require('mocks'); React = require('React'); ReactTestUtils = require('ReactTestUtils'); OriginalComponent = React.createClass({ getDefaultProps: function() { return {bar: 'baz'}; }, getInitialState: function() { return {foo: 'bar'}; }, hasCustomMethod: function() { return true; }, render: function() { return <span />; }, }); var metaData = mocks.getMetadata(OriginalComponent); AutoMockedComponent = mocks.generateFromMetadata(metaData); MockedComponent = mocks.generateFromMetadata(metaData); ReactTestUtils.mockComponent(MockedComponent); }); it('should allow an implicitly mocked component to be rendered without warnings', () => { spyOn(console, 'error'); ReactTestUtils.renderIntoDocument(<AutoMockedComponent />); expect(console.error.calls.length).toBe(0); }); it('should allow an implicitly mocked component to be updated', () => { var Wrapper = React.createClass({ getInitialState: function() { return {foo: 1}; }, update: function() { this.setState({foo: 2}); }, render: function() { return <div><AutoMockedComponent prop={this.state.foo} /></div>; }, }); var instance = ReactTestUtils.renderIntoDocument(<Wrapper />); var found = ReactTestUtils.findRenderedComponentWithType( instance, AutoMockedComponent ); expect(typeof found).toBe('object'); instance.update(); }); it('has custom methods on the implicitly mocked component', () => { var instance = ReactTestUtils.renderIntoDocument(<AutoMockedComponent />); expect(typeof instance.hasCustomMethod).toBe('function'); }); it('should allow an explicitly mocked component to be rendered', () => { ReactTestUtils.renderIntoDocument(<MockedComponent />); }); it('should allow an explicitly mocked component to be updated', () => { var Wrapper = React.createClass({ getInitialState: function() { return {foo: 1}; }, update: function() { this.setState({foo: 2}); }, render: function() { return <div><MockedComponent prop={this.state.foo} /></div>; }, }); var instance = ReactTestUtils.renderIntoDocument(<Wrapper />); var found = ReactTestUtils.findRenderedComponentWithType( instance, MockedComponent ); expect(typeof found).toBe('object'); instance.update(); }); it('has custom methods on the explicitly mocked component', () => { var instance = ReactTestUtils.renderIntoDocument(<MockedComponent />); expect(typeof instance.hasCustomMethod).toBe('function'); }); });
ajax/libs/yui/3.9.0/simpleyui/simpleyui.js
melvinsembrano/cdnjs
/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { if (Y.config.throwFail) { mod.fn(Y, name); } else { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } return function() { var args = arguments; Y._use(mod, function() { Y.on(until.event, function() { args[1].delayUntil = until.event; cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; } // dynamic load if (boot && len && Y.Loader) { Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // the base path for non-combo paths base: 'http://yui.yahooapis.com/2.8.0r4/build/', // the path to the combo service comboBase: 'http://yui.yahooapis.com/combo?', // a fragment to prepend to the path attribute when // when building combo urls root: '2.8.0r4/build/', // the module definitions modules: { yui2_yde: { path: "yahoo-dom-event/yahoo-dom-event.js" }, yui2_anim: { path: "animation/animation.js", requires: ['yui2_yde'] } } } } @property {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property delayUntil @type String|Object @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); @property {Object|String} delayUntil @since 3.6.0 **/ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; /*jshint expr: true*/ startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { } else { } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { } else { } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { } else { } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { } else { } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** * Deep object/array copy. Function clones are actually * wrappers around the original function. * Array-like objects are treated as arrays. * Primitives are returned untouched. Optionally, a * function can be provided to handle other data types, * filter keys, validate values, etc. * * NOTE: Cloning a non-trivial object is a reasonably heavy operation, due to * the need to recurrsively iterate down non-primitive properties. Clone * should be used only when a deep clone down to leaf level properties * is explicitly required. * * In many cases (for example, when trying to isolate objects used as * hashes for configuration properties), a shallow copy, using Y.merge is * normally sufficient. If more than one level of isolation is required, * Y.merge can be used selectively at each level which needs to be * isolated from the original without going all the way to leaf properties. * * @method clone * @param {object} o what to clone. * @param {boolean} safe if true, objects will not have prototype * items from the source. If false, they will. In this case, the * original is initially protected, but the clone is not completely * immune from changes to the source object prototype. Also, cloned * prototype items that are deleted from the clone will result * in the value of the source prototype being exposed. If operating * on a non-safe clone, items should be nulled out rather than deleted. * @param {function} f optional function to apply to each item in a * collection; it will be executed prior to applying the value to * the new object. Return false to prevent the copy. * @param {object} c optional execution context for f. * @param {object} owner Owner object passed when clone is iterating * an object. Used to set up context for cloned functions. * @param {object} cloned hash of previously cloned objects to avoid * multiple clones. * @return {Array|Object} the cloned object. */ Y.clone = function(o, safe, f, c, owner, cloned) { if (!L.isObject(o)) { return o; } // @todo cloning YUI instances doesn't currently work if (Y.instanceOf(o, YUI)) { return o; } var o2, marked = cloned || {}, stamp, yeach = Y.each; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } // #2528250 don't try to clone element properties if (!o.addEventListener && !o.attachEvent) { yeach(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); } if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.scrollTo && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } }; } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; }; creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@', {"requires": ["dom-core"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); (function(Y) { var PARSE_INT = parseInt, RE = RegExp; Y.Color = { KEYWORDS: { black: '000', silver: 'c0c0c0', gray: '808080', white: 'fff', maroon: '800000', red: 'f00', purple: '800080', fuchsia: 'f0f', green: '008000', lime: '0f0', olive: '808000', yellow: 'ff0', navy: '000080', blue: '00f', teal: '008080', aqua: '0ff' }, re_RGB: /^rgb\(([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\)$/i, re_hex: /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i, re_hex3: /([0-9A-F])/gi, toRGB: function(val) { if (!Y.Color.re_RGB.test(val)) { val = Y.Color.toHex(val); } if(Y.Color.re_hex.exec(val)) { val = 'rgb(' + [ PARSE_INT(RE.$1, 16), PARSE_INT(RE.$2, 16), PARSE_INT(RE.$3, 16) ].join(', ') + ')'; } return val; }, toHex: function(val) { val = Y.Color.KEYWORDS[val] || val; if (Y.Color.re_RGB.exec(val)) { val = [ Number(RE.$1).toString(16), Number(RE.$2).toString(16), Number(RE.$3).toString(16) ]; for (var i = 0; i < val.length; i++) { if (val[i].length < 2) { val[i] = '0' + val[i]; } } val = val.join(''); } if (val.length < 6) { val = val.replace(Y.Color.re_hex3, '$1$1'); } if (val !== 'transparent' && val.indexOf('#') < 0) { val = '#' + val; } return val.toUpperCase(); } }; })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } } else { } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector }; }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { this._kds = Y.CustomEvent.keepDeprecatedSubs; o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ if (this._kds) { this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ if (this._kds) { this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; if (sib) { s += sib._subscribers.length; a += sib._afters.length; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = this._subscribers, a = this._afters, sib = this.sibling; s = (sib) ? s.concat(sib._subscribers) : s.concat(); a = (sib) ? a.concat(sib._afters) : a.concat(); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this._afters.push(s); } else { this._subscribers.push(s); } if (this._kds) { if (when == AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; i = YArray.indexOf(subs, s, 0); } if (s && subs[i] === s) { subs.splice(i, 1); } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; events = edata.events; ce = events[type]; this._monitor('publish', type, { args: arguments }); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, defaults); if (opts) { ce.applyConfig(opts, true); } events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || EMPTY; this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret, events, subs, postponed, self = this, host = self.host || self, next, oldbubble; if (self.stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != self.stack.next.type) { self.log('queue ' + self.type); self.stack.queue.push([self, args]); return true; } } es = self.stack || { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; if (self.stoppedFn) { events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } if (subs[0]) { self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } if (self.prevented) { if (self.preventedFn) { self.preventedFn.apply(host, args); } } else if (self.defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { postponed = subs[1]; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } self.stack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { // protect the event facade properties mixFacadeProps(ef, o); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * If fn is not passed as an argument, the parent node will be returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a single Node instance, the first element matching the given * CSS selector. * Returns null if no match found. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node | null} A Node instance for the matching HTMLElement or null * if no match found. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; return nodelist; }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners. * Note that destroy() will not remove the node from its parent or from the DOM. For that * functionality, call remove(true). * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node} The last item in the NodeList. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node} The first item in the NodeList. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to toggle the style.display property. * @method _show * @protected * @chainable */ _show: function() { this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getStyle(this._node, 'display') === 'none'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using given named effect. * @method toggleView * @for Node * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to toggle the style.display property. * @method _hide * @protected * @chainable */ _hide: function() { this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using given named effect. * @method toggleView * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { name = this.DATA_PREFIX + name; var node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var YDOM = Y.DOM, _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { // TODO: See if there's a more performant way to return true early on this, for the common case return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !YDOM.isWindow(o)); } catch(ex) { return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = YDOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { ret = Event.onAvailable(el, function() { ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = YDOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return YDOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { executeItem(el, item); _avail[i] = null; } else { notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? YDOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); len = children.length; for (i = 0; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); }()); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@', {"requires": ["event-custom-base"]}); (function() { var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc && doc.documentElement, EVENT_NAME = 'onreadystatechange', pollInterval = config.pollInterval || 40; if (docElement.doScroll && !GLOBAL_ENV._ieready) { GLOBAL_ENV._ieready = function() { GLOBAL_ENV._ready(); }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. // This isolates what appears to be a safe moment to manipulate the // DOM prior to when the document's readyState suggests it is safe to do so. if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener); GLOBAL_ENV.ieready(); } }; GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener); } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; GLOBAL_ENV._ieready(); } catch (domNotReady) { } }, pollInterval); } } })(); YUI.add('event-base-ie', function (Y, NAME) { /* * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ function IEEventFacade() { // IEEventFacade.superclass.constructor.apply(this, arguments); Y.DOM2EventFacade.apply(this, arguments); } /* * (intentially left out of API docs) * Alternate Facade implementation that is based on Object.defineProperty, which * is partially supported in IE8. Properties that involve setup work are * deferred to temporary getters using the static _define method. */ function IELazyFacade(e) { var proxy = Y.config.doc.createEventObject(e), proto = IELazyFacade.prototype; // TODO: necessary? proxy.hasOwnProperty = function () { return true; }; proxy.init = proto.init; proxy.halt = proto.halt; proxy.preventDefault = proto.preventDefault; proxy.stopPropagation = proto.stopPropagation; proxy.stopImmediatePropagation = proto.stopImmediatePropagation; Y.DOM2EventFacade.apply(proxy, arguments); return proxy; } var imp = Y.config.doc && Y.config.doc.implementation, useLazyFacade = Y.config.lazyEventFacade, buttonMap = { 0: 1, // left click 4: 2, // middle click 2: 3 // right click }, relatedTargetMap = { mouseout: 'toElement', mouseover: 'fromElement' }, resolve = Y.DOM2EventFacade.resolve, proto = { init: function() { IEEventFacade.superclass.init.apply(this, arguments); var e = this._event, x, y, d, b, de, t; this.target = resolve(e.srcElement); if (('clientX' in e) && (!x) && (0 !== x)) { x = e.clientX; y = e.clientY; d = Y.config.doc; b = d.body; de = d.documentElement; x += (de.scrollLeft || (b && b.scrollLeft) || 0); y += (de.scrollTop || (b && b.scrollTop) || 0); this.pageX = x; this.pageY = y; } if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. this.relatedTarget = resolve(t || e.relatedTarget); // which should contain the unicode key code if this is a key event. // For click events, which is normalized for which mouse button was // clicked. this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; }, stopPropagation: function() { this._event.cancelBubble = true; this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { this.stopPropagation(); this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { this._event.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; } }; Y.extend(IEEventFacade, Y.DOM2EventFacade, proto); Y.extend(IELazyFacade, Y.DOM2EventFacade, proto); IELazyFacade.prototype.init = function () { var e = this._event, overrides = this._wrapper.overrides, define = IELazyFacade._define, lazyProperties = IELazyFacade._lazyProperties, prop; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.keyCode = // chained assignment this.charCode = e.keyCode; this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; for (prop in lazyProperties) { if (lazyProperties.hasOwnProperty(prop)) { define(this, prop, lazyProperties[prop]); } } if (this._touch) { this._touch(e, this._currentTarget, this._wrapper); } }; IELazyFacade._lazyProperties = { target: function () { return resolve(this._event.srcElement); }, relatedTarget: function () { var e = this._event, targetProp = relatedTargetMap[e.type] || 'relatedTarget'; // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. return resolve(e[targetProp] || e.relatedTarget); }, currentTarget: function () { return resolve(this._currentTarget); }, wheelDelta: function () { var e = this._event; if (e.type === "mousewheel" || e.type === "DOMMouseScroll") { return (e.detail) ? (e.detail * -1) : // wheelDelta between -80 and 80 result in -1 or 1 Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } }, pageX: function () { var e = this._event, val = e.pageX, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollLeft; docScroll = doc.documentElement.scrollLeft; val = e.clientX + (docScroll || bodyScroll || 0); } return val; }, pageY: function () { var e = this._event, val = e.pageY, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollTop; docScroll = doc.documentElement.scrollTop; val = e.clientY + (docScroll || bodyScroll || 0); } return val; } }; /** * Wrapper function for Object.defineProperty that creates a property whose * value will be calulated only when asked for. After calculating the value, * the getter wll be removed, so it will behave as a normal property beyond that * point. A setter is also assigned so assigning to the property will clear * the getter, so foo.prop = 'a'; foo.prop; won't trigger the getter, * overwriting value 'a'. * * Used only by the DOMEventFacades used by IE8 when the YUI configuration * <code>lazyEventFacade</code> is set to true. * * @method _define * @param o {DOMObject} A DOM object to add the property to * @param prop {String} The name of the new property * @param valueFn {Function} The function that will return the initial, default * value for the property. * @static * @private */ IELazyFacade._define = function (o, prop, valueFn) { function val(v) { var ret = (arguments.length) ? v : valueFn.call(this); delete o[prop]; Object.defineProperty(o, prop, { value: ret, configurable: true, writable: true }); return ret; } Object.defineProperty(o, prop, { get: val, set: val, configurable: true }); }; if (imp && (!imp.hasFeature('Events', '2.0'))) { if (useLazyFacade) { // Make sure we can use the lazy facade logic try { Object.defineProperty(Y.config.doc.createEventObject(), 'z', {}); } catch (e) { useLazyFacade = false; } } Y.DOMEventFacade = (useLazyFacade) ? IELazyFacade : IEEventFacade; } }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Regex to test for disabled elements during filtering. This is only relevant to IE to normalize behavior with other browsers, which swallow events that occur to disabled elements. IE fires the event from the parent element instead of the original target, though it does preserve `event.srcElement` as the disabled element. IE also supports disabled on `<a>`, but the event still bubbles, so it acts more like `e.preventDefault()` plus styling. That issue is not handled here because other browsers fire the event on the `<a>`, so delegate is supported in both cases. @property _disabledRE @type {RegExp} @protected @since 3.8.1 **/ delegate._disabledRE = /^(?:button|input|select|textarea)$/i; /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // For IE. IE propagates events from the parent element of disabled // elements, where other browsers swallow the event entirely. To normalize // this in IE, filtering for matching elements should abort if the target // is a disabled form control. if (target.disabled && delegate._disabledRE.test(target.nodeName)) { return match; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '@VERSION@', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE and IE >= 10 can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize a map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { if (Y.QueryString && Y.QueryString.stringify) { config.data = data = Y.QueryString.stringify(data); } else { } } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } // Convert falsy values to an empty string. This way IE can't be // rediculous and translate `undefined` to "undefined". data || (data = ''); if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) { transaction.c.withCredentials = true; } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject, // Checks for the presence of the `withCredentials` in an XHR instance // object, which will be present if the environment supports CORS. SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest()); Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { var _JSON = Y.config.global.JSON; Y.namespace('JSON').parse = function (obj, reviver, space) { return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', DOCUMENT_STYLE = DOCUMENT[DOCUMENT_ELEMENT].style, TRANSITION_CAMEL = 'transition', TRANSITION_PROPERTY_CAMEL = 'transitionProperty', TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; // One off handling of transform-prefixing. Transition._TRANSFORM = 'transform'; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; // Map transition properties to vendor-specific versions. if ('transition' in DOCUMENT_STYLE && 'transitionProperty' in DOCUMENT_STYLE && 'transitionDuration' in DOCUMENT_STYLE && 'transitionTimingFunction' in DOCUMENT_STYLE && 'transitionDelay' in DOCUMENT_STYLE) { Transition.useNative = true; Transition.supported = true; // TODO: remove } else { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transition'; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); } // Map transform property to vendor-specific versions. // One-off required for cssText injection. if (typeof DOCUMENT_STYLE.transform === 'undefined') { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transform'; if (typeof DOCUMENT_STYLE[property] !== 'undefined') { Transition._TRANSFORM = property; } }); } if (CAMEL_VENDOR_PREFIX) { TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition'; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; } TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration !== 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay !== 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[Transition._TRANSFORM]) { config[Transition._TRANSFORM] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur) * 1000; return dur + 'ms'; }, _runNative: function() { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } return this; }; Y.NodeList.prototype.show = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).show(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback && typeof callback === 'function') { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else { this._hide(); } return this; }; Y.NodeList.prototype.hide = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).hide(name, config, callback); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name !== 'string') { // no transition, just toggle on = name; this._toggleView(on, callback); // call original _toggleView in Y.Node return; } if (typeof on === 'function') { // Ignore "on" if used for callback argument. on = undefined; } if (typeof on === 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { node = Y.one(node); node.toggleView.apply(node, arguments); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); }, '@VERSION@', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '@VERSION@', { "use": [ "yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple" ] }); var Y = YUI().use('*');
force_dir/node_modules/react-bootstrap/es/FormControlFeedback.js
wolfiex/VisACC
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import Glyphicon from './Glyphicon'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var defaultProps = { bsRole: 'feedback' }; var contextTypes = { $bs_formGroup: React.PropTypes.object }; var FormControlFeedback = function (_React$Component) { _inherits(FormControlFeedback, _React$Component); function FormControlFeedback() { _classCallCheck(this, FormControlFeedback); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } FormControlFeedback.prototype.getGlyph = function getGlyph(validationState) { switch (validationState) { case 'success': return 'ok'; case 'warning': return 'warning-sign'; case 'error': return 'remove'; default: return null; } }; FormControlFeedback.prototype.renderDefaultFeedback = function renderDefaultFeedback(formGroup, className, classes, elementProps) { var glyph = this.getGlyph(formGroup && formGroup.validationState); if (!glyph) { return null; } return React.createElement(Glyphicon, _extends({}, elementProps, { glyph: glyph, className: classNames(className, classes) })); }; FormControlFeedback.prototype.render = function render() { var _props = this.props; var className = _props.className; var children = _props.children; var props = _objectWithoutProperties(_props, ['className', 'children']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); if (!children) { return this.renderDefaultFeedback(this.context.$bs_formGroup, className, classes, elementProps); } var child = React.Children.only(children); return React.cloneElement(child, _extends({}, elementProps, { className: classNames(child.props.className, className, classes) })); }; return FormControlFeedback; }(React.Component); FormControlFeedback.defaultProps = defaultProps; FormControlFeedback.contextTypes = contextTypes; export default bsClass('form-control-feedback', FormControlFeedback);
ajax/libs/F2/1.3.1/f2.no-easyXDM.js
znsstudio/cdnjs
;(function(exports) { if (exports.F2 && !exports.F2_TESTING_MODE) { return; } /*! JSON.org requires the following notice to accompany json2: Copyright (c) 2002 JSON.org http://json.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); /*! * jQuery JavaScript Library v1.8.3 * The jQuery Foundation and other contributors require the following notice to accompany jQuery: * * Copyright (c) 2013 jQuery Foundation and other contributors * * http://jquery.com * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) return (cache[ key + " " ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); /*! ========================================================= * bootstrap-modal.js v2.2.2 * http://twitter.github.com/bootstrap/javascript.html#modals * ========================================================= * Twitter, Inc. require the following notice to accompany Bootstrap: * * Copyright (c) 2012 Twitter, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work * except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing permissions and limitations under the License. * * ========================================================= */ !function ($) { "use strict"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) //don't move modals dom position } that.$element .show() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function (that) { this.$element .hide() .trigger('hidden') this.backdrop() } , removeBackdrop: function () { this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) : this.removeBackdrop() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /*! * This file creates $ and jQuery variables within the F2 closure scope */ var $, jQuery = $ = window.jQuery.noConflict(true); /*! * Hij1nx requires the following notice to accompany EventEmitter: * * Copyright (c) 2011 hij1nx * * http://www.twitter.com/hij1nx * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ !function(exports, undefined) { var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]"; }; var defaultMaxListeners = 10; function init() { this._events = new Object; } function configure(conf) { if (conf) { conf.delimiter && (this.delimiter = conf.delimiter); conf.wildcard && (this.wildcard = conf.wildcard); if (this.wildcard) { this.listenerTree = new Object; } } } function EventEmitter(conf) { this._events = new Object; configure.call(this, conf); } // // Attention, function return type now is array, always ! // It has zero elements if no any matches found and one or more // elements (leafs) if there are matches // function searchListenerTree(handlers, type, tree, i) { if (!tree) { return []; } var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, typeLength = type.length, currentType = type[i], nextType = type[i+1]; if (i === typeLength && tree._listeners) { // // If at the end of the event(s) list and the tree has listeners // invoke those listeners. // if (typeof tree._listeners === 'function') { handlers && handlers.push(tree._listeners); return [tree]; } else { for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { handlers && handlers.push(tree._listeners[leaf]); } return [tree]; } } if ((currentType === '*' || currentType === '**') || tree[currentType]) { // // If the event emitted is '*' at this part // or there is a concrete match at this patch // if (currentType === '*') { for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); } } return listeners; } else if(currentType === '**') { endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); if(endReached && tree._listeners) { // The next element has a _listeners, add it to the handlers. listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); } for (branch in tree) { if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { if(branch === '*' || branch === '**') { if(tree[branch]._listeners && !endReached) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); } listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } else if(branch === nextType) { listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); } else { // No match on this one, shift into the tree but not in the type array. listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); } } } return listeners; } listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); } xTree = tree['*']; if (xTree) { // // If the listener tree will allow any match for this part, // then recursively explore all branches of the tree // searchListenerTree(handlers, type, xTree, i+1); } xxTree = tree['**']; if(xxTree) { if(i < typeLength) { if(xxTree._listeners) { // If we have a listener on a '**', it will catch all, so add its handler. searchListenerTree(handlers, type, xxTree, typeLength); } // Build arrays of matching next branches and others. for(branch in xxTree) { if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { if(branch === nextType) { // We know the next element will match, so jump twice. searchListenerTree(handlers, type, xxTree[branch], i+2); } else if(branch === currentType) { // Current node matches, move into the tree. searchListenerTree(handlers, type, xxTree[branch], i+1); } else { isolatedBranch = {}; isolatedBranch[branch] = xxTree[branch]; searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); } } } } else if(xxTree._listeners) { // We have reached the end and still on a '**' searchListenerTree(handlers, type, xxTree, typeLength); } else if(xxTree['*'] && xxTree['*']._listeners) { searchListenerTree(handlers, type, xxTree['*'], typeLength); } } return listeners; } function growListenerTree(type, listener) { type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); // // Looks for two consecutive '**', if so, don't add the event at all. // for(var i = 0, len = type.length; i+1 < len; i++) { if(type[i] === '**' && type[i+1] === '**') { return; } } var tree = this.listenerTree; var name = type.shift(); while (name) { if (!tree[name]) { tree[name] = new Object; } tree = tree[name]; if (type.length === 0) { if (!tree._listeners) { tree._listeners = listener; } else if(typeof tree._listeners === 'function') { tree._listeners = [tree._listeners, listener]; } else if (isArray(tree._listeners)) { tree._listeners.push(listener); if (!tree._listeners.warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && tree._listeners.length > m) { tree._listeners.warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', tree._listeners.length); console.trace(); } } } return true; } name = type.shift(); } return true; }; // By default EventEmitters will print a warning if more than // 10 listeners are added to it. This is a useful default which // helps finding memory leaks. // // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.delimiter = '.'; EventEmitter.prototype.setMaxListeners = function(n) { this._events || init.call(this); this._events.maxListeners = n; }; EventEmitter.prototype.event = ''; EventEmitter.prototype.once = function(event, fn) { this.many(event, 1, fn); return this; }; EventEmitter.prototype.many = function(event, ttl, fn) { var self = this; if (typeof fn !== 'function') { throw new Error('many only accepts instances of Function'); } function listener() { if (--ttl === 0) { self.off(event, listener); } fn.apply(this, arguments); }; listener._origin = fn; this.on(event, listener); return self; }; EventEmitter.prototype.emit = function() { this._events || init.call(this); var type = arguments[0]; if (type === 'newListener') { if (!this._events.newListener) { return false; } } // Loop through the *_all* functions and invoke them. if (this._all) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; for (i = 0, l = this._all.length; i < l; i++) { this.event = type; this._all[i].apply(this, args); } } // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._all && !this._events.error && !(this.wildcard && this.listenerTree.error)) { if (arguments[1] instanceof Error) { throw arguments[1]; // Unhandled 'error' event } else { throw new Error("Uncaught, unspecified 'error' event."); } return false; } } var handler; if(this.wildcard) { handler = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handler, ns, this.listenerTree, 0); } else { handler = this._events[type]; } if (typeof handler === 'function') { this.event = type; if (arguments.length === 1) { handler.call(this); } else if (arguments.length > 1) switch (arguments.length) { case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } return true; } else if (handler) { var l = arguments.length; var args = new Array(l - 1); for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; var listeners = handler.slice(); for (var i = 0, l = listeners.length; i < l; i++) { this.event = type; listeners[i].apply(this, args); } return (listeners.length > 0) || this._all; } else { return this._all; } }; EventEmitter.prototype.on = function(type, listener) { if (typeof type === 'function') { this.onAny(type); return this; } if (typeof listener !== 'function') { throw new Error('on only accepts instances of Function'); } this._events || init.call(this); // To avoid recursion in the case that type == "newListeners"! Before // adding it to the listeners, first emit "newListeners". this.emit('newListener', type, listener); if(this.wildcard) { growListenerTree.call(this, type, listener); return this; } if (!this._events[type]) { // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; } else if(typeof this._events[type] === 'function') { // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; } else if (isArray(this._events[type])) { // If we've already got an array, just append. this._events[type].push(listener); // Check for listener leak if (!this._events[type].warned) { var m = defaultMaxListeners; if (typeof this._events.maxListeners !== 'undefined') { m = this._events.maxListeners; } if (m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } } return this; }; EventEmitter.prototype.onAny = function(fn) { if(!this._all) { this._all = []; } if (typeof fn !== 'function') { throw new Error('onAny only accepts instances of Function'); } // Add the function to the event listener collection. this._all.push(fn); return this; }; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prototype.off = function(type, listener) { if (typeof listener !== 'function') { throw new Error('removeListener only takes instances of Function'); } var handlers,leafs=[]; if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); } else { // does not use listeners(), so no side effect of creating _events[type] if (!this._events[type]) return this; handlers = this._events[type]; leafs.push({_listeners:handlers}); } for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; handlers = leaf._listeners; if (isArray(handlers)) { var position = -1; for (var i = 0, length = handlers.length; i < length; i++) { if (handlers[i] === listener || (handlers[i].listener && handlers[i].listener === listener) || (handlers[i]._origin && handlers[i]._origin === listener)) { position = i; break; } } if (position < 0) { return this; } if(this.wildcard) { leaf._listeners.splice(position, 1) } else { this._events[type].splice(position, 1); } if (handlers.length === 0) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } else if (handlers === listener || (handlers.listener && handlers.listener === listener) || (handlers._origin && handlers._origin === listener)) { if(this.wildcard) { delete leaf._listeners; } else { delete this._events[type]; } } } return this; }; EventEmitter.prototype.offAny = function(fn) { var i = 0, l = 0, fns; if (fn && this._all && this._all.length > 0) { fns = this._all; for(i = 0, l = fns.length; i < l; i++) { if(fn === fns[i]) { fns.splice(i, 1); return this; } } } else { this._all = []; } return this; }; EventEmitter.prototype.removeListener = EventEmitter.prototype.off; EventEmitter.prototype.removeAllListeners = function(type) { if (arguments.length === 0) { !this._events || init.call(this); return this; } if(this.wildcard) { var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) { var leaf = leafs[iLeaf]; leaf._listeners = null; } } else { if (!this._events[type]) return this; this._events[type] = null; } return this; }; EventEmitter.prototype.listeners = function(type) { if(this.wildcard) { var handlers = []; var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); searchListenerTree.call(this, handlers, ns, this.listenerTree, 0); return handlers; } this._events || init.call(this); if (!this._events[type]) this._events[type] = []; if (!isArray(this._events[type])) { this._events[type] = [this._events[type]]; } return this._events[type]; }; EventEmitter.prototype.listenersAny = function() { if(this._all) { return this._all; } else { return []; } }; // if (typeof define === 'function' && define.amd) { // define('EventEmitter2', [], function() { // return EventEmitter; // }); // } else { exports.EventEmitter2 = EventEmitter; // } }(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window); /*! * F2 v1.3.1 10-15-2013 * Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org * * "F2" is 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. * * Please note that F2 ("Software") may contain third party material that Markit * On Demand Inc. has a license to use and include within the Software (the * "Third Party Material"). A list of the software comprising the Third Party Material * and the terms and conditions under which such Third Party Material is distributed * are reproduced in the ThirdPartyMaterial.md file available at: * * https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md * * The inclusion of the Third Party Material in the Software does not grant, provide * nor result in you having acquiring any rights whatsoever, other than as stipulated * in the terms and conditions related to the specific Third Party Material, if any. * */ var F2; /** * Open F2 * @module f2 * @main f2 */ F2 = (function() { /** * Abosolutizes a relative URL * @method _absolutizeURI * @private * @param {e.g., location.href} base * @param {URL to absolutize} href * @returns {string} URL * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _absolutizeURI = function(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = _parseURI(href || ''); base = _parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; }; /** * Parses URI * @method _parseURI * @private * @param {The URL to parse} url * @returns {Parsed URL} string * Source: https://gist.github.com/Yaffle/1088850 * Tests: http://skew.org/uri/uri_tests.html */ var _parseURI = function(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); }; return { /** * A function to pass into F2.stringify which will prevent circular * reference errors when serializing objects * @method appConfigReplacer */ appConfigReplacer: function(key, value) { if (key == 'root' || key == 'ui' || key == 'height') { return undefined; } else { return value; } }, /** * The apps namespace is a place for app developers to put the javascript * class that is used to initialize their app. The javascript classes should * be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId. * It is recommended that the code be placed in a closure to help keep the * global namespace clean. * * If the class has an 'init' function, that function will be called * automatically by F2. * @property Apps * @type object * @example * F2.Apps["com_example_helloworld"] = (function() { * var App_Class = function(appConfig, appContent, root) { * this._app = appConfig; // the F2.AppConfig object * this._appContent = appContent // the F2.AppManifest.AppContent object * this.$root = $(root); // the root DOM Element that contains this app * } * * App_Class.prototype.init = function() { * // perform init actions * } * * return App_Class; * })(); * @example * F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) { * return { * init:function() { * // perform init actions * } * }; * }; * @for F2 */ Apps: {}, /** * Creates a namespace on F2 and copies the contents of an object into * that namespace optionally overwriting existing properties. * @method extend * @param {string} ns The namespace to create. Pass a falsy value to * add properties to the F2 namespace directly. * @param {object} obj The object to copy into the namespace. * @param {bool} overwrite True if object properties should be overwritten * @return {object} The created object */ extend: function (ns, obj, overwrite) { var isFunc = typeof obj === 'function'; var parts = ns ? ns.split('.') : []; var parent = this; obj = obj || {}; // ignore leading global if (parts[0] === 'F2') { parts = parts.slice(1); } // create namespaces for (var i = 0, len = parts.length; i < len; i++) { if (!parent[parts[i]]) { parent[parts[i]] = isFunc && i + 1 == len ? obj : {}; } parent = parent[parts[i]]; } // copy object into namespace if (!isFunc) { for (var prop in obj) { if (typeof parent[prop] === 'undefined' || overwrite) { parent[prop] = obj[prop]; } } } return parent; }, /** * Generates a somewhat random id * @method guid * @return {string} A random id * @for F2 */ guid: function() { var S4 = function() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4()); }, /** * Search for a value within an array. * @method inArray * @param {object} value The value to search for * @param {Array} array The array to search * @return {bool} True if the item is in the array */ inArray: function(value, array) { return jQuery.inArray(value, array) > -1; }, /** * Tests a URL to see if it's on the same domain (local) or not * @method isLocalRequest * @param {URL to test} url * @returns {bool} Whether the URL is local or not * Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js */ isLocalRequest: function(url){ var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, urlLower = url.toLowerCase(), parts = rurl.exec( urlLower ), ajaxLocation, ajaxLocParts; try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement('a'); ajaxLocation.href = ''; ajaxLocation = ajaxLocation.href; } ajaxLocation = ajaxLocation.toLowerCase(); // uh oh, the url must be relative // make it fully qualified and re-regex url if (!parts){ urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase(); parts = rurl.exec( urlLower ); } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation ) || []; // do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain) var matched = !(parts && (parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || (parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !== (ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443')))); return matched; }, /** * Utility method to determine whether or not the argument passed in is or is not a native dom node. * @method isNativeDOMNode * @param {object} testObject The object you want to check as native dom node. * @return {bool} Returns true if the object passed is a native dom node. */ isNativeDOMNode: function(testObject) { var bIsNode = ( typeof Node === 'object' ? testObject instanceof Node : testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string' ); var bIsElement = ( typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2 testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string' ); return (bIsNode || bIsElement); }, /** * A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console). * @method log * @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api). * @param {object} [obj2]* An object to be logged * @example //Pass any object (string, int, array, object, bool) to .log() F2.log('foo'); F2.log(myArray); //Use a console method name as the first argument. F2.log('error', err); F2.log('info', 'The session ID is ' + sessionId); * Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js) */ log: function() { var _log; var _logMethod = 'log'; var method; var noop = function () { }; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); var args; while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } //if first arg is a console function, use it. //defaults to console.log() if (arguments && arguments.length > 1 && arguments[0] == method){ _logMethod = method; //remove console func from args args = Array.prototype.slice.call(arguments, 1); } } if (Function.prototype.bind) { _log = Function.prototype.bind.call(console[_logMethod], console); } else { _log = function() { Function.prototype.apply.call(console[_logMethod], console, (args || arguments)); }; } _log.apply(this, (args || arguments)); }, /** * Wrapper to convert a JSON string to an object * @method parse * @param {string} str The JSON string to convert * @return {object} The parsed object */ parse: function(str) { return JSON.parse(str); }, /** * Wrapper to convert an object to JSON * * **Note: When using F2.stringify on an F2.AppConfig object, it is * recommended to pass F2.appConfigReplacer as the replacer function in * order to prevent circular serialization errors.** * @method stringify * @param {object} value The object to convert * @param {function|Array} replacer An optional parameter that determines * how object values are stringified for objects. It can be a function or an * array of strings. * @param {int|string} space An optional parameter that specifies the * indentation of nested structures. If it is omitted, the text will be * packed without extra whitespace. If it is a number, it will specify the * number of spaces to indent at each level. If it is a string (such as '\t' * or '&nbsp;'), it contains the characters used to indent at each level. * @return {string} The JSON string */ stringify: function(value, replacer, space) { return JSON.stringify(value, replacer, space); }, /** * Function to get the F2 version number * @method version * @return {string} F2 version number */ version: function() { return '{{sdk.version}}'; } }; })(); /** * The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction. * *<p class="alert alert-block alert-warning"> *The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated&mdash;but not removed&mdash;in version 1.2. They will be permanently removed in a future version of F2. *</p> * *<p class="alert alert-block alert-info"> *Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout. *</p> * * ### Order of Execution * * **App Rendering** * * 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed. * 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached. * 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached. * 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired. * 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached. * 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached. * * * **App Removal** * 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run. * 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached. * 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached. * 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached. * * **Error Handling** * 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached. * * @class F2.AppHandlers */ F2.extend('AppHandlers', (function() { // the hidden token that we will check against every time someone tries to add, remove, fire handler var _ct = F2.guid(); var _f2t = F2.guid(); var _handlerCollection = { appCreateRoot: [], appRenderBefore: [], appDestroyBefore: [], appRenderAfter: [], appDestroyAfter: [], appRender: [], appDestroy: [], appScriptLoadFailed: [] }; var _defaultMethods = { appRender: function(appConfig, appHtml) { var $root = null; // if no app root is defined use the app's outer most node if(!F2.isNativeDOMNode(appConfig.root)) { appConfig.root = jQuery(appHtml).get(0); // get a handle on the root in jQuery $root = jQuery(appConfig.root); } else { // get a handle on the root in jQuery $root = jQuery(appConfig.root); // append the app html to the root $root.append(appHtml); } // append the root to the body by default. jQuery('body').append($root); }, appDestroy: function(appInstance) { // call the apps destroy method, if it has one if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') { appInstance.app.destroy(); } // warn the Container and App Developer that even though they have a destroy method it hasn't been else if(appInstance && appInstance.app && appInstance.app.destroy) { F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); } // fade out and remove the root jQuery(appInstance.config.root).fadeOut(500, function() { jQuery(this).remove(); }); } }; var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate) { // will throw an exception and stop execution if the token is invalid _validateToken(token); // create handler structure. Not all arguments properties will be populated/used. var handler = { func: (typeof(func_or_element)) ? func_or_element : null, namespace: sNamespace, domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null }; if(!handler.func && !handler.domNode) { throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.'); } if(handler.domNode && !bDomNodeAppropriate) { throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.'); } return handler; }; var _validateToken = function(sToken) { // check token against F2 and container if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); } }; var _removeHandler = function(sToken, eventKey, sNamespace) { // will throw an exception and stop execution if the token is invalid _validateToken(sToken); if(!sNamespace && !eventKey) { return; } // remove by event key else if(!sNamespace && eventKey) { _handlerCollection[eventKey] = []; } // remove by namespace only else if(sNamespace && !eventKey) { sNamespace = sNamespace.toLowerCase(); for(var currentEventKey in _handlerCollection) { var eventCollection = _handlerCollection[currentEventKey]; var newEvents = []; for(var i = 0, ec = eventCollection.length; i < ec; i++) { var currentEventHandler = eventCollection[i]; if(currentEventHandler) { if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace) { newEvents.push(currentEventHandler); } } } eventCollection = newEvents; } } else if(sNamespace && _handlerCollection[eventKey]) { sNamespace = sNamespace.toLowerCase(); var newHandlerCollection = []; for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++) { var currentHandler = _handlerCollection[eventKey][iCounter]; if(currentHandler) { if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace) { newHandlerCollection.push(currentHandler); } } } _handlerCollection[eventKey] = newHandlerCollection; } }; return { /** * Allows Container Developer to retrieve a unique token which must be passed to * all `on` and `off` methods. This function will self destruct and can only be called * one time. Container Developers must store the return value inside of a closure. * @method getToken **/ getToken: function() { // delete this method for security that way only the container has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.getToken; // return the token, which we validate against. return _ct; }, /** * Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}. * This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}} * and additional internal methods. * @method __f2GetToken * @private **/ __f2GetToken: function() { // delete this method for security that way only the F2 internally has access to the token 1 time. // kind of Ethan Hunt-ish, this message will self destruct immediately. delete this.__f2GetToken; // return the token, which we validate against. return _f2t; }, /** * Allows F2 to trigger specific events internally. * @method __trigger * @private * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}. * @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. **/ __trigger: function(token, eventKey) // additional arguments will likely be passed { // will throw an exception and stop execution if the token is invalid if(token != _f2t) { throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().'); } if(_handlerCollection && _handlerCollection[eventKey]) { // create a collection of arguments that are safe to pass to the callback. var passableArgs = []; // populate that collection with all arguments except token and eventKey for(var i = 2, j = arguments.length; i < j; i++) { passableArgs.push(arguments[i]); } if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey]) { _defaultMethods[eventKey].apply(F2, passableArgs); return this; } else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey]) { return this; } // fire all event listeners in the order that they were added. for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++) { var handler = _handlerCollection[eventKey][iCounter]; // appRender where root is already defined if (handler.domNode && arguments[2] && arguments[2].root && arguments[3]) { var $appRoot = jQuery(arguments[2].root).append(arguments[3]); jQuery(handler.domNode).append($appRoot); } else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3]) { // set the root to the actual HTML of the app arguments[2].root = jQuery(arguments[3]).get(0); // appends the root to the dom node specified jQuery(handler.domNode).append(arguments[2].root); } else { handler.func.apply(F2, passableArgs); } } } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {HTMLElement} element Specific DOM element to which app gets appended. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRender', * document.getElementById('my_app') * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRender.myNamespace', * document.getElementById('my_app') * ); **/ /** * Allows Container Developer to add listener method that will be triggered when a specific event occurs. * @method on * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * 'appRenderBefore' * function() { F2.log('before app rendered!'); } * ); * * Or: * @example * F2.AppHandlers.on( * _token, * 'appRenderBefore.myNamespace', * function() { F2.log('before app rendered!'); } * ); **/ on: function(token, eventKey, func_or_element) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _handlerCollection[eventKey].push( _createHandler( token, sNamespace, func_or_element, (eventKey == 'appRender') ) ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; }, /** * Allows Container Developer to remove listener methods for specific events * @method off * @chainable * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all * listeners for the specified event type will be removed. * Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.off(_token,'appRenderBefore'); * **/ off: function(token, eventKey) { var sNamespace = null; if(!eventKey) { throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); } // we need to check the key for a namespace if(eventKey.indexOf('.') > -1) { var arData = eventKey.split('.'); eventKey = arData[0]; sNamespace = arData[1]; } if(_handlerCollection && _handlerCollection[eventKey]) { _removeHandler( token, eventKey, sNamespace ); } else { throw ('Invalid EventKey passed. Check your inputs and try again.'); } return this; } }; })()); F2.extend('Constants', { /** * A convenient collection of all available appHandler events. * @class F2.Constants.AppHandlers **/ AppHandlers: (function() { return { /** * Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_CREATE_ROOT * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_CREATE_ROOT, * function(appConfig) * { * // If you want to create a custom root. By default F2 uses the app's outermost HTML element. * // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER * appConfig.root = jQuery('<section></section>').get(0); * } * ); */ APP_CREATE_ROOT: 'appCreateRoot', /** * Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_BEFORE, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_BEFORE: 'appRenderBefore', /** * Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) ) * @property APP_RENDER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER, * function(appConfig, appHtml) * { * var $root = null; * * // if no app root is defined use the app's outer most node * if(!F2.isNativeDOMNode(appConfig.root)) * { * appConfig.root = jQuery(appHtml).get(0); * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * } * else * { * // get a handle on the root in jQuery * $root = jQuery(appConfig.root); * * // append the app html to the root * $root.append(appHtml); * } * * // append the root to the body by default. * jQuery('body').append($root); * } * ); */ APP_RENDER: 'appRender', /** * Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) * @property APP_RENDER_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_RENDER_AFTER, * function(appConfig) * { * F2.log(appConfig); * } * ); */ APP_RENDER_AFTER: 'appRenderAfter', /** * Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_BEFORE * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_BEFORE, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_BEFORE: 'appDestroyBefore', /** * Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY, * function(appInstance) * { * // call the apps destroy method, if it has one * if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') * { * appInstance.app.destroy(); * } * else if(appInstance && appInstance.app && appInstance.app.destroy) * { * F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); * } * * // fade out and remove the root * jQuery(appInstance.config.root).fadeOut(500, function() { * jQuery(this).remove(); * }); * } * ); */ APP_DESTROY: 'appDestroy', /** * Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( appInstance ) * @property APP_DESTROY_AFTER * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_DESTROY_AFTER, * function(appInstance) * { * F2.log(appInstance); * } * ); */ APP_DESTROY_AFTER: 'appDestroyAfter', /** * Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off. * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo ) * @property APP_SCRIPT_LOAD_FAILED * @type string * @static * @final * @example * var _token = F2.AppHandlers.getToken(); * F2.AppHandlers.on( * _token, * F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, * function(appConfig, scriptInfo) * { * F2.log(appConfig.appId); * } * ); */ APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed' }; })() }); /** * Class stubs for documentation purposes * @main F2 */ F2.extend('', { /** * The App Class is an optional class that can be namespaced onto the * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The * [F2 Docs](../../app-development.html#app-class) * has more information on the usage of the App Class. * @class F2.App * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object for the app * @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent * object * @param {Element} root The root DOM Element for the app */ App: function(appConfig, appContent, root) { return { /** * An optional init function that will automatically be called when * F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called. * @method init * @optional */ init:function() {} }; }, /** * The AppConfig object represents an app's meta data * @class F2.AppConfig */ AppConfig: { /** * The unique ID of the app. More information can be found * [here](../../app-development.html#f2-appid) * @property appId * @type string * @required */ appId: '', /** * An object that represents the context of an app * @property context * @type object */ context: {}, /** * True if the app should be requested in a single request with other apps. * @property enableBatchRequests * @type bool * @default false */ enableBatchRequests: false, /** * The height of the app. The initial height will be pulled from * the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later * modified by calling * F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used * for secure apps to be able to set the initial height of the iframe. * @property height * @type int */ height: 0, /** * The unique runtime ID of the app. * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property instanceId * @type string */ instanceId: '', /** * True if the app will be loaded in an iframe. This property * will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object * sets isSecure = true. It will also be true if the * [container](../../container-development.html) has made the decision to * run apps in iframes. * @property isSecure * @type bool * @default false */ isSecure: false, /** * The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}} * object. * @property manifestUrl * @type string * @required */ manifestUrl: '', /** * The recommended maximum width in pixels that this app should be run. * **It is up to the [container](../../container-development.html) to * implement the logic to prevent an app from being run when the maxWidth * requirements are not met.** * @property maxWidth * @type int */ maxWidth: 0, /** * The recommended minimum grid size that this app should be run. This * value corresponds to the 12-grid system that is used by the * [container](../../container-development.html). This property should be * set by apps that require a certain number of columns in their layout. * @property minGridSize * @type int * @default 4 */ minGridSize: 4, /** * The recommended minimum width in pixels that this app should be run. **It * is up to the [container](../../container-development.html) to implement * the logic to prevent an app from being run when the minWidth requirements * are not met. * @property minWidth * @type int * @default 300 */ minWidth: 300, /** * The name of the app * @property name * @type string * @required */ name: '', /** * The root DOM element that contains the app * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property root * @type Element */ root: undefined, /** * The instance of F2.UI providing easy access to F2.UI methods * * **This property is populated during the * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** * @property ui * @type F2.UI */ ui: undefined, /** * The views that this app supports. Available views * are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The * presence of a view can be checked via * F2.{{#crossLink "F2/inArray"}}{{/crossLink}}: * * F2.inArray(F2.Constants.Views.SETTINGS, app.views) * * @property views * @type Array */ views: [] }, /** * The assets needed to render an app on the page * @class F2.AppManifest */ AppManifest: { /** * The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}} * objects * @property apps * @type Array * @required */ apps: [], /** * Any inline javascript tha should initially be run * @property inlineScripts * @type Array * @optional */ inlineScripts: [], /** * Urls to javascript files required by the app * @property scripts * @type Array * @optional */ scripts: [], /** * Urls to CSS files required by the app * @property styles * @type Array * @optional */ styles: [] }, /** * The AppContent object * @class F2.AppManifest.AppContent **/ AppContent: { /** * Arbitrary data to be passed along with the app * @property data * @type object * @optional */ data: {}, /** * The string of HTML representing the app * @property html * @type string * @required */ html: '', /** * A status message * @property status * @type string * @optional */ status: '' }, /** * An object containing configuration information for the * [container](../../container-development.html) * @class F2.ContainerConfig */ ContainerConfig: { /** * Allows the [container](../../container-development.html) to override how * an app's html is inserted into the page. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html * @method afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app * @return {Element} The DOM Element surrounding the app */ afterAppRender: function(appConfig, html) {}, /** * Allows the [container](../../container-development.html) to wrap an app * in extra html. The function should accept an * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of * html. The extra html can provide links to edit app settings and remove an * app from the container. See * {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that * should be applied to elements. * @method appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html representing the app */ appRender: function(appConfig, html) {}, /** * Allows the container to render html for an app before the AppManifest for * an app has loaded. This can be useful if the design calls for loading * icons to appear for each app before each app is loaded and rendered to * the page. * @method beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ beforeAppRender: function(appConfig) {}, /** * True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc. * @property debugMode * @type bool * @default false */ debugMode: false, /** * Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire. * @property scriptErrorTimeout * @type milliseconds * @default 7000 (7 seconds) */ scriptErrorTimeout: 7000, /** * Tells the container that it is currently running within * a secure app page * @property isSecureAppPage * @type bool */ isSecureAppPage: false, /** * Allows the container to specify which page is used when * loading a secure app. The page must reside on a different domain than the * container * @property secureAppPagePath * @type string * @for F2.ContainerConfig */ secureAppPagePath: '', /** * Specifies what views a container will provide buttons * or links to. Generally, the views will be switched via buttons or links * in the app's header. * @property supportedViews * @type Array * @required */ supportedViews: [], /** * An object containing configuration defaults for F2.UI * @class F2.ContainerConfig.UI */ UI: { /** * An object containing configuration defaults for the * F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and * F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods. * @class F2.ContainerConfig.UI.Mask */ Mask: { /** * The backround color of the overlay * @property backgroundColor * @type string * @default #FFF */ backgroundColor: '#FFF', /** * The path to the loading icon * @property loadingIcon * @type string */ loadingIcon: '', /** * The opacity of the background overlay * @property opacity * @type int * @default 0.6 */ opacity: 0.6, /** * Do not use inline styles for mask functinality. Instead classes will * be applied to the elements and it is up to the container provider to * implement the class definitions. * @property useClasses * @type bool * @default false */ useClasses: false, /** * The z-index to use for the overlay * @property zIndex * @type int * @default 2 */ zIndex: 2 } }, /** * Allows the container to fully override how the AppManifest request is * made inside of F2. * * @method xhr * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {function} success The function to be called if the request * succeeds * @param {function} error The function to be called if the request fails * @param {function} complete The function to be called when the request * finishes (after success and error callbacks have been executed) * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has * an `abort` function (such as the jqXHR object in jQuery) to abort the * request) * * @example * F2.init({ * xhr: function(url, appConfigs, success, error, complete) { * $.ajax({ * url: url, * type: 'POST', * data: { * params: F2.stringify(appConfigs, F2.appConfigReplacer) * }, * jsonp: false, // do not put 'callback=' in the query string * jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name * dataType: 'json', * success: function(appManifest) { * // custom success logic * success(appManifest); // fire success callback * }, * error: function() { * // custom error logic * error(); // fire error callback * }, * complete: function() { * // custom complete logic * complete(); // fire complete callback * } * }); * } * }); * * @for F2.ContainerConfig */ //xhr: function(url, appConfigs, success, error, complete) {}, /** * Allows the container to override individual parts of the AppManifest * request. See properties and methods with the `xhr.` prefix. * @property xhr * @type Object * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ xhr: { /** * Allows the container to override the request data type (JSON or JSONP) * that is used for the request * @method xhr.dataType * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request data type that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ dataType: function(url, appConfigs) {}, /** * Allows the container to override the request method that is used (just * like the `type` parameter to `jQuery.ajax()`. * @method xhr.type * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The request method that should be used * * @example * F2.init({ * xhr: { * dataType: function(url) { * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; * }, * type: function(url) { * return F2.isLocalRequest(url) ? 'POST' : 'GET'; * } * } * }); */ type: function(url, appConfigs) {}, /** * Allows the container to override the url that is used to request an * app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}} * @method xhr.url * @param {string} url The manifest url * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @return {string} The url that should be used for the request * * @example * F2.init({ * xhr: { * url: function(url, appConfigs) { * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); * } * } * }); */ url: function(url, appConfigs) {} } } }); /** * Constants used throughout the Open Financial Framework * @class F2.Constants * @static */ F2.extend('Constants', { /** * CSS class constants * @class F2.Constants.Css */ Css: (function() { /** @private */ var _PREFIX = 'f2-'; return { /** * The APP class should be applied to the DOM Element that surrounds the * entire app, including any extra html that surrounds the APP\_CONTAINER * that is inserted by the container. See the * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object. * @property APP * @type string * @static * @final */ APP: _PREFIX + 'app', /** * The APP\_CONTAINER class should be applied to the outermost DOM Element * of the app. * @property APP_CONTAINER * @type string * @static * @final */ APP_CONTAINER: _PREFIX + 'app-container', /** * The APP\_TITLE class should be applied to the DOM Element that contains * the title for an app. If this class is not present, then * F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function. * @property APP_TITLE * @type string * @static * @final */ APP_TITLE: _PREFIX + 'app-title', /** * The APP\_VIEW class should be applied to the DOM Element that contains * a view for an app. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is. * @property APP_VIEW * @type string * @static * @final */ APP_VIEW: _PREFIX + 'app-view', /** * APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that * trigger an * {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE * event. The DOM Element should also have a * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE * attribute that specifies which * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger. * @property APP_VIEW_TRIGGER * @type string * @static * @final */ APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger', /** * The MASK class is applied to the overlay element that is created * when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is * fired. * @property MASK * @type string * @static * @final */ MASK: _PREFIX + 'mask', /** * The MASK_CONTAINER class is applied to the Element that is passed into * the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method. * @property MASK_CONTAINER * @type string * @static * @final */ MASK_CONTAINER: _PREFIX + 'mask-container' }; })(), /** * Events constants * @class F2.Constants.Events */ Events: (function() { /** @private */ var _APP_EVENT_PREFIX = 'App.'; /** @private */ var _CONTAINER_EVENT_PREFIX = 'Container.'; return { /** * The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an * app. It is up to the app developer to fire this event. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property APP_SYMBOL_CHANGE * @type string * @static * @final */ APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange', /** * The APP\_WIDTH\_CHANGE event will be fired by the container when the * width of an app is changed. The app's instanceId should be concatenated * to this constant. * Returns an object with the gridSize and width in pixels: * * { gridSize:8, width:620 } * * @property APP_WIDTH_CHANGE * @type string * @static * @final */ APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.', /** * The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed * at the container level. This event should only be fired by the * container or container provider. * Returns an object with the symbol and company name: * * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } * * @property CONTAINER_SYMBOL_CHANGE * @type string * @static * @final */ CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange', /** * The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when * the width of the container has changed. * @property CONTAINER_WIDTH_CHANGE * @type string * @static * @final */ CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange' }; })(), JSONP_CALLBACK: 'F2_jsonpCallback_', /** * Constants for use with cross-domain sockets * @class F2.Constants.Sockets * @protected */ Sockets: { /** * The EVENT message is sent whenever * F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired * @property EVENT * @type string * @static * @final */ EVENT: '__event__', /** * The LOAD message is sent when an iframe socket initially loads. * Returns a JSON string that represents: * * [ App, AppManifest] * * @property LOAD * @type string * @static * @final */ LOAD: '__socketLoad__', /** * The RPC message is sent when a method is passed up from within a secure * app page. * @property RPC * @type string * @static * @final */ RPC: '__rpc__', /** * The RPC\_CALLBACK message is sent when a call back from an RPC method is * fired. * @property RPC_CALLBACK * @type string * @static * @final */ RPC_CALLBACK: '__rpcCallback__', /** * The UI\_RPC message is sent when a UI method called. * @property UI_RPC * @type string * @static * @final */ UI_RPC: '__uiRpc__' }, /** * The available view types to apps. The view should be specified by applying * the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the * containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the * Element as well which defines what view type is represented. * The `hide` class can be applied to views that should be hidden by default. * @class F2.Constants.Views */ Views: { /** * The DATA_ATTRIBUTE should be placed on the DOM Element that contains the * view. * @property DATA_ATTRIBUTE * @type string * @static * @final */ DATA_ATTRIBUTE: 'data-f2-view', /** * The ABOUT view gives details about the app. * @property ABOUT * @type string * @static * @final */ ABOUT: 'about', /** * The HELP view provides users with help information for using an app. * @property HELP * @type string * @static * @final */ HELP: 'help', /** * The HOME view is the main view for an app. This view should always * be provided by an app. * @property HOME * @type string * @static * @final */ HOME: 'home', /** * The REMOVE view is a special view that handles the removal of an app * from the container. * @property REMOVE * @type string * @static * @final */ REMOVE: 'remove', /** * The SETTINGS view provides users the ability to modify advanced settings * for an app. * @property SETTINGS * @type string * @static * @final */ SETTINGS: 'settings' } }); /** * Handles [Context](../../app-development.html#context) passing from * containers to apps and apps to apps. * @class F2.Events */ F2.extend('Events', (function() { // init EventEmitter var _events = new EventEmitter2({ wildcard:true }); // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); return { /** * Same as F2.Events.emit except that it will not send the event * to all sockets. * @method _socketEmit * @private * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ _socketEmit: function() { return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Execute each of the listeners that may be listening for the specified * event name in order with the list of arguments. * @method emit * @param {string} event The event name * @param {object} [arg]* The arguments to be passed */ emit: function() { F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments)); return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); }, /** * Adds a listener that will execute n times for the event before being * removed. The listener is invoked only the first time the event is * fired, after which it is removed. * @method many * @param {string} event The event name * @param {int} timesToListen The number of times to execute the event * before being removed * @param {function} listener The function to be fired when the event is * emitted */ many: function(event, timesToListen, listener) { return _events.many(event, timesToListen, listener); }, /** * Remove a listener for the specified event. * @method off * @param {string} event The event name * @param {function} listener The function that will be removed */ off: function(event, listener) { return _events.off(event, listener); }, /** * Adds a listener for the specified event * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ on: function(event, listener){ return _events.on(event, listener); }, /** * Adds a one time listener for the event. The listener is invoked only * the first time the event is fired, after which it is removed. * @method once * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted */ once: function(event, listener) { return _events.once(event, listener); } }; })()); /** * Handles socket communication between the container and secure apps * @class F2.Rpc */ F2.extend('Rpc', (function(){ var _callbacks = {}; var _secureAppPagePath = ''; var _apps = {}; var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT); var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC); var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK); var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD); var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC); /** * Creates a socket connection from the app to the container using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createAppToContainerSocket * @private */ var _createAppToContainerSocket = function() { var appConfig; // socket closure var isLoaded = false; // its possible for messages to be received before the socket load event has // happened. We'll save off these messages and replay them once the socket // is ready var messagePlayback = []; var socket = new easyXDM.Socket({ onMessage: function(message, origin){ // handle Socket Load if (!isLoaded && _rSocketLoad.test(message)) { message = message.replace(_rSocketLoad, ''); var appParts = F2.parse(message); // make sure we have the AppConfig and AppManifest if (appParts.length == 2) { appConfig = appParts[0]; // save socket _apps[appConfig.instanceId] = { config:appConfig, socket:socket }; // register app F2.registerApps([appConfig], [appParts[1]]); // socket message playback jQuery.each(messagePlayback, function(i, e) { _onMessage(appConfig, message, origin); }); isLoaded = true; } } else if (isLoaded) { // pass everyting else to _onMessage _onMessage(appConfig, message, origin); } else { //F2.log('socket not ready, queuing message', message); messagePlayback.push(message); } } }); }; /** * Creates a socket connection from the container to the app using * <a href="http://easyxdm.net" target="_blank">easyXDM</a>. * @method _createContainerToAppSocket * @private * @param {appConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The F2.AppManifest object */ var _createContainerToAppSocket = function(appConfig, appManifest) { var container = jQuery(appConfig.root); if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) { container.find('.' + F2.Constants.Css.APP_CONTAINER); } if (!container.length) { F2.log('Unable to locate app in order to establish secure connection.'); return; } var iframeProps = { scrolling:'no', style:{ width:'100%' } }; if (appConfig.height) { iframeProps.style.height = appConfig.height + 'px'; } var socket = new easyXDM.Socket({ remote: _secureAppPagePath, container: container.get(0), props:iframeProps, onMessage: function(message, origin) { // pass everything to _onMessage _onMessage(appConfig, message, origin); }, onReady: function() { socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer)); } }); return socket; }; /** * @method _createRpcCallback * @private * @param {string} instanceId The app's Instance ID * @param {function} callbackId The callback ID * @return {function} A function to make the RPC call */ var _createRpcCallback = function(instanceId, callbackId) { return function() { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC_CALLBACK, callbackId, [].slice.call(arguments).slice(2) ); }; }; /** * Handles messages that come across the sockets * @method _onMessage * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} message The socket message * @param {string} origin The originator */ var _onMessage = function(appConfig, message, origin) { var obj, func; function parseFunction(parent, functionName) { var path = String(functionName).split('.'); for (var i = 0; i < path.length; i++) { if (parent[path[i]] === undefined) { parent = undefined; break; } parent = parent[path[i]]; } return parent; } function parseMessage(regEx, message, instanceId) { var o = F2.parse(message.replace(regEx, '')); // if obj.callbacks // for each callback // for each params // if callback matches param // replace param with _createRpcCallback(app.instanceId, callback) if (o.params && o.params.length && o.callbacks && o.callbacks.length) { jQuery.each(o.callbacks, function(i, c) { jQuery.each(o.params, function(i, p) { if (c == p) { o.params[i] = _createRpcCallback(instanceId, c); } }); }); } return o; } // handle UI Call if (_rUiCall.test(message)) { obj = parseMessage(_rUiCall, message, appConfig.instanceId); func = parseFunction(appConfig.ui, obj.functionName); // if we found the function, call it if (func !== undefined) { func.apply(appConfig.ui, obj.params); } else { F2.log('Unable to locate UI RPC function: ' + obj.functionName); } // handle RPC } else if (_rRpc.test(message)) { obj = parseMessage(_rRpc, message, appConfig.instanceId); func = parseFunction(window, obj.functionName); if (func !== undefined) { func.apply(func, obj.params); } else { F2.log('Unable to locate RPC function: ' + obj.functionName); } // handle RPC Callback } else if (_rRpcCallback.test(message)) { obj = parseMessage(_rRpcCallback, message, appConfig.instanceId); if (_callbacks[obj.functionName] !== undefined) { _callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params); delete _callbacks[obj.functionName]; } // handle Events } else if (_rEvents.test(message)) { obj = parseMessage(_rEvents, message, appConfig.instanceId); F2.Events._socketEmit.apply(F2.Events, obj); } }; /** * Registers a callback function * @method _registerCallback * @private * @param {function} callback The callback function * @return {string} The callback ID */ var _registerCallback = function(callback) { var callbackId = F2.guid(); _callbacks[callbackId] = callback; return callbackId; }; return { /** * Broadcast an RPC function to all sockets * @method broadcast * @param {string} messageType The message type * @param {Array} params The parameters to broadcast */ broadcast: function(messageType, params) { // check valid messageType var message = messageType + F2.stringify(params); jQuery.each(_apps, function(i, a) { a.socket.postMessage(message); }); }, /** * Calls a remote function * @method call * @param {string} instanceId The app's Instance ID * @param {string} messageType The message type * @param {string} functionName The name of the remote function * @param {Array} params An array of parameters to pass to the remote * function. Any functions found within the params will be treated as a * callback function. */ call: function(instanceId, messageType, functionName, params) { // loop through params and find functions and convert them to callbacks var callbacks = []; jQuery.each(params, function(i, e) { if (typeof e === 'function') { var cid = _registerCallback(e); params[i] = cid; callbacks.push(cid); } }); // check valid messageType _apps[instanceId].socket.postMessage( messageType + F2.stringify({ functionName:functionName, params:params, callbacks:callbacks }) ); }, /** * Init function which tells F2.Rpc whether it is running at the container- * level or the app-level. This method is generally called by * F2.{{#crossLink "F2/init"}}{{/crossLink}} * @method init * @param {string} [secureAppPagePath] The * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath * property */ init: function(secureAppPagePath) { _secureAppPagePath = secureAppPagePath; if (!_secureAppPagePath) { _createAppToContainerSocket(); } }, /** * Determines whether the Instance ID is considered to be 'remote'. This is * determined by checking if 1) the app has an open socket and 2) whether * F2.Rpc is running inside of an iframe * @method isRemote * @param {string} instanceId The Instance ID * @return {bool} True if there is an open socket */ isRemote: function(instanceId) { return ( // we have an app _apps[instanceId] !== undefined && // the app is secure _apps[instanceId].config.isSecure && // we can't access the iframe jQuery(_apps[instanceId].config.root).find('iframe').length === 0 ); }, /** * Creates a container-to-app or app-to-container socket for communication * @method register * @param {F2.AppConfig} [appConfig] The F2.AppConfig object * @param {F2.AppManifest} [appManifest] The F2.AppManifest object */ register: function(appConfig, appManifest) { if (!!appConfig && !!appManifest) { _apps[appConfig.instanceId] = { config:appConfig, socket:_createContainerToAppSocket(appConfig, appManifest) }; } else { F2.log('Unable to register socket connection. Please check container configuration.'); } } }; })()); F2.extend('UI', (function(){ var _containerConfig; /** * UI helper methods * @class F2.UI * @constructor * @param {F2.AppConfig} appConfig The F2.AppConfig object */ var UI_Class = function(appConfig) { var _appConfig = appConfig; var $root = jQuery(appConfig.root); var _updateHeight = function(height) { height = height || jQuery(_appConfig.root).outerHeight(); if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'updateHeight', [ height ] ); } else { _appConfig.height = height; $root.find('iframe').height(_appConfig.height); } }; return { /** * Removes a overlay from an Element on the page * @method hideMask * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader */ hideMask: function(selector) { F2.UI.hideMask(_appConfig.instanceId, selector); }, /** * Helper methods for creating and using Modals * @class F2.UI.Modals * @for F2.UI */ Modals: (function(){ var _renderAlert = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Alert!</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button class="btn btn-primary btn-ok">OK</button>', '</div>', '</div>' ].join(''); }; var _renderConfirm = function(message) { return [ '<div class="modal">', '<header class="modal-header">', '<h3>Confirm</h3>', '</header>', '<div class="modal-body">', '<p>', message, '</p>', '</div>', '<div class="modal-footer">', '<button type="button" class="btn btn-primary btn-ok">OK</button>', '<button type="button" class="btn btn-cancel">Cancel</button">', '</div>', '</div>' ].join(''); }; return { /** * Display an alert message on the page * @method alert * @param {string} message The message to be displayed * @param {function} [callback] The callback to be fired when the user * closes the dialog * @for F2.UI.Modals */ alert: function(message, callback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.alert()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.alert', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderAlert(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-primary').on('click', function() { jQuery(modal).modal('hide').remove(); (callback || jQuery.noop)(); }); }) .modal({backdrop:true}); } }, /** * Display a confirm message on the page * @method confirm * @param {string} message The message to be displayed * @param {function} okCallback The function that will be called when the OK * button is pressed * @param {function} cancelCallback The function that will be called when * the Cancel button is pressed * @for F2.UI.Modals */ confirm: function(message, okCallback, cancelCallback) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.Modals.confirm()'); return; } if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Modals.confirm', [].slice.call(arguments) ); } else { // display the alert jQuery(_renderConfirm(message)) .on('show', function() { var modal = this; jQuery(modal).find('.btn-ok').on('click', function() { jQuery(modal).modal('hide').remove(); (okCallback || jQuery.noop)(); }); jQuery(modal).find('.btn-cancel').on('click', function() { jQuery(modal).modal('hide').remove(); (cancelCallback || jQuery.noop)(); }); }) .modal({backdrop:true}); } } }; })(), /** * Sets the title of the app as shown in the browser. Depending on the * container HTML, this method may do nothing if the container has not been * configured properly or else the container provider does not allow Title's * to be set. * @method setTitle * @params {string} title The title of the app * @for F2.UI */ setTitle: function(title) { if (F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'setTitle', [ title ] ); } else { jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title); } }, /** * Display an ovarlay over an Element on the page * @method showMask * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ showMask: function(selector, showLoader) { F2.UI.showMask(_appConfig.instanceId, selector, showLoader); }, /** * For secure apps, this method updates the size of the iframe that * contains the app. **Note: It is recommended that app developers call * this method anytime Elements are added or removed from the DOM** * @method updateHeight * @params {int} height The height of the app */ updateHeight: _updateHeight, /** * Helper methods for creating and using Views * @class F2.UI.Views * @for F2.UI */ Views: (function(){ var _events = new EventEmitter2(); var _rValidEvents = /change/i; // unlimited listeners, set to > 0 for debugging _events.setMaxListeners(0); var _isValid = function(eventName) { if (_rValidEvents.test(eventName)) { return true; } else { F2.log('"' + eventName + '" is not a valid F2.UI.Views event name'); return false; } }; return { /** * Change the current view for the app or add an event listener * @method change * @param {string|function} [input] If a string is passed in, the view * will be changed for the app. If a function is passed in, a change * event listener will be added. * @for F2.UI.Views */ change: function(input) { if (typeof input === 'function') { this.on('change', input); } else if (typeof input === 'string') { if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) { F2.Rpc.call( _appConfig.instanceId, F2.Constants.Sockets.UI_RPC, 'Views.change', [].slice.call(arguments) ); } else if (F2.inArray(input, _appConfig.views)) { jQuery('.' + F2.Constants.Css.APP_VIEW, $root) .addClass('hide') .filter('[data-f2-view="' + input + '"]', $root) .removeClass('hide'); _updateHeight(); _events.emit('change', input); } } }, /** * Removes a view event listener * @method off * @param {string} event The event name * @param {function} listener The function that will be removed * @for F2.UI.Views */ off: function(event, listener) { if (_isValid(event)) { _events.off(event, listener); } }, /** * Adds a view event listener * @method on * @param {string} event The event name * @param {function} listener The function to be fired when the event is * emitted * @for F2.UI.Views */ on: function(event, listener) { if (_isValid(event)) { _events.on(event, listener); } } }; })() }; }; /** * Removes a overlay from an Element on the page * @method hideMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * that currently contains the loader * @for F2.UI */ UI_Class.hideMask = function(instanceId, selector) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.hideMask()'); return; } if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.hideMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector ] ); } else { var container = jQuery(selector); container.find('> .' + F2.Constants.Css.MASK).remove(); container.removeClass(F2.Constants.Css.MASK_CONTAINER); // if the element contains this data property, we need to reset static // position if (container.data(F2.Constants.Css.MASK_CONTAINER)) { container.css({'position':'static'}); } } }; /** * * @method init * @static * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ UI_Class.init = function(containerConfig) { _containerConfig = containerConfig; // set defaults _containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {}); }; /** * Display an ovarlay over an Element on the page * @method showMask * @static * @param {string} instanceId The Instance ID of the app * @param {string|Element} selector The Element or selector to an Element * over which to display the loader * @param {bool} showLoading Display a loading icon */ UI_Class.showMask = function(instanceId, selector, showLoading) { if (!F2.isInit()) { F2.log('F2.init() must be called before F2.UI.showMask()'); return; } if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) { F2.Rpc.call( instanceId, F2.Constants.Sockets.RPC, 'F2.UI.showMask', [ instanceId, // must only pass the selector argument. if we pass an Element there // will be F2.stringify() errors jQuery(selector).selector, showLoading ] ); } else { if (showLoading && !_containerConfig.UI.Mask.loadingIcon) { F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();'); } var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER); var mask = jQuery('<div>') .height('100%' /*container.outerHeight()*/) .width('100%' /*container.outerWidth()*/) .addClass(F2.Constants.Css.MASK); // set inline styles if useClasses is false if (!_containerConfig.UI.Mask.useClasses) { mask.css({ 'background-color':_containerConfig.UI.Mask.backgroundColor, 'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '', 'background-position':'50% 50%', 'background-repeat':'no-repeat', 'display':'block', 'left':0, 'min-height':30, 'padding':0, 'position':'absolute', 'top':0, 'z-index':_containerConfig.UI.Mask.zIndex, 'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')', 'opacity':_containerConfig.UI.Mask.opacity }); } // only set the position if the container is currently static if (container.css('position') === 'static') { container.css({'position':'relative'}); // setting this data property tells hideMask to set the position // back to static container.data(F2.Constants.Css.MASK_CONTAINER, true); } // add the mask to the container container.append(mask); } }; return UI_Class; })()); /** * Root namespace of the F2 SDK * @module f2 * @class F2 */ F2.extend('', (function(){ var _apps = {}; var _config = false; var _bUsesAppHandlers = false; var _sAppHandlerToken = F2.AppHandlers.__f2GetToken(); /** * Appends the app's html to the DOM * @method _afterAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html * @return {Element} The DOM Element that contains the app */ var _afterAppRender = function(appConfig, html) { var handler = _config.afterAppRender || function(appConfig, html) { return jQuery(html).appendTo('body'); }; var appContainer = handler(appConfig, html); if (!!_config.afterAppRender && !appContainer) { F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app'); return; } else { // apply APP class and Instance ID jQuery(appContainer).addClass(F2.Constants.Css.APP); return appContainer.get(0); } }; /** * Renders the html for an app. * @method _appRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {string} html The string of html */ var _appRender = function(appConfig, html) { // apply APP_CONTAINER class html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); // optionally apply wrapper html if (_config.appRender) { html = _config.appRender(appConfig, html); } // apply APP class and instanceId return _outerHtml(html); }; /** * Rendering hook to allow containers to render some html prior to an app * loading * @method _beforeAppRender * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {Element} The DOM Element surrounding the app */ var _beforeAppRender = function(appConfig) { var handler = _config.beforeAppRender || jQuery.noop; return handler(appConfig); }; /** * Handler to inform the container that a script failed to load * @method _onScriptLoadFailure * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param scriptInfo The path of the script that failed to load or the exception info * for the inline script that failed to execute */ var _appScriptLoadFailed = function(appConfig, scriptInfo) { var handler = _config.appScriptLoadFailed || jQuery.noop; return handler(appConfig, scriptInfo); }; /** * Adds properties to the AppConfig object * @method _createAppConfig * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with * necessary properties */ var _createAppConfig = function(appConfig) { // make a copy of the app config to ensure that the original is not modified appConfig = jQuery.extend(true, {}, appConfig); // create the instanceId for the app appConfig.instanceId = appConfig.instanceId || F2.guid(); // default the views if not provided appConfig.views = appConfig.views || []; if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) { appConfig.views.push(F2.Constants.Views.HOME); } return appConfig; }; /** * Adds properties to the ContainerConfig object to take advantage of defaults * @method _hydrateContainerConfig * @private * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object */ var _hydrateContainerConfig = function(containerConfig) { if (!containerConfig.scriptErrorTimeout){ containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout; } if (containerConfig.debugMode !== true){ containerConfig.debugMode = F2.ContainerConfig.debugMode; } }; /** * Attach app events * @method _initAppEvents * @private */ var _initAppEvents = function (appConfig) { jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) { event.preventDefault(); var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase(); // handle the special REMOVE view if (view == F2.Constants.Views.REMOVE) { F2.removeApp(appConfig.instanceId); } else { appConfig.ui.Views.change(view); } }); }; /** * Attach container Events * @method _initContainerEvents * @private */ var _initContainerEvents = function() { var resizeTimeout; var resizeHandler = function() { F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE); }; jQuery(window).on('resize', function() { clearTimeout(resizeTimeout); resizeTimeout = setTimeout(resizeHandler, 100); }); }; /** * Has the container been init? * @method _isInit * @private * @return {bool} True if the container has been init */ var _isInit = function() { return !!_config; }; /** * Instantiates each app from it's appConfig and stores that in a local private collection * @method _createAppInstance * @private * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects */ var _createAppInstance = function(appConfig, appContent){ // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // instantiate F2.App if (F2.Apps[appConfig.appId] !== undefined) { if (typeof F2.Apps[appConfig.appId] === 'function') { // IE setTimeout(function() { _apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root); if (_apps[appConfig.instanceId].app['init'] !== undefined) { _apps[appConfig.instanceId].app.init(); } }, 0); } else { F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')'); } } }; /** * Loads the app's html/css/javascript * @method loadApp * @private * @param {Array} appConfigs An array of * {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects * @param {F2.AppManifest} [appManifest] The AppManifest object */ var _loadApps = function(appConfigs, appManifest) { appConfigs = [].concat(appConfigs); // check for secure app if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) { _loadSecureApp(appConfigs[0], appManifest); return; } // check that the number of apps in manifest matches the number requested if (appConfigs.length != appManifest.apps.length) { F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest); return; } var scripts = appManifest.scripts || []; var styles = appManifest.styles || []; var inlines = appManifest.inlineScripts || []; var scriptCount = scripts.length; var scriptsLoaded = 0; var appInit = function() { jQuery.each(appConfigs, function(i, a) { _createAppInstance(a, appManifest.apps[i]); }); }; //Check to see if any of the ways a file can be ready are available as properties on the file's element (borrowed from yepnope) var isFileReady = function(readyState) { return ( !readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized' ); }; var _onload = function(e){ if ( e.type == 'load' || isFileReady((e.currentTarget || e.srcElement).readyState) ){ //done, cleanup var script = e.currentTarget || e.srcElement; if (script.detachEvent){ script.detachEvent('onreadystatechange', _onload);//IE } else { removeEventListener(script, _onload, 'load'); removeEventListener(script, _error, 'error'); } } //are we done loading all scripts for this app? if (++scriptsLoaded == scriptCount) { evalInlines(); appInit(); } }; var _error = function(e){ //log and emit event for the failed (400,500) scripts setTimeout(function(){ var evtData = { src: e.target.src, appId: appConfigs[0].appId }; //send error to console F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\''); //emit event F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData); if(!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0],evtData.src); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], evtData.src ); } }, _config.scriptErrorTimeout);//defaults to 7000 }; //eval inlines var evalInlines = function(){ jQuery.each(inlines, function(i, e) { try { eval(e); } catch (exception) { F2.log('Error loading inline script: ' + exception + '\n\n' + e); if(!_bUsesAppHandlers) { _appScriptLoadFailed(appConfigs[0],exception); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, appConfigs[0], exception ); } } }); }; // load styles, see #101 var stylesFragment = null, useCreateStyleSheet = !!document.createStyleSheet; jQuery.each(styles, function(i, e) { if (useCreateStyleSheet) { document.createStyleSheet(e); } else { stylesFragment = stylesFragment || []; stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>'); } }); if (stylesFragment){ jQuery('head').append(stylesFragment.join('')); } // load html jQuery.each(appManifest.apps, function(i, a) { if(!_bUsesAppHandlers) { // load html and save the root node appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html)); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfigs[i], // the app config _outerHtml(a.html) ); var appId = appConfigs[i].appId; if (!appConfigs[i].root) { throw('Root for ' +appId+ ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.'); } var $root = jQuery(appConfigs[i].root); if ($root.parents('body:first').length === 0) { throw('App root for ' +appId+ ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfigs[i] // the app config ); if(!F2.isNativeDOMNode(appConfigs[i].root)) { throw('App root for ' +appId+ ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.'); } $root.addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId); } // init events _initAppEvents(appConfigs[i]); }); // load scripts and eval inlines once complete jQuery.each(scripts, function(i, e) { var doc = document, script = doc.createElement('script'), resourceUrl = e; //if in debugMode, add cache buster to each script URL if (_config.debugMode){ resourceUrl += '?cachebuster=' + new Date().getTime(); } //scripts needed to be loaded in order they're defined in the AppManifest script.async = false; //add other attrs script.src = resourceUrl; script.type = 'text/javascript'; script.charset = 'utf-8'; //attach load event to script to evaluate inline scripts and init the AppClass if (script.attachEvent && !(script.attachEvent.toString && script.attachEvent.toString().indexOf('[native code') < 0)){//for IE, from requirejs script.attachEvent('onreadystatechange', _onload); } else { script.addEventListener('load', _onload, false); //attach error event for 400s and 500s script.addEventListener('error', _error, false); } doc.body.appendChild(script); }); // if no scripts were to be processed, fire the appInit event if (!scriptCount) { evalInlines(); appInit(); } }; /** * Loads the app's html/css/javascript into an iframe * @method loadSecureApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the * page. */ var _loadSecureApp = function(appConfig, appManifest) { // make sure the container is configured for secure apps if (_config.secureAppPagePath) { if(!_bUsesAppHandlers) { // create the html container for the iframe appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>')); } else { var $root = jQuery(appConfig.root); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER, appConfig, // the app config appManifest.html ); if ($root.parents('body:first').length === 0) { throw('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); } F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_AFTER, appConfig // the app config ); if (!appConfig.root) { throw('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } if (!F2.isNativeDOMNode(appConfig.root)) { throw('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); } jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId); } // instantiate F2.UI appConfig.ui = new F2.UI(appConfig); // init events _initAppEvents(appConfig); // create RPC socket F2.Rpc.register(appConfig, appManifest); } else { F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.'); } }; var _outerHtml = function(html) { return jQuery('<div></div>').append(html).html(); }; /** * Checks if the app is valid * @method _validateApp * @private * @param {F2.AppConfig} appConfig The F2.AppConfig object * @returns {bool} True if the app is valid */ var _validateApp = function(appConfig) { // check for valid app configurations if (!appConfig.appId) { F2.log('"appId" missing from app object'); return false; } else if (!appConfig.root && !appConfig.manifestUrl) { F2.log('"manifestUrl" missing from app object'); return false; } return true; }; /** * Checks if the ContainerConfig is valid * @method _validateContainerConfig * @private * @returns {bool} True if the config is valid */ var _validateContainerConfig = function() { if (_config) { if (_config.xhr) { if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) { throw('ContainerConfig.xhr should be a function or an object'); } if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') { throw('ContainerConfig.xhr.dataType should be a function'); } if (_config.xhr.type && typeof _config.xhr.type !== 'function') { throw('ContainerConfig.xhr.type should be a function'); } if (_config.xhr.url && typeof _config.xhr.url !== 'function') { throw('ContainerConfig.xhr.url should be a function'); } } } return true; }; return { /** * Gets the current list of apps in the container * @method getContainerState * @returns {Array} An array of objects containing the appId */ getContainerState: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.getContainerState()'); return; } return jQuery.map(_apps, function(app) { return { appId: app.config.appId }; }); }, /** * Initializes the container. This method must be called before performing * any other actions in the container. * @method init * @param {F2.ContainerConfig} config The configuration object */ init: function(config) { _config = config || {}; _validateContainerConfig(); _hydrateContainerConfig(_config); // dictates whether we use the old logic or the new logic. // TODO: Remove in v2.0 _bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed); // only establish RPC connection if the container supports the secure app page if (!!_config.secureAppPagePath || _config.isSecureAppPage) { F2.Rpc.init(!!_config.secureAppPagePath ? _config.secureAppPagePath : false); } F2.UI.init(_config); if (!_config.isSecureAppPage) { _initContainerEvents(); } }, /** * Has the container been init? * @method isInit * @return {bool} True if the container has been init */ isInit: _isInit, /** * Begins the loading process for all apps and/or initialization process for pre-loaded apps. * The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will * contain the app's unique instanceId within the container. If the * {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered * to be a pre-loaded app and will be handled accordingly. Optionally, the * {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those * assets will be used instead of making a request. * @method registerApps * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} * objects * @param {Array} [appManifests] An array of * {{#crossLink "F2.AppManifest"}}{{/crossLink}} * objects. This array must be the same length as the apps array that is * objects. This array must be the same length as the apps array that is * passed in. This can be useful if apps are loaded on the server-side and * passed down to the client. * @example * Traditional App requests. * * // Traditional f2 app configs * var arConfigs = [ * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * }, * { * appId: 'com_externaldomain_example_app2', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Pre-loaded and tradition apps mixed. * * // Pre-loaded apps and traditional f2 app configs * // you can preload the same app multiple times as long as you have a unique root for each * var arConfigs = [ * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-1', * manifestUrl: '' * }, * { * appId: 'com_mydomain_example_app', * context: {}, * root: 'div#example-app-2', * manifestUrl: '' * }, * { * appId: 'com_externaldomain_example_app', * context: {}, * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' * } * ]; * * F2.init(); * F2.registerApps(arConfigs); * * @example * Apps with predefined manifests. * * // Traditional f2 app configs * var arConfigs = [ * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app', context: {}}, * {appId: 'com_externaldomain_example_app2', context: {}} * ]; * * // Pre requested manifest responses * var arManifests = [ * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/AppClass.js'], * styles: ['http://www.domain.com/css/AppStyles.css'] * }, * { * apps: ['<div>Example App 2!</div>'], * inlineScripts: [], * scripts: ['http://www.domain.com/js/App2Class.js'], * styles: ['http://www.domain.com/css/App2Styles.css'] * } * ]; * * F2.init(); * F2.registerApps(arConfigs, arManifests); */ registerApps: function(appConfigs, appManifests) { if (!_isInit()) { F2.log('F2.init() must be called before F2.registerApps()'); return; } else if (!appConfigs) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; } var appStack = []; var batches = {}; var callbackStack = {}; var haveManifests = false; appConfigs = [].concat(appConfigs); appManifests = [].concat(appManifests || []); haveManifests = !!appManifests.length; // appConfigs must have a length if (!appConfigs.length) { F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); return; // ensure that the array of apps and manifests are qual } else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) { F2.log('The length of "apps" does not equal the length of "appManifests"'); return; } // validate each app and assign it an instanceId // then determine which apps can be batched together jQuery.each(appConfigs, function(i, a) { // add properties and methods a = _createAppConfig(a); // Will set to itself, for preloaded apps, or set to null for apps that aren't already // on the page. a.root = a.root || null; // we validate the app after setting the root property because pre-load apps do no require // manifest url if (!_validateApp(a)) { return; // move to the next app } // save app _apps[a.instanceId] = { config:a }; // If the root property is defined then this app is considered to be preloaded and we will // run it through that logic. if(a.root) { if((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) { F2.log('AppConfig invalid for pre-load, not a valid string and not dom node'); F2.log('AppConfig instance:', a); throw('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.'); } else if(jQuery(a.root).length != 1) { F2.log('AppConfig invalid for pre-load, root not unique'); F2.log('AppConfig instance:', a); F2.log('Number of dom node instances:', jQuery(a.root).length); throw('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.'); } // instantiate F2.App _createAppInstance(a); // init events _initAppEvents(a); // Continue on in the .each loop, no need to continue because the app is on the page // the js in initialized, and it is ready to role. return; // equivalent to continue in .each } if(!_bUsesAppHandlers) { // fire beforeAppRender a.root = _beforeAppRender(a); } else { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_CREATE_ROOT, a // the app config ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_RENDER_BEFORE, a // the app config ); } // if we have the manifest, go ahead and load the app if (haveManifests) { _loadApps(a, appManifests[i]); } else { // check if this app can be batched if (a.enableBatchRequests && !a.isSecure) { batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || []; batches[a.manifestUrl.toLowerCase()].push(a); } else { appStack.push({ apps:[a], url:a.manifestUrl }); } } }); // we don't have the manifests, go ahead and load them if (!haveManifests) { // add the batches to the appStack jQuery.each(batches, function(i, b) { appStack.push({ url:i, apps:b }); }); // if an app is being loaded more than once on the page, there is the // potential that the jsonp callback will be clobbered if the request // for the AppManifest for the app comes back at the same time as // another request for the same app. We'll create a callbackStack // that will ensure that requests for the same app are loaded in order // rather than at the same time jQuery.each(appStack, function(i, req) { // define the callback function based on the first app's App ID var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId; // push the request onto the callback stack callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || []; callbackStack[jsonpCallback].push(req); }); // loop through each item in the callback stack and make the request // for the AppManifest. When the request is complete, pop the next // request off the stack and make the request. jQuery.each(callbackStack, function(i, requests) { var manifestRequest = function(jsonpCallback, req) { if (!req) { return; } // setup defaults and callbacks var url = req.url, type = 'GET', dataType = 'jsonp', completeFunc = function() { manifestRequest(i, requests.pop()); }, errorFunc = function() { jQuery.each(req.apps, function(idx,item){ F2.log('Removed failed ' +item.name+ ' app', item); F2.removeApp(item.instanceId); }); }, successFunc = function(appManifest) { _loadApps(req.apps, appManifest); }; // optionally fire xhr overrides if (_config.xhr && _config.xhr.dataType) { dataType = _config.xhr.dataType(req.url, req.apps); if (typeof dataType !== 'string') { throw('ContainerConfig.xhr.dataType should return a string'); } } if (_config.xhr && _config.xhr.type) { type = _config.xhr.type(req.url, req.apps); if (typeof type !== 'string') { throw('ContainerConfig.xhr.type should return a string'); } } if (_config.xhr && _config.xhr.url) { url = _config.xhr.url(req.url, req.apps); if (typeof url !== 'string') { throw('ContainerConfig.xhr.url should return a string'); } } // setup the default request function if an override is not present var requestFunc = _config.xhr; if (typeof requestFunc !== 'function') { requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) { jQuery.ajax({ url: url, type: type, data: { params: F2.stringify(req.apps, F2.appConfigReplacer) }, jsonp: false, // do not put 'callback=' in the query string jsonpCallback: jsonpCallback, // Unique function name dataType: dataType, success: successCallback, error: function(jqxhr, settings, exception) { F2.log('Failed to load app(s)', exception.toString(), req.apps); errorCallback(); }, complete: completeCallback }); }; } requestFunc(url, req.apps, successFunc, errorFunc, completeFunc); }; manifestRequest(i, requests.pop()); }); } }, /** * Removes all apps from the container * @method removeAllApps */ removeAllApps: function() { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeAllApps()'); return; } jQuery.each(_apps, function(i, a) { F2.removeApp(a.config.instanceId); }); }, /** * Removes an app from the container * @method removeApp * @param {string} instanceId The app's instanceId */ removeApp: function(instanceId) { if (!_isInit()) { F2.log('F2.init() must be called before F2.removeApp()'); return; } if (_apps[instanceId]) { F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_BEFORE, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY, _apps[instanceId] // the app instance ); F2.AppHandlers.__trigger( _sAppHandlerToken, F2.Constants.AppHandlers.APP_DESTROY_AFTER, _apps[instanceId] // the app instance ); delete _apps[instanceId]; } } }; })()); exports.F2 = F2; if (typeof define !== 'undefined' && define.amd) { define(function() { return F2; }); } })(typeof exports !== 'undefined' ? exports : window);
src/svg-icons/image/exposure.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageExposure = (props) => ( <SvgIcon {...props}> <path d="M15 17v2h2v-2h2v-2h-2v-2h-2v2h-2v2h2zm5-15H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM5 5h6v2H5V5zm15 15H4L20 4v16z"/> </SvgIcon> ); ImageExposure = pure(ImageExposure); ImageExposure.displayName = 'ImageExposure'; ImageExposure.muiName = 'SvgIcon'; export default ImageExposure;
tests/framework.spec.js
hack-duke/hackduke-portal
import assert from 'assert' import React from 'react' import {mount, render, shallow} from 'enzyme' class Fixture extends React.Component { render () { return ( <div> <input id='checked' defaultChecked /> <input id='not' defaultChecked={false} /> </div> ) } } describe('(Framework) Karma Plugins', function () { it('Should expose "expect" globally.', function () { assert.ok(expect) }) it('Should expose "should" globally.', function () { assert.ok(should) }) it('Should have chai-as-promised helpers.', function () { const pass = new Promise(res => res('test')) const fail = new Promise((res, rej) => rej()) return Promise.all([ expect(pass).to.be.fulfilled, expect(fail).to.not.be.fulfilled ]) }) it('should have chai-enzyme working', function() { let wrapper = shallow(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() wrapper = mount(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() wrapper = render(<Fixture />) expect(wrapper.find('#checked')).to.be.checked() }) })
node_modules/native-base/src/basic/Header.js
tausifmuzaffar/bisApp
import React, { Component } from 'react'; import { View, StatusBar } from 'react-native'; import { connectStyle } from '@shoutem/theme'; import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames'; import variable from '../theme/variables/platform'; import _ from 'lodash'; class Header extends Component { static contextTypes = { theme: React.PropTypes.object, } render() { const variables = (this.context.theme) ? this.context.theme['@@shoutem.theme/themeStyle'].variables : variable; const platformStyle = variables.platformStyle; return ( <View> <StatusBar backgroundColor={(this.props.androidStatusBarColor) ? this.props.androidStatusBarColor : variables.statusBarColor} barStyle={(this.props.iosBarStyle) ? this.props.iosBarStyle : (platformStyle === 'material') ? 'light-content' : variables.iosStatusbar } /> <View ref={c => this._root = c} {...this.props} /> </View> ); } } Header.propTypes = { ...View.propTypes, style: React.PropTypes.object, searchBar: React.PropTypes.bool, rounded: React.PropTypes.bool, }; const StyledHeader = connectStyle('NativeBase.Header', {}, mapPropsToStyleNames)(Header); export { StyledHeader as Header, };
src/pages/NotFoundPage.js
Pavel-DV/ChronoMint
import React from 'react' const NotFoundPage = () => { return ( <div> <div> 404 Page Not Found </div> </div> ) } export default NotFoundPage
src/svg-icons/image/palette.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImagePalette = (props) => ( <SvgIcon {...props}> <path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9c.83 0 1.5-.67 1.5-1.5 0-.39-.15-.74-.39-1.01-.23-.26-.38-.61-.38-.99 0-.83.67-1.5 1.5-1.5H16c2.76 0 5-2.24 5-5 0-4.42-4.03-8-9-8zm-5.5 9c-.83 0-1.5-.67-1.5-1.5S5.67 9 6.5 9 8 9.67 8 10.5 7.33 12 6.5 12zm3-4C8.67 8 8 7.33 8 6.5S8.67 5 9.5 5s1.5.67 1.5 1.5S10.33 8 9.5 8zm5 0c-.83 0-1.5-.67-1.5-1.5S13.67 5 14.5 5s1.5.67 1.5 1.5S15.33 8 14.5 8zm3 4c-.83 0-1.5-.67-1.5-1.5S16.67 9 17.5 9s1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/> </SvgIcon> ); ImagePalette = pure(ImagePalette); ImagePalette.displayName = 'ImagePalette'; ImagePalette.muiName = 'SvgIcon'; export default ImagePalette;
assets/js/vendor/jquery-1.9.1.min.js
wujackjack/wujackjack.github.io
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
react-flux-mui/js/material-ui/src/svg-icons/device/battery-unknown.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryUnknown = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4zm-2.72 13.95h-1.9v-1.9h1.9v1.9zm1.35-5.26s-.38.42-.67.71c-.48.48-.83 1.15-.83 1.6h-1.6c0-.83.46-1.52.93-2l.93-.94c.27-.27.44-.65.44-1.06 0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5H9c0-1.66 1.34-3 3-3s3 1.34 3 3c0 .66-.27 1.26-.7 1.69z"/> </SvgIcon> ); DeviceBatteryUnknown = pure(DeviceBatteryUnknown); DeviceBatteryUnknown.displayName = 'DeviceBatteryUnknown'; DeviceBatteryUnknown.muiName = 'SvgIcon'; export default DeviceBatteryUnknown;
docs/src/IntroductionPage.js
chrishoage/react-bootstrap
import React from 'react'; import CodeExample from './CodeExample'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const IntroductionPage = React.createClass({ render() { return ( <div> <NavMain activePage="introduction" /> <PageHeader title="Introduction" subTitle="The most popular front-end framework, rebuilt for React."/> <div className="container bs-docs-container"> <div className="row"> <div className="col-md-9" role="main"> <div className="bs-docs-section"> <p className="lead"> React-Bootstrap is a library of reuseable front-end components. You'll get the look-and-feel of Twitter Bootstrap, but with much cleaner code, via Facebook's React.js framework. </p> <p> Let's say you want a small button that says "Something", to trigger the function someCallback. If you were writing a native application, you might write something like: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `button(size=SMALL, color=GREEN, text="Something", onClick=someCallback)` } /> </div> <p> With the most popular web front-end framework, Twitter Bootstrap, you'd write this in your HTML: </p> <div className="highlight"> <CodeExample mode="htmlmixed" codeText={ `<button id="something-btn" type="button" class="btn btn-success btn-sm"> Something </button>` } /> </div> <p> And something like <code className="js"> $('#something-btn').click(someCallback); </code> in your Javascript. </p> <p> By web standards this is quite nice, but it's still quite nasty. React-Bootstrap lets you write this: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `<Button bsStyle="success" bsSize="small" onClick={someCallback}> Something </Button>` } /> </div> <p> The HTML/CSS implementation details are abstracted away, leaving you with an interface that more closely resembles what you would expect to write in other programming languages. </p> <h2>A better Bootstrap API using React.js</h2> <p> The Bootstrap code is so repetitive because HTML and CSS do not support the abstractions necessary for a nice library of components. That's why we have to write <code>btn</code> three times, within an element called <code>button</code>. </p> <p> <strong> The React.js solution is to write directly in Javascript. </strong> React takes over the page-rendering entirely. You just give it a tree of Javascript objects, and tell it how state is transmitted between them. </p> <p> For instance, we might tell React to render a page displaying a single button, styled using the handy Bootstrap CSS: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = React.DOM.button({ className: "btn btn-lg btn-success", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> But now that we're in Javascript, we can wrap the HTML/CSS, and provide a much better API: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var button = ReactBootstrap.Button({ bsStyle: "success", bsSize: "large", children: "Register" }); React.render(button, mountNode);` } /> </div> <p> React-Bootstrap is a library of such components, which you can also easily extend and enhance with your own functionality. </p> <h3>JSX Syntax</h3> <p> While each React component is really just a Javascript object, writing tree-structures that way gets tedious. React encourages the use of a syntactic-sugar called JSX, which lets you write the tree in an HTML-like syntax: </p> <div className="highlight"> <CodeExample mode="javascript" codeText={ `var buttonGroupInstance = ( <ButtonGroup> <DropdownButton bsStyle="success" title="Dropdown"> <MenuItem key="1">Dropdown link</MenuItem> <MenuItem key="2">Dropdown link</MenuItem> </DropdownButton> <Button bsStyle="info">Middle</Button> <Button bsStyle="info">Right</Button> </ButtonGroup> ); React.render(buttonGroupInstance, mountNode);` } /> </div> <p> Some people's first impression of React.js is that it seems messy to mix Javascript and HTML in this way. However, compare the code required to add a dropdown button in the example above to the <a href="http://getbootstrap.com/javascript/#dropdowns"> Bootstrap Javascript</a> and <a href="http://getbootstrap.com/components/#btn-dropdowns"> Components</a> documentation for creating a dropdown button. The documentation is split in two because you have to implement the component in two places in your code: first you must add the HTML/CSS elements, and then you must call some Javascript setup code to wire the component together. </p> <p> The React-Bootstrap component library tries to follow the React.js philosophy that a single piece of functionality should be defined in a single place. View the current React-Bootstrap library on the <a href="/components.html">components page</a>. </p> </div> </div> </div> </div> <PageFooter /> </div> ); } }); export default IntroductionPage;
public/js/components/admin/Settings.react.js
rajikaimal/Coupley
/** * Created by Isuru 1 on 21/01/2016. */ import React from 'react'; import { Link } from 'react-router'; const Settings = React.createClass({ render: function () { return ( <div className="settings"> <aside className="control-sidebar control-sidebar-dark"> <ul className="nav nav-tabs nav-justified control-sidebar-tabs"> </ul> <div className="tab-content"> <div className="tab-pane" id="control-sidebar-home-tab"> </div> <div className="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div> </div> </aside> </div> ); }, }); export default Settings;
ajax/libs/react-is/0.0.0-experimental-5a0607278-20210922/umd/react-is.development.js
cdnjs/cdnjs
/** @license React vundefined * react-is.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.ReactIs = {})); }(this, (function (exports) { 'use strict'; // ATTENTION // When adding new symbols to this file, // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols' // The Symbol used to tag the ReactElement-like types. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = 0xeac7; var REACT_PORTAL_TYPE = 0xeaca; var REACT_FRAGMENT_TYPE = 0xeacb; var REACT_STRICT_MODE_TYPE = 0xeacc; var REACT_PROFILER_TYPE = 0xead2; var REACT_PROVIDER_TYPE = 0xeacd; var REACT_CONTEXT_TYPE = 0xeace; var REACT_FORWARD_REF_TYPE = 0xead0; var REACT_SUSPENSE_TYPE = 0xead1; var REACT_SUSPENSE_LIST_TYPE = 0xead8; var REACT_MEMO_TYPE = 0xead3; var REACT_LAZY_TYPE = 0xead4; var REACT_SCOPE_TYPE = 0xead7; var REACT_OPAQUE_ID_TYPE = 0xeae0; var REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1; var REACT_OFFSCREEN_TYPE = 0xeae2; var REACT_LEGACY_HIDDEN_TYPE = 0xeae3; var REACT_CACHE_TYPE = 0xeae4; if (typeof Symbol === 'function' && Symbol.for) { var symbolFor = Symbol.for; REACT_ELEMENT_TYPE = symbolFor('react.element'); REACT_PORTAL_TYPE = symbolFor('react.portal'); REACT_FRAGMENT_TYPE = symbolFor('react.fragment'); REACT_STRICT_MODE_TYPE = symbolFor('react.strict_mode'); REACT_PROFILER_TYPE = symbolFor('react.profiler'); REACT_PROVIDER_TYPE = symbolFor('react.provider'); REACT_CONTEXT_TYPE = symbolFor('react.context'); REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'); REACT_SUSPENSE_TYPE = symbolFor('react.suspense'); REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'); REACT_MEMO_TYPE = symbolFor('react.memo'); REACT_LAZY_TYPE = symbolFor('react.lazy'); REACT_SCOPE_TYPE = symbolFor('react.scope'); REACT_OPAQUE_ID_TYPE = symbolFor('react.opaque.id'); REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'); REACT_OFFSCREEN_TYPE = symbolFor('react.offscreen'); REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden'); REACT_CACHE_TYPE = symbolFor('react.cache'); } // Filter certain DOM attributes (e.g. src, href) if their values are empty strings. var enableScopeAPI = false; // Experimental Create Event Handle API. var REACT_MODULE_REFERENCE = 0; if (typeof Symbol === 'function') { REACT_MODULE_REFERENCE = Symbol.for('react.module.reference'); } function isValidElementType(type) { if (typeof type === 'string' || typeof type === 'function') { return true; } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill). if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || type === REACT_DEBUG_TRACING_MODE_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || type === REACT_CACHE_TYPE) { return true; } if (typeof type === 'object' && type !== null) { if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { return true; } } return false; } function typeOf(object) { if (typeof object === 'object' && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type = object.type; switch (type) { case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: case REACT_SUSPENSE_LIST_TYPE: return type; default: var $$typeofType = type && type.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return undefined; } var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var SuspenseList = REACT_SUSPENSE_LIST_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; var hasWarnedAboutDeprecatedIsConcurrentMode = false; // AsyncMode should be deprecated function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; // Using console['warn'] to evade Babel and ESLint console['warn']('The ReactIs.isAsyncMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); } } return false; } function isConcurrentMode(object) { { if (!hasWarnedAboutDeprecatedIsConcurrentMode) { hasWarnedAboutDeprecatedIsConcurrentMode = true; // Using console['warn'] to evade Babel and ESLint console['warn']('The ReactIs.isConcurrentMode() alias has been deprecated, ' + 'and will be removed in React 18+.'); } } return false; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } function isSuspenseList(object) { return typeOf(object) === REACT_SUSPENSE_LIST_TYPE; } exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode; exports.Suspense = Suspense; exports.SuspenseList = SuspenseList; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; exports.isSuspenseList = isSuspenseList; exports.isValidElementType = isValidElementType; exports.typeOf = typeOf; })));
app/routes.js
juanda99/arasaac-frontend
// These are the pages you can go to. // They are all wrapped in the App component, which should contain the navbar etc // See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information // about the code splitting business import { getAsyncInjectors } from 'utils/asyncInjectors' const errorLoading = (err) => { console.error('Dynamic page loading failed', err) // eslint-disable-line no-console } const loadModule = (cb) => (componentModule) => { cb(null, componentModule.default) } export default function createRoutes(store) { // Create reusable async injectors using getAsyncInjectors factory const { injectReducer, injectSagas } = getAsyncInjectors(store) // eslint-disable-line no-unused-vars return [ { path: '/', name: 'home', getComponent(nextState, cb) { const importModules = Promise.all([import('containers/HomePage')]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/aac(/:language)', name: 'AAC', getComponent(nextState, cb) { const importModules = Promise.all([import('containers/IntroAAC')]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/aac-users(/:language)', name: 'AAC-users', getComponent(nextState, cb) { const importModules = Promise.all([import('containers/IntroUsersAAC')]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/use-of-aac(/:language)', name: 'AAC-usage', getComponent(nextState, cb) { const importModules = Promise.all([import('containers/IntroUsageAAC')]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/pictograms/search', name: 'pictogramsView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/PictogramsView/reducer'), import('containers/PictogramsView/sagas'), import('containers/PictogramsView') ]) const renderRoute = loadModule(cb) importModules.then(([reducer, sagas, component]) => { injectReducer('pictogramsView', reducer.default) injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) }, childRoutes: [ { path: '/pictograms/search/:searchText', name: 'gallery', getComponent(nextState, cb) { const importModules = Promise.all([ import('components/PictogramList') ]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } } ] }, { path: '/pictograms/favorites', name: 'favoritesView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/PictogramsView/reducer'), import('containers/PictogramsView/sagas'), import('containers/FavoritesView') ]) const renderRoute = loadModule(cb) importModules.then(([reducer, sagas, component]) => { injectReducer('pictogramsView', reducer.default) injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/activate/:activationCode', name: 'activateView', getComponent(location, cb) { import('containers/ActivateView') .then(loadModule(cb)) .catch(errorLoading) } }, // { // path: '/activate/:activationCode', // name: 'activateView', // getComponent(nextState, cb) { // const importModules = Promise.all([ // import('containers/App/reducer'), // import('containers/App/sagas'), // import('containers/ActivateView/') // ]) // const renderRoute = loadModule(cb) // // if reducer is async, render values: defaultToggled: // // state.configuration.filters[ownProps.filter] got undefined!!! // importModules.then(([reducer, sagas, component]) => { // // injectReducer('aux', reducer.default) // injectSagas(sagas.default) // renderRoute(component) // }) // importModules.catch(errorLoading) // } // }, { path: '/materials/search', name: 'materialsView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/MaterialsView/reducer'), import('containers/MaterialsView/sagas'), import('containers/MaterialsView') ]) const renderRoute = loadModule(cb) importModules.then(([reducer, sagas, component]) => { injectReducer('materialsView', reducer.default) injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) }, childRoutes: [ { path: '/materials/search/:searchText', name: 'gallery', getComponent(nextState, cb) { const importModules = Promise.all([ import('components/MaterialList') ]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } } ] }, { path: '/news/upload', onEnter(nextState, replace, callback) { // onEnter gets called when we visit a route // childRoute changes do not trigger onEnter, which is a desired behavior // Prevent saga reinjection if they are running if (this.loadedSagas) { callback() return } // Inject sagas as usual const importModules = System.import('containers/UploadNewsView/sagas') importModules.then((sagas) => { this.loadedSagas = injectSagas(sagas.default) callback() }) importModules.catch(errorLoading) }, onLeave() { // onLeave gets called when we leave the route // Cancel the sagas if they are running if (this.loadedSagas) { this.loadedSagas.forEach((saga) => saga.cancel()) delete this.loadedSagas } }, getComponent(nextState, cb) { const importModules = Promise.all([ System.import('containers/UploadNewsView'), System.import('containers/UploadNewsView/reducer') ]) const renderRoute = loadModule(cb) importModules.then(([component, reducer]) => { injectReducer('uploadNewsView', reducer.default) renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/materials/upload', name: 'uploadMaterialView', getComponent(nextState, cb) { import('containers/UploadMaterialView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/materials/update(/:idMaterial)', name: 'updateMaterialView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/MaterialsView/sagas'), import('containers/UpdateMaterialView/') ]) const renderRoute = loadModule(cb) // if reducer is async, render values: defaultToggled: // state.configuration.filters[ownProps.filter] got undefined!!! importModules.then(([sagas, component]) => { injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/materials/add-translation(/:idMaterial)', name: 'uploadTranslationView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/MaterialsView/sagas'), import('containers/UploadTranslationView/') ]) const renderRoute = loadModule(cb) // if reducer is async, render values: defaultToggled: // state.configuration.filters[ownProps.filter] got undefined!!! importModules.then(([sagas, component]) => { injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/materials/:locale/:idMaterial', name: 'materialView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/MaterialsView/sagas'), import('containers/MaterialView/') ]) const renderRoute = loadModule(cb) // if reducer is async, render values: defaultToggled: // state.configuration.filters[ownProps.filter] got undefined!!! importModules.then(([sagas, component]) => { injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/pictograms/:locale/:idPictogram(/:searchText)', name: 'pictogramView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/PictogramsView/reducer'), import('containers/PictogramsView/sagas'), import('containers/PictogramView/') ]) const renderRoute = loadModule(cb) // if reducer is async, render values: defaultToggled: // state.configuration.filters[ownProps.filter] got undefined!!! importModules.then(([reducer, sagas, component]) => { injectReducer('pictogramsView', reducer.default) injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/developers', name: 'DevelopersView', getComponent(location, cb) { import('containers/DevelopersView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/developers/accounts', name: 'DevAccountView', getComponent(location, cb) { import('containers/DevAccountView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/developers/api', name: 'ApiView', getComponent(location, cb) { import('containers/ApiView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/profile', name: 'profileView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/ProfileView/sagas'), import('containers/ProfileView/') ]) const renderRoute = loadModule(cb) // if reducer is async, render values: defaultToggled: // state.configuration.filters[ownProps.filter] got undefined!!! importModules.then(([sagas, component]) => { injectSagas(sagas.default) renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/signin', name: 'LoginView', getComponent(nextState, cb) { const importModules = Promise.all([import('containers/LoginView')]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/registerform', name: 'SignupView', getComponent(nextState, cb) { const importModules = Promise.all([import('containers/SignupView')]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/recoverpassword(/:email)', name: 'RecoverPasswordView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/RecoverPasswordView') ]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: '/register', name: 'SignupOptionsView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/SignupOptionsView') ]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } }, { path: 'terms-of-use', name: 'useConditions', getComponent(location, cb) { import('containers/TermsOfUseView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: 'privacy-policy', name: 'privacyPolicy', getComponent(location, cb) { import('containers/PrivacyPolicyView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: 'cookies-policy', name: 'cookiesPolicy', getComponent(location, cb) { import('containers/CookiesPolicyView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/prizes', name: 'prizes', getComponent(location, cb) { import('containers/PrizesView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/world', name: 'world', getComponent(location, cb) { import('containers/WorldView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/settings', name: 'settings', getComponent(location, cb) { import('containers/SettingsView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/translators', name: 'translators', getComponent(location, cb) { import('containers/CollaboratorsView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: 'contact-us', name: 'contact-us', getComponent(location, cb) { import('containers/ContactView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: 'about-us', name: 'about-us', getComponent(location, cb) { import('containers/AboutView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '/lse/search', name: 'lseView', getComponent(nextState, cb) { const importModules = Promise.all([ import('containers/LSE') ]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) }, childRoutes: [ { path: '/lse/search/:searchText', name: 'lseList', getComponent(nextState, cb) { const importModules = Promise.all([ import('components/PictogramList') ]) const renderRoute = loadModule(cb) importModules.then(([component]) => { renderRoute(component) }) importModules.catch(errorLoading) } } ] }, { path: 'permissionsError', name: 'permissionsError', getComponent(location, cb) { import('containers/PermissionsErrorView') .then(loadModule(cb)) .catch(errorLoading) } }, { path: '*', name: 'notfound', getComponent(nextState, cb) { import('containers/NotFoundPage') .then(loadModule(cb)) .catch(errorLoading) } } ] }
src/app/screens/Anonymous/screens/Home/components/Home.js
docgecko/react-alt-firebase-starter
/*! React Alt Firebase Starter */ import './Home.less'; import React from 'react'; export default class Home extends React.Component { render() { return ( <div className='home'> <h1>Welcome to the Home page...</h1> </div> ); } }
ajax/libs/yui/3.10.3/event-focus/event-focus-min.js
mrehayden1/cdnjs
YUI.add("event-focus",function(e,t){function u(t,r,u){var a="_"+t+"Notifiers";e.Event.define(t,{_useActivate:o,_attach:function(i,s,o){return e.DOM.isWindow(i)?n._attach([t,function(e){s.fire(e)},i]):n._attach([r,this._proxy,i,this,s,o],{capture:!0})},_proxy:function(t,r,i){var s=t.target,f=t.currentTarget,l=s.getData(a),c=e.stamp(f._node),h=o||s!==f,p;r.currentTarget=i?s:f,r.container=i?f:null,l?h=!0:(l={},s.setData(a,l),h&&(p=n._attach([u,this._notify,s._node]).sub,p.once=!0)),l[c]||(l[c]=[]),l[c].push(r),h||this._notify(t)},_notify:function(t,n){var r=t.currentTarget,i=r.getData(a),o=r.ancestors(),u=r.get("ownerDocument"),f=[],l=i?e.Object.keys(i).length:0,c,h,p,d,v,m,g,y,b,w;r.clearData(a),o.push(r),u&&o.unshift(u),o._nodes.reverse(),l&&(m=l,o.some(function(t){var n=e.stamp(t),r=i[n],s,o;if(r){l--;for(s=0,o=r.length;s<o;++s)r[s].handle.sub.filter&&f.push(r[s])}return!l}),l=m);while(l&&(c=o.shift())){d=e.stamp(c),h=i[d];if(h){for(g=0,y=h.length;g<y;++g){p=h[g],b=p.handle.sub,v=!0,t.currentTarget=c,b.filter&&(v=b.filter.apply(c,[c,t].concat(b.args||[])),f.splice(s(f,p),1)),v&&(t.container=p.container,w=p.fire(t));if(w===!1||t.stopped===2)break}delete h[d],l--}if(t.stopped!==2)for(g=0,y=f.length;g<y;++g){p=f[g],b=p.handle.sub,b.filter.apply(c,[c,t].concat(b.args||[]))&&(t.container=p.container,t.currentTarget=c,w=p.fire(t));if(w===!1||t.stopped===2)break}if(t.stopped)break}},on:function(e,t,n){t.handle=this._attach(e._node,n)},detach:function(e,t){t.handle.detach()},delegate:function(t,n,r,s){i(s)&&(n.filter=function(n){return e.Selector.test(n._node,s,t===n?null:t._node)}),n.handle=this._attach(t._node,r,!0)},detachDelegate:function(e,t){t.handle.detach()}},!0)}var n=e.Event,r=e.Lang,i=r.isString,s=e.Array.indexOf,o=function(){var t=!1,n=e.config.doc,r;return n&&(r=n.createElement("p"),r.setAttribute("onbeforeactivate",";"),t=r.onbeforeactivate!==undefined),t}();o?(u("focus","beforeactivate","focusin"),u("blur","beforedeactivate","focusout")):(u("focus","focus","focus"),u("blur","blur","blur"))},"@VERSION@",{requires:["event-synthetic"]});
node_modules/react-dom/lib/ReactDebugTool.js
knguyen1/kylecodes
/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ 'use strict'; var ReactInvalidSetStateWarningHook = require('./ReactInvalidSetStateWarningHook'); var ReactHostOperationHistoryHook = require('./ReactHostOperationHistoryHook'); var ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook'); var ExecutionEnvironment = require('fbjs/lib/ExecutionEnvironment'); var performanceNow = require('fbjs/lib/performanceNow'); var warning = require('fbjs/lib/warning'); var hooks = []; var didHookThrowForEvent = {}; function callHook(event, fn, context, arg1, arg2, arg3, arg4, arg5) { try { fn.call(context, arg1, arg2, arg3, arg4, arg5); } catch (e) { process.env.NODE_ENV !== 'production' ? warning(didHookThrowForEvent[event], 'Exception thrown by hook while handling %s: %s', event, e + '\n' + e.stack) : void 0; didHookThrowForEvent[event] = true; } } function emitEvent(event, arg1, arg2, arg3, arg4, arg5) { for (var i = 0; i < hooks.length; i++) { var hook = hooks[i]; var fn = hook[event]; if (fn) { callHook(event, fn, hook, arg1, arg2, arg3, arg4, arg5); } } } var isProfiling = false; var flushHistory = []; var lifeCycleTimerStack = []; var currentFlushNesting = 0; var currentFlushMeasurements = []; var currentFlushStartTime = 0; var currentTimerDebugID = null; var currentTimerStartTime = 0; var currentTimerNestedFlushDuration = 0; var currentTimerType = null; var lifeCycleTimerHasWarned = false; function clearHistory() { ReactComponentTreeHook.purgeUnmountedComponents(); ReactHostOperationHistoryHook.clearHistory(); } function getTreeSnapshot(registeredIDs) { return registeredIDs.reduce(function (tree, id) { var ownerID = ReactComponentTreeHook.getOwnerID(id); var parentID = ReactComponentTreeHook.getParentID(id); tree[id] = { displayName: ReactComponentTreeHook.getDisplayName(id), text: ReactComponentTreeHook.getText(id), updateCount: ReactComponentTreeHook.getUpdateCount(id), childIDs: ReactComponentTreeHook.getChildIDs(id), // Text nodes don't have owners but this is close enough. ownerID: ownerID || parentID && ReactComponentTreeHook.getOwnerID(parentID) || 0, parentID: parentID }; return tree; }, {}); } function resetMeasurements() { var previousStartTime = currentFlushStartTime; var previousMeasurements = currentFlushMeasurements; var previousOperations = ReactHostOperationHistoryHook.getHistory(); if (currentFlushNesting === 0) { currentFlushStartTime = 0; currentFlushMeasurements = []; clearHistory(); return; } if (previousMeasurements.length || previousOperations.length) { var registeredIDs = ReactComponentTreeHook.getRegisteredIDs(); flushHistory.push({ duration: performanceNow() - previousStartTime, measurements: previousMeasurements || [], operations: previousOperations || [], treeSnapshot: getTreeSnapshot(registeredIDs) }); } clearHistory(); currentFlushStartTime = performanceNow(); currentFlushMeasurements = []; } function checkDebugID(debugID) { var allowRoot = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (allowRoot && debugID === 0) { return; } if (!debugID) { process.env.NODE_ENV !== 'production' ? warning(false, 'ReactDebugTool: debugID may not be empty.') : void 0; } } function beginLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'Did not expect %s timer to start while %s timer is still in ' + 'progress for %s instance.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } currentTimerStartTime = performanceNow(); currentTimerNestedFlushDuration = 0; currentTimerDebugID = debugID; currentTimerType = timerType; } function endLifeCycleTimer(debugID, timerType) { if (currentFlushNesting === 0) { return; } if (currentTimerType !== timerType && !lifeCycleTimerHasWarned) { process.env.NODE_ENV !== 'production' ? warning(false, 'There is an internal error in the React performance measurement code. ' + 'We did not expect %s timer to stop while %s timer is still in ' + 'progress for %s instance. Please report this as a bug in React.', timerType, currentTimerType || 'no', debugID === currentTimerDebugID ? 'the same' : 'another') : void 0; lifeCycleTimerHasWarned = true; } if (isProfiling) { currentFlushMeasurements.push({ timerType: timerType, instanceID: debugID, duration: performanceNow() - currentTimerStartTime - currentTimerNestedFlushDuration }); } currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function pauseCurrentLifeCycleTimer() { var currentTimer = { startTime: currentTimerStartTime, nestedFlushStartTime: performanceNow(), debugID: currentTimerDebugID, timerType: currentTimerType }; lifeCycleTimerStack.push(currentTimer); currentTimerStartTime = 0; currentTimerNestedFlushDuration = 0; currentTimerDebugID = null; currentTimerType = null; } function resumeCurrentLifeCycleTimer() { var _lifeCycleTimerStack$ = lifeCycleTimerStack.pop(), startTime = _lifeCycleTimerStack$.startTime, nestedFlushStartTime = _lifeCycleTimerStack$.nestedFlushStartTime, debugID = _lifeCycleTimerStack$.debugID, timerType = _lifeCycleTimerStack$.timerType; var nestedFlushDuration = performanceNow() - nestedFlushStartTime; currentTimerStartTime = startTime; currentTimerNestedFlushDuration += nestedFlushDuration; currentTimerDebugID = debugID; currentTimerType = timerType; } var lastMarkTimeStamp = 0; var canUsePerformanceMeasure = // $FlowFixMe https://github.com/facebook/flow/issues/2345 typeof performance !== 'undefined' && typeof performance.mark === 'function' && typeof performance.clearMarks === 'function' && typeof performance.measure === 'function' && typeof performance.clearMeasures === 'function'; function shouldMark(debugID) { if (!isProfiling || !canUsePerformanceMeasure) { return false; } var element = ReactComponentTreeHook.getElement(debugID); if (element == null || typeof element !== 'object') { return false; } var isHostElement = typeof element.type === 'string'; if (isHostElement) { return false; } return true; } function markBegin(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; lastMarkTimeStamp = performanceNow(); performance.mark(markName); } function markEnd(debugID, markType) { if (!shouldMark(debugID)) { return; } var markName = debugID + '::' + markType; var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown'; // Chrome has an issue of dropping markers recorded too fast: // https://bugs.chromium.org/p/chromium/issues/detail?id=640652 // To work around this, we will not report very small measurements. // I determined the magic number by tweaking it back and forth. // 0.05ms was enough to prevent the issue, but I set it to 0.1ms to be safe. // When the bug is fixed, we can `measure()` unconditionally if we want to. var timeStamp = performanceNow(); if (timeStamp - lastMarkTimeStamp > 0.1) { var measurementName = displayName + ' [' + markType + ']'; performance.measure(measurementName, markName); } performance.clearMarks(markName); performance.clearMeasures(measurementName); } var ReactDebugTool = { addHook: function (hook) { hooks.push(hook); }, removeHook: function (hook) { for (var i = 0; i < hooks.length; i++) { if (hooks[i] === hook) { hooks.splice(i, 1); i--; } } }, isProfiling: function () { return isProfiling; }, beginProfiling: function () { if (isProfiling) { return; } isProfiling = true; flushHistory.length = 0; resetMeasurements(); ReactDebugTool.addHook(ReactHostOperationHistoryHook); }, endProfiling: function () { if (!isProfiling) { return; } isProfiling = false; resetMeasurements(); ReactDebugTool.removeHook(ReactHostOperationHistoryHook); }, getFlushHistory: function () { return flushHistory; }, onBeginFlush: function () { currentFlushNesting++; resetMeasurements(); pauseCurrentLifeCycleTimer(); emitEvent('onBeginFlush'); }, onEndFlush: function () { resetMeasurements(); currentFlushNesting--; resumeCurrentLifeCycleTimer(); emitEvent('onEndFlush'); }, onBeginLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); emitEvent('onBeginLifeCycleTimer', debugID, timerType); markBegin(debugID, timerType); beginLifeCycleTimer(debugID, timerType); }, onEndLifeCycleTimer: function (debugID, timerType) { checkDebugID(debugID); endLifeCycleTimer(debugID, timerType); markEnd(debugID, timerType); emitEvent('onEndLifeCycleTimer', debugID, timerType); }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onHostOperation: function (operation) { checkDebugID(operation.instanceID); emitEvent('onHostOperation', operation); }, onSetState: function () { emitEvent('onSetState'); }, onSetChildren: function (debugID, childDebugIDs) { checkDebugID(debugID); childDebugIDs.forEach(checkDebugID); emitEvent('onSetChildren', debugID, childDebugIDs); }, onBeforeMountComponent: function (debugID, element, parentDebugID) { checkDebugID(debugID); checkDebugID(parentDebugID, true); emitEvent('onBeforeMountComponent', debugID, element, parentDebugID); markBegin(debugID, 'mount'); }, onMountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'mount'); emitEvent('onMountComponent', debugID); }, onBeforeUpdateComponent: function (debugID, element) { checkDebugID(debugID); emitEvent('onBeforeUpdateComponent', debugID, element); markBegin(debugID, 'update'); }, onUpdateComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'update'); emitEvent('onUpdateComponent', debugID); }, onBeforeUnmountComponent: function (debugID) { checkDebugID(debugID); emitEvent('onBeforeUnmountComponent', debugID); markBegin(debugID, 'unmount'); }, onUnmountComponent: function (debugID) { checkDebugID(debugID); markEnd(debugID, 'unmount'); emitEvent('onUnmountComponent', debugID); }, onTestEvent: function () { emitEvent('onTestEvent'); } }; // TODO remove these when RN/www gets updated ReactDebugTool.addDevtool = ReactDebugTool.addHook; ReactDebugTool.removeDevtool = ReactDebugTool.removeHook; ReactDebugTool.addHook(ReactInvalidSetStateWarningHook); ReactDebugTool.addHook(ReactComponentTreeHook); var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { ReactDebugTool.beginProfiling(); } module.exports = ReactDebugTool;
apps/mk-app-my-setting/action.js
ziaochina/mk-demo
import React from 'react' import { action as MetaAction, AppLoader } from 'mk-meta-engine' import config from './config' import photo from './img/photo.png' class action { constructor(option) { this.metaAction = option.metaAction this.config = config.current this.webapi = this.config.webapi } onInit = ({ component, injections }) => { this.component = component this.injections = injections injections.reduce('init') this.load() } load = async () => { //网站中不存在login应用,那么就不做用户相关处理,正式环境应该不需要这段代码,仅为单应用运行使用 if (!this.config.apps['mk-app-login']) { const option = { user: { id: 1, mobile: '13334445556', nickname: '齐天大圣', password: '1' }, securityLevel: 1 } this.injections.reduce('load', option) return } const currentUser = this.metaAction.context.get('currentUser') const response = await this.webapi.mySetting.init(currentUser.id) this.injections.reduce('load', response) } saveBaseInfo = async () => { const form = this.metaAction.gf('data.form').toJS() const ok = await this.check([{ path: 'data.form.nickname', value: form.nickname }]) if (!ok) return await this.webapi.user.update({ id: form.id, mobile: form.mobile, sex: form.sex, nickname: form.nickname, birthday: form.birthday }) this.component.props.onPortalReload && this.component.props.onPortalReload() this.metaAction.toast('success', '保存个人资料成功') } modifyPassword = async () => { if (!this.config.apps['mk-app-modify-password']) throw '网站中存在mk-app-modify-password才可使用这个功能' const ret = await this.metaAction.modal('show', { title: '修改密码', children: this.metaAction.loadApp('mk-app-modify-password', { store: this.component.props.store, }) }) if (ret) { this.load() } } upload = () => { this.metaAction.toast('error', '纯静态网站,上传目前不可用') } getPhoto = () => photo getSecurityLevelText = () => { const level = this.metaAction.gf('data.form.securityLevel') if (level == 1) return '低' else if (level == 2) return '中低' else if (level == 3) return '中' else if (level == 4) return '中高' else return '高' } getSecurityLevelClassName = () => { var level = this.metaAction.gf('data.form.securityLevel') var className = 'mk-app-my-setting-security-level ' if (level == 1) return className += 'mk-app-my-setting-security-level-error' else if (level == 2) return className += 'mk-app-my-setting-security-level-warn' else if (level == 3) return className += 'mk-app-my-setting-security-level-normal' else if (level == 4) return className += 'mk-app-my-setting-security-level-good' else return className += 'mk-app-my-setting-security-level-success' } menuSelected = ({ item, key }) => { this.metaAction.sf('data.other.selectedMenuItem', key) } fieldChange = async (fieldPath, value) => { await this.check([{ path: fieldPath, value }]) } check = async (fieldPathAndValues) => { if (!fieldPathAndValues) return var checkResults = [] for (var o of fieldPathAndValues) { let r = { ...o } if (o.path == 'data.form.nickname') { Object.assign(r, await this.checkNickname(o.value)) } checkResults.push(r) } var json = {} var hasError = true checkResults.forEach(o => { json[o.path] = o.value json[o.errorPath] = o.message if (o.message) hasError = false }) this.metaAction.sfs(json) return hasError } checkNickname = async (nickname) => { var message if (!nickname) message = '请录入昵称' return { errorPath: 'data.other.error.nickname', message } } } export default function creator(option) { const metaAction = new MetaAction(option), o = new action({ ...option, metaAction }), ret = { ...metaAction, ...o } metaAction.config({ metaHandlers: ret }) return ret }
[2]. Demo_RN/[15]. loginPage_demo/index.ios.js
knightsj/RN_Demo
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image } from 'react-native'; var LoginView = require('./loginView'); class LoginViewDemo extends Component{ render(){ return( <LoginView/> ); } } AppRegistry.registerComponent('component_demo', () => LoginViewDemo);
ajax/libs/ink/2.2.1/js/ink-all.js
iros/cdnjs
(function() { 'use strict'; /** * @module Ink_1 */ /** * global object * * @class Ink */ // skip redefinition of Ink core if ('Ink' in window) { return; } // internal data /* * NOTE: * invoke Ink.setPath('Ink', '/Ink/'); before requiring local modules */ var paths = { Ink: ( ('INK_PATH' in window) ? window.INK_PATH : window.location.protocol + '//js.ink.sapo.pt/Ink/' ) }; var modules = {}; var modulesLoadOrder = []; var modulesRequested = {}; var pendingRMs = []; // auxiliary fns var isEmptyObject = function(o) { /*jshint unused:false */ if (typeof o !== 'object') { return false; } for (var k in o) { if (o.hasOwnProperty(k)) { return false; } } return true; }; window.Ink = { _checkPendingRequireModules: function() { var I, F, o, dep, mod, cb, pRMs = []; for (I = 0, F = pendingRMs.length; I < F; ++I) { o = pendingRMs[I]; if (!o) { continue; } for (dep in o.left) { if (o.left.hasOwnProperty(dep)) { mod = modules[dep]; if (mod) { o.args[o.left[dep] ] = mod; delete o.left[dep]; --o.remaining; } } } if (o.remaining > 0) { pRMs.push(o); } else { cb = o.cb; if (!cb) { continue; } delete o.cb; // to make sure I won't call this more than once! cb.apply(false, o.args); } } pendingRMs = pRMs; if (pendingRMs.length > 0) { setTimeout( function() { Ink._checkPendingRequireModules(); }, 0 ); } }, _modNameToUri: function(modName) { if (modName.indexOf('/') !== -1) { return modName; } var parts = modName.replace(/_/g, '.').split('.'); var root = parts.shift(); var uriPrefix = paths[root]; if (!uriPrefix) { uriPrefix = './' + root + '/'; // console.warn('Not sure where to fetch ' + root + ' modules from! Attempting ' + uriPrefix + '...'); } return [uriPrefix, parts.join('/'), '/lib.js'].join(''); }, getPath: function(key) { return paths[key || 'Ink']; }, setPath: function(key, rootURI) { paths[key] = rootURI; }, /** * loads a javascript script in the head. * * @method loadScript * @param {String} uri can be an http URI or a module name */ loadScript: function(uri) { /*jshint evil:true */ var scriptEl = document.createElement('script'); scriptEl.setAttribute('type', 'text/javascript'); scriptEl.setAttribute('src', this._modNameToUri(uri)); // CHECK ON ALL BROWSERS /*if (document.readyState !== 'complete' && !document.body) { document.write( scriptEl.outerHTML ); } else {*/ var aHead = document.getElementsByTagName('head'); if(aHead.length > 0) { aHead[0].appendChild(scriptEl); } //} }, /** * defines a namespace. * * @method namespace * @param {String} ns * @param {Boolean} [returnParentAndKey] * @return {Array|Object} if returnParentAndKey, returns [parent, lastPart], otherwise return the namespace directly */ namespace: function(ns, returnParentAndKey) { if (!ns || !ns.length) { return null; } var levels = ns.split('.'); var nsobj = window; var parent; for (var i = 0, f = levels.length; i < f; ++i) { nsobj[ levels[i] ] = nsobj[ levels[i] ] || {}; parent = nsobj; nsobj = nsobj[ levels[i] ]; } if (returnParentAndKey) { return [ parent, levels[i-1] ]; } return nsobj; }, /** * synchronous. assumes module is loaded already! * * @method getModule * @param {String} mod * @param {Number} [version] * @return {Object|Function} module object / function */ getModule: function(mod, version) { var key = version ? [mod, '_', version].join('') : mod; return modules[key]; }, /** * must be the wrapper around each Ink lib module for require resolution * * @method createModule * @param {String} mod module name. parts are split with dots * @param {Number} version * @param {Array} deps array of module names which are dependencies for the module being created * @param {Function} modFn its arguments are the resolved dependecies, once all of them are fetched. the body of this function should return the module. */ createModule: function(mod, ver, deps, modFn) { // define var cb = function() { //console.log(['createModule(', mod, ', ', ver, ', [', deps.join(', '), '], ', !!modFn, ')'].join('')); if (typeof mod !== 'string') { throw new Error('module name must be a string!'); } // validate version correctness if (typeof ver === 'number' || (typeof ver === 'string' && ver.length > 0)) { } else { throw new Error('version number missing!'); } var modAll = [mod, '_', ver].join(''); // make sure module in not loaded twice if (modules[modAll]) { //console.warn(['Ink.createModule ', modAll, ': module has been defined already.'].join('')); return; } // delete related pending tasks delete modulesRequested[modAll]; delete modulesRequested[mod]; // run module's supplied factory var args = Array.prototype.slice.call(arguments); var moduleContent = modFn.apply(window, args); modulesLoadOrder.push(modAll); // console.log('** loaded module ' + modAll + '**'); // set version if (typeof moduleContent === 'object') { // Dom.Css Dom.Event moduleContent._version = ver; } else if (typeof moduleContent === 'function') { moduleContent.prototype._version = ver; // if constructor moduleContent._version = ver; // if regular function } // add to global namespace... var isInkModule = mod.indexOf('Ink.') === 0; var t; if (isInkModule) { t = Ink.namespace(mod, true); // for mod 'Ink.Dom.Css', t[0] gets 'Ink.Dom' object and t[1] 'Css' } // versioned modules[ modAll ] = moduleContent; // in modules if (isInkModule) { t[0][ t[1] + '_' + ver ] = moduleContent; // in namespace } // unversioned modules[ mod ] = moduleContent; // in modules if (isInkModule) { if (isEmptyObject( t[0][ t[1] ] )) { t[0][ t[1] ] = moduleContent; // in namespace } else { // console.warn(['Ink.createModule ', modAll, ': module has been defined already with a different version!'].join('')); } } if (this) { // there may be pending requires expecting this module, check... Ink._checkPendingRequireModules(); } }; this.requireModules(deps, cb); }, /** * use this to get depencies, even if they're not loaded yet * * @method requireModules * @param {Array} deps array of module names which are dependencies for the require function body * @param {Function} cbFn its arguments are the resolved dependecies, once all of them are fetched */ requireModules: function(deps, cbFn) { // require //console.log(['requireModules([', deps.join(', '), '], ', !!cbFn, ')'].join('')); var i, f, o, dep, mod; f = deps.length; o = { args: new Array(f), left: {}, remaining: f, cb: cbFn }; if (!(typeof deps === 'object' && deps.length !== undefined)) { throw new Error('Dependency list should be an array!'); } if (typeof cbFn !== 'function') { throw new Error('Callback should be a function!'); } for (i = 0; i < f; ++i) { dep = deps[i]; mod = modules[dep]; if (mod) { o.args[i] = mod; --o.remaining; continue; } else if (modulesRequested[dep]) { } else { modulesRequested[dep] = true; Ink.loadScript(dep); } o.left[dep] = i; } if (o.remaining > 0) { pendingRMs.push(o); } else { cbFn.apply(true, o.args); } }, /** * list or module names, ordered by loaded time * * @method getModulesLoadOrder * @return {Array} returns the order in which modules were resolved and correctly loaded */ getModulesLoadOrder: function() { return modulesLoadOrder.slice(); }, /** * returns the markup you should have to bundle your JS resources yourself * * @return {String} scripts markup */ getModuleScripts: function() { var mlo = this.getModulesLoadOrder(); mlo.unshift('Ink_1'); // console.log(mlo); mlo = mlo.map(function(m) { var cutAt = m.indexOf('.'); if (cutAt === -1) { cutAt = m.indexOf('_'); } var root = m.substring(0, cutAt); m = m.substring(cutAt + 1); var rootPath = Ink.getPath(root); return ['<script type="text/javascript" src="', rootPath, m.replace(/\./g, '/'), '/"></script>'].join(''); }); return mlo.join('\n'); }, /** * Function.prototype.bind alternative. * Additional arguments will be sent to the original function as prefix arguments. * * @method bind * @param {Function} fn * @param {Object} context * @return {Function} */ bind: function(fn, context) { var args = Array.prototype.slice.call(arguments, 2); return function() { var innerArgs = Array.prototype.slice.call(arguments); var finalArgs = args.concat(innerArgs); return fn.apply(context, finalArgs); }; }, /** * Function.prototype.bind alternative for binding class methods * * @method bindMethod * @param {Object} object * @param {String} methodName * @return {Function} * * @example * // Build a function which calls Ink.Dom.Element.remove on an element. * var removeMyElem = Ink.bindMethod(Ink.Dom.Element, 'remove', someElement); * * removeMyElem(); // no arguments, nor Ink.Dom.Element, needed * @example * // (comparison with using Ink.bind to the same effect). * // The following two calls are equivalent * * Ink.bind(this.remove, this, myElem); * Ink.bindMethod(this, 'remove', myElem); */ bindMethod: function (object, methodName) { return this.bind.apply(this, [object[methodName], object].concat([].slice.call(arguments, 2))); }, /** * Function.prototype.bind alternative for event handlers. * Same as bind but keeps first argument of the call the original event. * Additional arguments will be sent to the original function as prefix arguments. * * @method bindEvent * @param {Function} fn * @param {Object} context * @return {Function} */ bindEvent: function(fn, context) { var args = Array.prototype.slice.call(arguments, 2); return function(event) { var finalArgs = args.slice(); finalArgs.unshift(event || window.event); return fn.apply(context, finalArgs); }; }, /** * alias to document.getElementById * * @method i * @param {String} id */ i: function(id) { if(!id) { throw new Error('Ink.i => id or element must be passed'); } if(typeof(id) === 'string') { return document.getElementById(id); } return id; }, /** * alias to sizzle or querySelector * * @method s * @param {String} rule * @param {DOMElement} [from] * @return {DOMElement} */ s: function(rule, from) { if(typeof(Ink.Dom) === 'undefined' || typeof(Ink.Dom.Selector) === 'undefined') { throw new Error('This method requires Ink.Dom.Selector'); } return Ink.Dom.Selector.select(rule, (from || document))[0] || null; }, /** * alias to sizzle or querySelectorAll * * @method ss * @param {String} rule * @param {DOMElement} [from] * @return {Array} array of DOMElements */ ss: function(rule, from) { if(typeof(Ink.Dom) === 'undefined' || typeof(Ink.Dom.Selector) === 'undefined') { throw new Error('This method requires Ink.Dom.Selector'); } return Ink.Dom.Selector.select(rule, (from || document)); }, /** * Enriches the destination object with values from source object whenever the key is missing in destination. * * More than one object can be passed as source, in which case the rightmost objects have precedence. * * @method extendObj * @param {Object} destination * @param {Object...} sources * @return destination object, enriched with defaults from the sources */ extendObj: function(destination, source) { if (arguments.length > 2) { source = Ink.extendObj.apply(this, [].slice.call(arguments, 1)); } if (source) { for (var property in source) { if(Object.prototype.hasOwnProperty.call(source, property)) { destination[property] = source[property]; } } } return destination; } }; // TODO for debug - to detect pending stuff /* var failCount = {}; // fail count per module name var maxFails = 3; // times var checkDelta = 0.5; //seconds var tmpTmr = setInterval(function() { var mk = Object.keys(modulesRequested); var l = mk.length; if (l > 0) { // console.log('** waiting for modules: ' + mk.join(', ') + ' **'); for (var i = 0, f = mk.length, k, v; i < f; ++i) { k = mk[i]; v = failCount[k]; failCount[k] = (v === undefined) ? 1 : ++v; if (v >= maxFails) { console.error('** Loading of module ' + k + ' failed! **'); delete modulesRequested[k]; } } } else { // console.log('** Module loads complete. **'); clearInterval(tmpTmr); } }, checkDelta*1000); */ })(); /** * @author inkdev AT sapo.pt */ Ink.createModule('Ink.Net.Ajax', '1', [], function() { 'use strict'; /** * @module Ink.Net.Ajax_1 */ /** * Creates a new cross browser XMLHttpRequest object * * @class Ink.Net.Ajax * @constructor * * @param {String} url request url * @param {Object} options request options * @param {Boolean} [options.asynchronous] if the request should be asynchronous. true by default. * @param {String} [options.method] HTTP request method. POST by default. * @param {Object|String} [options.parameters] Request parameters which should be sent with the request * @param {Number} [options.timeout] Request timeout * @param {Number} [options.delay] Artificial delay. If request is completed in time lower than this, then wait a bit before calling the callbacks * @param {String} [options.postBody] POST request body. If not specified, it's filled with the contents from parameters * @param {String} [options.contentType] Content-type header to be sent. Defaults to 'application/x-www-form-urlencoded' * @param {Object} [options.requestHeaders] key-value pairs for additional request headers * @param {Function} [options.onComplete] Callback executed after the request is completed, no matter what happens during the request. * @param {Function} [options.onSuccess] Callback executed if the request is successful (requests with 2xx status codes) * @param {Function} [options.onFailure] Callback executed if the request fails (requests with status codes different from 2xx) * @param {Function} [options.onException] Callback executed if an exception occurs. Receives the exception as a parameter. * @param {Function} [options.onCreate] Callback executed after object initialization but before the request is made * @param {Function} [options.onInit] Callback executed before any initialization * @param {Function} [options.onTimeout] Callback executed if the request times out * @param {Boolean|String} [options.evalJS] If the request Content-type header is application/json, evaluates the response and populates responseJSON. Use 'force' if you want to force the response evaluation, no matter what Content-type it's using. Defaults to true. * @param {Boolean} [options.sanitizeJSON] Sanitize the content of responseText before evaluation * @param {String} [options.xhrProxy] URI for proxy service hosted on the same server as the web app, that can fetch documents from other domains. * The service must pipe all input and output untouched (some input sanitization is allowed, like clearing cookies). * e.g., requesting http://example.org/doc can become /proxy/http%3A%2F%2Fexample.org%2Fdoc The proxy service will * be used for cross-domain requests, if set, else a network error is returned as exception. */ var Ajax = function(url, options){ // start of AjaxMock patch - uncomment to enable it /*var AM = SAPO.Communication.AjaxMock; if (AM && !options.inMock) { if (AM.autoRecordThisUrl && AM.autoRecordThisUrl(url)) { return new AM.Record(url, options); } if (AM.mockThisUrl && AM.mockThisUrl(url)) { return new AM.Play(url, options, true); } }*/ // end of AjaxMock patch this.init(url, options); }; /** * Options for all requests. These can then be * overriden for individual ones. */ Ajax.globalOptions = { parameters: {}, requestHeaders: {} }; // IE10 does not need XDomainRequest var xMLHttpRequestWithCredentials = 'XMLHttpRequest' in window && 'withCredentials' in (new XMLHttpRequest()); Ajax.prototype = { init: function(url, userOptions) { if (!url) { throw new Error("WRONG_ARGUMENTS_ERR"); } var options = Ink.extendObj({ asynchronous: true, method: 'POST', parameters: null, timeout: 0, delay: 0, postBody: '', contentType: 'application/x-www-form-urlencoded', requestHeaders: null, onComplete: null, onSuccess: null, onFailure: null, onException: null, onHeaders: null, onCreate: null, onInit: null, onTimeout: null, sanitizeJSON: false, evalJS: true, xhrProxy: '', cors: false, debug: false, useCredentials: false, signRequest: false }, Ajax.globalOptions); if (userOptions && typeof userOptions === 'object') { options = Ink.extendObj(options, userOptions); if (typeof userOptions.parameters === 'object') { options.parameters = Ink.extendObj(Ink.extendObj({}, Ajax.globalOptions.parameters), userOptions.parameters); } else if (userOptions.parameters !== null) { var globalParameters = this.paramsObjToStr(Ajax.globalOptions.parameters); if (globalParameters) { options.parameters = userOptions.parameters + '&' + globalParameters; } } options.requestHeaders = Ink.extendObj({}, Ajax.globalOptions.requestHeaders); options.requestHeaders = Ink.extendObj(options.requestHeaders, userOptions.requestHeaders); } this.options = options; this.safeCall('onInit'); var urlLocation = document.createElementNS ? document.createElementNS('http://www.w3.org/1999/xhtml', 'a') : document.createElement('a'); urlLocation.href = url; this.url = url; this.isHTTP = urlLocation.protocol.match(/^https?:$/i) && true; this.requestHasBody = options.method.search(/^get|head$/i) < 0; if (!this.isHTTP || location.protocol === 'widget:' || typeof window.widget === 'object') { this.isCrossDomain = false; } else { this.isCrossDomain = location.protocol !== urlLocation.protocol || location.host !== urlLocation.host; } if(this.options.cors) { this.isCrossDomain = false; } this.transport = this.getTransport(); this.request(); }, /** * Creates the appropriate XMLHttpRequest object * * @method getTransport * @return {Object} XMLHttpRequest object */ getTransport: function() { /*global XDomainRequest:false, ActiveXObject:false */ if (!xMLHttpRequestWithCredentials && this.options.cors && 'XDomainRequest' in window) { this.usingXDomainReq = true; return new XDomainRequest(); } else if (typeof XMLHttpRequest !== 'undefined') { return new XMLHttpRequest(); } else if (typeof ActiveXObject !== 'undefined') { try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { return new ActiveXObject('Microsoft.XMLHTTP'); } } else { return null; } }, /** * Set the necessary headers for an ajax request * * @method setHeaders * @param {String} url - url for the request */ setHeaders: function() { if (this.transport) { try { var headers = { "Accept": "text/javascript,text/xml,application/xml,application/xhtml+xml,text/html,application/json;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1", "Accept-Language": navigator.language, "X-Requested-With": "XMLHttpRequest", "X-Ink-Version": "1" }; if (this.options.cors) { if (!this.options.signRequest) { delete headers['X-Requested-With']; } delete headers['X-Ink-Version']; } if (this.options.requestHeaders && typeof this.options.requestHeaders === 'object') { for(var headerReqName in this.options.requestHeaders) { if (this.options.requestHeaders.hasOwnProperty(headerReqName)) { headers[headerReqName] = this.options.requestHeaders[headerReqName]; } } } if (this.transport.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) { headers['Connection'] = 'close'; } for (var headerName in headers) { if(headers.hasOwnProperty(headerName)) { this.transport.setRequestHeader(headerName, headers[headerName]); } } } catch(e) {} } }, /** * Converts an object with parameters to a querystring * * @method paramsObjToStr * @param {Object|String} optParams parameters object * @return {String} querystring */ paramsObjToStr: function(optParams) { var k, m, p, a, params = []; if (typeof optParams === 'object') { for (p in optParams){ if (optParams.hasOwnProperty(p)) { a = optParams[p]; if (Object.prototype.toString.call(a) === '[object Array]' && !isNaN(a.length)) { for (k = 0, m = a.length; k < m; k++) { params = params.concat([ encodeURIComponent(p), '[]', '=', encodeURIComponent(a[k]), '&' ]); } } else { params = params.concat([ encodeURIComponent(p), '=', encodeURIComponent(a), '&' ]); } } } if (params.length > 0) { params.pop(); } } else { return optParams; } return params.join(''); }, /** * set the url parameters for a GET request * * @method setParams */ setParams: function() { var params = null, optParams = this.options.parameters; if(typeof optParams === "object"){ params = this.paramsObjToStr(optParams); } else { params = '' + optParams; } if(params){ if(this.url.indexOf('?') > -1) { this.url = this.url.split('#')[0] + '&' + params; } else { this.url = this.url.split('#')[0] + '?' + params; } } }, /** * Retrieves HTTP header from response * * @method getHeader * @param {String} name header name * @return {String} header content */ getHeader: function(name) { if (this.usingXDomainReq && name === 'Content-Type') { return this.transport.contentType; } try{ return this.transport.getResponseHeader(name); } catch(e) { return null; } }, /** * Returns all http headers from the response * * @method getAllHeaders * @return {String} the headers, each separated by a newline */ getAllHeaders: function() { try { return this.transport.getAllResponseHeaders(); } catch(e) { return null; } }, /** * Setup the response object * * @method getResponse * @return {Object} the response object */ getResponse: function(){ // setup our own stuff var t = this.transport, r = { headerJSON: null, responseJSON: null, getHeader: this.getHeader, getAllHeaders: this.getAllHeaders, request: this, transport: t, timeTaken: new Date() - this.startTime, requestedUrl: this.url }; // setup things expected from the native object r.readyState = t.readyState; try { r.responseText = t.responseText; } catch(e) {} try { r.responseXML = t.responseXML; } catch(e) {} try { r.status = t.status; } catch(e) { r.status = 0; } try { r.statusText = t.statusText; } catch(e) { r.statusText = ''; } return r; }, /** * Aborts the request if still running. No callbacks are called * * @method abort */ abort: function(){ if (this.transport) { clearTimeout(this.delayTimeout); clearTimeout(this.stoTimeout); try { this.transport.abort(); } catch(ex) {} this.finish(); } }, /** * Executes the state changing phase of an ajax request * * @method runStateChange */ runStateChange: function() { var rs = this.transport.readyState; if (rs === 3) { if (this.isHTTP) { this.safeCall('onHeaders'); } } else if (rs === 4 || this.usingXDomainReq) { if (this.options.asynchronous && this.options.delay && (this.startTime + this.options.delay > new Date().getTime())) { this.delayTimeout = setTimeout(Ink.bind(this.runStateChange, this), this.options.delay + this.startTime - new Date().getTime()); return; } var responseJSON, responseContent = this.transport.responseText, response = this.getResponse(), curStatus = this.transport.status; if (this.isHTTP && !this.options.asynchronous) { this.safeCall('onHeaders'); } clearTimeout(this.stoTimeout); if (curStatus === 0) { // Status 0 indicates network error for http requests. // For http less requests, 0 is always returned. if (this.isHTTP) { this.safeCall('onException', this.makeError(18, 'NETWORK_ERR')); } else { curStatus = responseContent ? 200 : 404; } } else if (curStatus === 304) { curStatus = 200; } var isSuccess = this.usingXDomainReq || 200 <= curStatus && curStatus < 300; var headerContentType = this.getHeader('Content-Type') || ''; if (this.options.evalJS && (headerContentType.indexOf("application/json") >= 0 || this.options.evalJS === 'force')){ try { responseJSON = this.evalJSON(responseContent, this.sanitizeJSON); if(responseJSON){ responseContent = response.responseJSON = responseJSON; } } catch(e){ if (isSuccess) { // If the request failed, then this is perhaps an error page // so don't notify error. this.safeCall('onException', e); } } } if (this.usingXDomainReq && headerContentType.indexOf('xml') !== -1 && 'DOMParser' in window) { // http://msdn.microsoft.com/en-us/library/ie/ff975278(v=vs.85).aspx var mimeType; switch (headerContentType) { case 'application/xml': case 'application/xhtml+xml': case 'image/svg+xml': mimeType = headerContentType; break; default: mimeType = 'text/xml'; } var xmlDoc = (new DOMParser()).parseFromString( this.transport.responseText, mimeType); this.transport.responseXML = xmlDoc; response.responseXML = xmlDoc; } if (this.transport.responseXML !== null && response.responseJSON === null && this.transport.responseXML.xml !== ""){ responseContent = this.transport.responseXML; } if (curStatus || this.usingXDomainReq) { if (isSuccess) { this.safeCall('onSuccess', response, responseContent); } else { this.safeCall('onFailure', response, responseContent); } this.safeCall('on'+curStatus, response, responseContent); } this.finish(response, responseContent); } }, /** * Last step after XHR is complete. Call onComplete and cleanup object * * @method finish * @param {} response * @param {} responseContent */ finish: function(response, responseContent){ if (response) { this.safeCall('onComplete', response, responseContent); } clearTimeout(this.stoTimeout); if (this.transport) { // IE6 sometimes barfs on this one try{ this.transport.onreadystatechange = null; } catch(e){} if (typeof this.transport.destroy === 'function') { // Stuff for Samsung. this.transport.destroy(); } // Let XHR be collected. this.transport = null; } }, /** * Safely calls a callback function. * Verifies that the callback is well defined and traps errors * * @method safeCall * @param {Function} listener */ safeCall: function(listener, first/*, second*/) { function rethrow(exception){ setTimeout(function() { // Rethrow exception so it'll land in // the error console, firebug, whatever. if (exception.message) { exception.message += '\n'+(exception.stacktrace || exception.stack || ''); } throw exception; }, 1); } if (typeof this.options[listener] === 'function') { //SAPO.safeCall(this, this.options[listener], first, second); //return object[listener].apply(object, [].slice.call(arguments, 2)); try { this.options[listener].apply(this, [].slice.call(arguments, 1)); } catch(ex) { rethrow(ex); } } else if (first && window.Error && (first instanceof Error)) { rethrow(first); } }, /** * Sets new request header for the subsequent http request * * @method setRequestHeader * @param {String} name * @param {String} value */ setRequestHeader: function(name, value){ if (!this.options.requestHeaders) { this.options.requestHeaders = {}; } this.options.requestHeaders[name] = value; }, /** * Execute the request * * @method request */ request: function() { if(this.transport) { var params = null; if(this.requestHasBody) { if(this.options.postBody !== null && this.options.postBody !== '') { params = this.options.postBody; this.setParams(); } else if (this.options.parameters !== null && this.options.parameters !== ''){ params = this.options.parameters; } if (typeof params === "object" && !params.nodeType) { params = this.paramsObjToStr(params); } else if (typeof params !== "object" && params !== null){ params = '' + params; } if(this.options.contentType) { this.setRequestHeader('Content-Type', this.options.contentType); } } else { this.setParams(); } var url = this.url; var method = this.options.method; var crossDomain = this.isCrossDomain; if (crossDomain && this.options.xhrProxy) { this.setRequestHeader('X-Url', url); url = this.options.xhrProxy + encodeURIComponent(url); crossDomain = false; } try { this.transport.open(method, url, this.options.asynchronous); } catch(e) { this.safeCall('onException', e); return this.finish(this.getResponse(), null); } this.setHeaders(); this.safeCall('onCreate'); if(this.options.timeout && !isNaN(this.options.timeout)) { this.stoTimeout = setTimeout(Ink.bind(function() { if(this.options.onTimeout) { this.safeCall('onTimeout'); this.abort(); } }, this), (this.options.timeout * 1000)); } if(this.options.useCredentials && !this.usingXDomainReq) { this.transport.withCredentials = true; } if(this.options.asynchronous && !this.usingXDomainReq) { this.transport.onreadystatechange = Ink.bind(this.runStateChange, this); } else if (this.usingXDomainReq) { this.transport.onload = Ink.bind(this.runStateChange, this); } try { if (crossDomain) { // Need explicit handling because Mozila aborts // the script and Chrome fails silently.per the spec throw this.makeError(18, 'NETWORK_ERR'); } else { this.startTime = new Date().getTime(); this.transport.send(params); } } catch(e) { this.safeCall('onException', e); return this.finish(this.getResponse(), null); } if(!this.options.asynchronous) { this.runStateChange(); } } }, /** * Returns new exception object that can be thrown * * @method makeError * @param code * @param message * @returns {Object} */ makeError: function(code, message){ if (typeof Error !== 'function') { return {code: code, message: message}; } var e = new Error(message); e.code = code; return e; }, /** * Checks if a given string is valid JSON * * @method isJSON * @param {String} str String to be evaluated * @return {Boolean} True if the string is valid JSON */ isJSON: function(str) { if (typeof str !== "string" || !str){ return false; } str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); }, /** * Evaluates a given string as JSON * * @method evalJSON * @param {String} str String to be evaluated * @param {Boolean} sanitize whether to sanitize the content or not * @return {Object} Json content as an object */ evalJSON: function(strJSON, sanitize) { if (strJSON && (!sanitize || this.isJSON(strJSON))) { try { if (typeof JSON !== "undefined" && typeof JSON.parse !== 'undefined'){ return JSON.parse(strJSON); } return eval('(' + strJSON + ')'); } catch(e) { throw new Error('ERROR: Bad JSON string...'); } } return null; } }; /** * Loads content from a given url through a XMLHttpRequest. * Shortcut function for simple AJAX use cases. * * @method load * @param {String} url request url * @param {Function} callback callback to be executed if the request is successful * @return {Object} XMLHttpRequest object */ Ajax.load = function(url, callback){ return new Ajax(url, { method: 'GET', onSuccess: function(response){ callback(response.responseText, response); } }); }; /** * Loads content from a given url through a XMLHttpRequest. * Shortcut function for simple AJAX use cases. * * @method ping * @param {String} url request url * @param {Function} callback callback to be executed if the request is successful * @return {Object} XMLHttpRequest object */ Ajax.ping = function(url, callback){ return new Ajax(url, { method: 'HEAD', onSuccess: function(response){ if (typeof callback === 'function'){ callback(response); } } }); }; return Ajax; }); /** * @author inkdev AT sapo.pt */ Ink.createModule('Ink.Net.JsonP', '1', [], function() { 'use strict'; /** * @module Ink.Net.JsonP_1 */ /** * This class takes care of the nitty-gritty details of doing jsonp requests: Storing * a callback in a globally accessible manner, waiting for the timeout or completion * of the request, and passing extra GET parameters to the server, is not so complicated * but it's boring and repetitive to code and tricky to get right. * * @class Ink.Net.JsonP * @constructor * @param {String} uri * @param {Object} options * @param {Function} options.onSuccess success callback * @param {Function} [options.onFailure] failure callback * @param {Object} [options.failureObj] object to be passed as argument to failure callback * @param {Number} [options.timeout] timeout for request fail, in seconds. defaults to 10 * @param {Object} [options.params] object with the parameters and respective values to unfold * @param {String} [options.callbackParam] parameter to use as callback. defaults to 'jsoncallback' * @param {String} [options.internalCallback] *Advanced*: name of the callback function stored in the Ink.Net.JsonP object. * * @example * Ink.requireModules(['Ink.Net.JsonP_1'], function (JsonP) { * var jsonp = new JsonP('http://path.to.jsonp/endpoint', { * // When the JSONP response arrives, this callback is called: * onSuccess: function (gameData) { * game.startGame(gameData); * }, * // after options.timeout seconds, this callback gets called: * onFailure: function () { * game.error('Could not load game data!'); * }, * timeout: 5 * }); * }); */ var JsonP = function(uri, options) { this.init(uri, options); }; JsonP.prototype = { init: function(uri, options) { this.options = Ink.extendObj( { onSuccess: undefined, onFailure: undefined, failureObj: {}, timeout: 10, params: {}, callbackParam: 'jsoncallback', internalCallback: '_cb', randVar: false }, options || {}); if(this.options.randVar !== false) { this.randVar = this.options.randVar; } else { this.randVar = parseInt(Math.random() * 100000, 10); } this.options.internalCallback += this.randVar; this.uri = uri; // prevent SAPO legacy onComplete - make it onSuccess if(typeof(this.options.onComplete) === 'function') { this.options.onSuccess = this.options.onComplete; } if (typeof this.uri !== 'string') { throw 'Please define an URI'; } if (typeof this.options.onSuccess !== 'function') { throw 'please define a callback function on option onSuccess!'; } Ink.Net.JsonP[this.options.internalCallback] = Ink.bind(function() { window.clearTimeout(this.timeout); delete window.Ink.Net.JsonP[this.options.internalCallback]; this._removeScriptTag(); this.options.onSuccess(arguments[0]); }, this); this._addScriptTag(); }, _addParamsToGet: function(uri, params) { var hasQuestionMark = uri.indexOf('?') !== -1; var sep, pKey, pValue, parts = [uri]; for (pKey in params) { if (params.hasOwnProperty(pKey)) { if (!hasQuestionMark) { sep = '?'; hasQuestionMark = true; } else { sep = '&'; } pValue = params[pKey]; if (typeof pValue !== 'number' && !pValue) { pValue = ''; } parts = parts.concat([sep, pKey, '=', encodeURIComponent(pValue)]); } } return parts.join(''); }, _getScriptContainer: function() { var headEls = document.getElementsByTagName('head'); if (headEls.length === 0) { var scriptEls = document.getElementsByTagName('script'); return scriptEls[0]; } return headEls[0]; }, _addScriptTag: function() { // enrich options will callback and random seed this.options.params[this.options.callbackParam] = 'Ink.Net.JsonP.' + this.options.internalCallback; this.options.params.rnd_seed = this.randVar; this.uri = this._addParamsToGet(this.uri, this.options.params); // create script tag var scriptEl = document.createElement('script'); scriptEl.type = 'text/javascript'; scriptEl.src = this.uri; var scriptCtn = this._getScriptContainer(); scriptCtn.appendChild(scriptEl); this.timeout = setTimeout(Ink.bind(this._requestFailed, this), (this.options.timeout * 1000)); }, _requestFailed : function () { delete Ink.Net.JsonP[this.options.internalCallback]; this._removeScriptTag(); if(typeof this.options.onFailure === 'function'){ this.options.onFailure(this.options.failureObj); } }, _removeScriptTag: function() { var scriptEl; var scriptEls = document.getElementsByTagName('script'); var scriptUri; for (var i = 0, f = scriptEls.length; i < f; ++i) { scriptEl = scriptEls[i]; scriptUri = scriptEl.getAttribute('src') || scriptEl.src; if (scriptUri !== null && scriptUri === this.uri) { scriptEl.parentNode.removeChild(scriptEl); return; } } } }; return JsonP; }); /** * @author inkdev AT sapo.pt */ Ink.createModule( 'Ink.Dom.Css', 1, [], function() { 'use strict'; /** * @module Ink.Dom.Css_1 */ /** * @class Ink.Dom.Css * @static */ var DomCss = { /** * adds or removes a class to the given element according to addRemState * * @method addRemoveClassName * @param {DOMElement|string} elm DOM element or element id * @param {string} className class name to add or remove. * @param {boolean} addRemState Whether to add or remove. `true` to add, `false` to remove. * * @example * Ink.requireModules(['Ink.Dom.Css_1'], function (Css) { * Css.addRemoveClassName(myElm, 'classss', true); // Adds the `classss` class. * Css.addRemoveClassName(myElm, 'classss', false); // Removes the `classss` class. * }); */ addRemoveClassName: function(elm, className, addRemState) { if (addRemState) { return this.addClassName(elm, className); } this.removeClassName(elm, className); }, /** * add a class to a given element * * @method addClassName * @param {DOMElement|String} elm DOM element or element id * @param {String} className */ addClassName: function(elm, className) { elm = Ink.i(elm); if (elm && className) { if (typeof elm.classList !== "undefined"){ elm.classList.add(className); } else if (!this.hasClassName(elm, className)) { elm.className += (elm.className ? ' ' : '') + className; } } }, /** * removes a class from a given element * * @method removeClassName * @param {DOMElement|String} elm DOM element or element id * @param {String} className */ removeClassName: function(elm, className) { elm = Ink.i(elm); if (elm && className) { if (typeof elm.classList !== "undefined"){ elm.classList.remove(className); } else { if (typeof elm.className === "undefined") { return false; } var elmClassName = elm.className, re = new RegExp("(^|\\s+)" + className + "(\\s+|$)"); elmClassName = elmClassName.replace(re, ' '); elmClassName = elmClassName.replace(/^\s+/, '').replace(/\s+$/, ''); elm.className = elmClassName; } } }, /** * Alias to addRemoveClassName. Utility function, saves many if/elses. * * @method setClassName * @param {DOMElement|String} elm DOM element or element id * @param {String} className * @param {Boolean} add true to add, false to remove */ setClassName: function(elm, className, add) { this.addRemoveClassName(elm, className, add || false); }, /** * @method hasClassName * @param {DOMElement|String} elm DOM element or element id * @param {String} className * @return {Boolean} true if a given class is applied to a given element */ hasClassName: function(elm, className) { elm = Ink.i(elm); if (elm && className) { if (typeof elm.classList !== "undefined"){ return elm.classList.contains(className); } else { if (typeof elm.className === "undefined") { return false; } var elmClassName = elm.className; if (typeof elmClassName.length === "undefined") { return false; } if (elmClassName.length > 0) { if (elmClassName === className) { return true; } else { var re = new RegExp("(^|\\s)" + className + "(\\s|$)"); if (re.test(elmClassName)) { return true; } } } } } return false; }, /** * Add and removes the class from the element with a timeout, so it blinks * * @method blinkClass * @param {DOMElement|String} elm DOM element or element id * @param {String} className class name * @param {Boolean} timeout timeout in ms between adding and removing, default 100 ms * @param {Boolean} negate is true, class is removed then added */ blinkClass: function(element, className, timeout, negate){ element = Ink.i(element); this.addRemoveClassName(element, className, !negate); setTimeout(Ink.bind(function() { this.addRemoveClassName(element, className, negate); }, this), Number(timeout) || 100); /* var _self = this; setTimeout(function() { console.log(_self); _self.addRemoveClassName(element, className, negate); }, Number(timeout) || 100); */ }, /** * Add or remove a class name from a given element * * @method toggleClassName * @param {DOMElement|String} elm DOM element or element id * @param {String} className class name * @param {Boolean} forceAdd forces the addition of the class if it doesn't exists */ toggleClassName: function(elm, className, forceAdd) { if (elm && className){ if (typeof elm.classList !== "undefined"){ elm = Ink.i(elm); if (elm !== null){ elm.classList.toggle(className); } return true; } } if (typeof forceAdd !== 'undefined') { if (forceAdd === true) { this.addClassName(elm, className); } else if (forceAdd === false) { this.removeClassName(elm, className); } } else { if (this.hasClassName(elm, className)) { this.removeClassName(elm, className); } else { this.addClassName(elm, className); } } }, /** * sets the opacity of given client a given element * * @method setOpacity * @param {DOMElement|String} elm DOM element or element id * @param {Number} value allows 0 to 1(default mode decimal) or percentage (warning using 0 or 1 will reset to default mode) */ setOpacity: function(elm, value) { elm = Ink.i(elm); if (elm !== null){ var val = 1; if (!isNaN(Number(value))){ if (value <= 0) { val = 0; } else if (value <= 1) { val = value; } else if (value <= 100) { val = value / 100; } else { val = 1; } } if (typeof elm.style.opacity !== 'undefined') { elm.style.opacity = val; } else { elm.style.filter = "alpha(opacity:"+(val*100|0)+")"; } } }, /** * Converts a css property name to a string in camelcase to be used with CSSStyleDeclaration. * @method _camelCase * @private * @param {String} str String to convert * @return {String} Converted string */ _camelCase: function(str) { return str ? str.replace(/-(\w)/g, function (_, $1){ return $1.toUpperCase(); }) : str; }, /** * Gets the value for an element's style attribute * * @method getStyle * @param {DOMElement|String} elm DOM element or element id * @param {String} style Which css attribute to fetch * @return Style value */ getStyle: function(elm, style) { elm = Ink.i(elm); if (elm !== null) { style = style === 'float' ? 'cssFloat': this._camelCase(style); var value = elm.style[style]; if (window.getComputedStyle && (!value || value === 'auto')) { var css = window.getComputedStyle(elm, null); value = css ? css[style] : null; } else if (!value && elm.currentStyle) { value = elm.currentStyle[style]; if (value === 'auto' && (style === 'width' || style === 'height')) { value = elm["offset" + style.charAt(0).toUpperCase() + style.slice(1)] + "px"; } } if (style === 'opacity') { return value ? parseFloat(value, 10) : 1.0; } else if (style === 'borderTopWidth' || style === 'borderBottomWidth' || style === 'borderRightWidth' || style === 'borderLeftWidth' ) { if (value === 'thin') { return '1px'; } else if (value === 'medium') { return '3px'; } else if (value === 'thick') { return '5px'; } } return value === 'auto' ? null : value; } }, /** * Adds CSS rules to an element's style attribute. * * @method setStyle * @param {DOMElement|String} elm DOM element or element id * @param {String} style Which css attribute to set * * @example * <a href="#" class="change-color">Change his color</a> * <p class="him">"He" is me</p> * <script type="text/javascript"> * Ink.requireModules(['Ink.Dom.Css_1', 'Ink.Dom.Event_1', 'Ink.Dom.Selector_1'], function (Css, InkEvent, Selector) { * var btn = Selector.select('.change-color')[0]; * var other = Selector.select('.him')[0]; * InkEvent.observe(btn, 'click', function () { * Css.setStyle(other, 'background-color: black'); * Css.setStyle(other, 'color: white'); * }); * }); * </script> * */ setStyle: function(elm, style) { elm = Ink.i(elm); if (elm !== null) { if (typeof style === 'string') { elm.style.cssText += '; '+style; if (style.indexOf('opacity') !== -1) { this.setOpacity(elm, style.match(/opacity:\s*(\d?\.?\d*)/)[1]); } } else { for (var prop in style) { if (style.hasOwnProperty(prop)){ if (prop === 'opacity') { this.setOpacity(elm, style[prop]); } else { if (prop === 'float' || prop === 'cssFloat') { if (typeof elm.style.styleFloat === 'undefined') { elm.style.cssFloat = style[prop]; } else { elm.style.styleFloat = style[prop]; } } else { elm.style[prop] = style[prop]; } } } } } } }, /** * Makes an element visible * * @method show * @param {DOMElement|String} elm DOM element or element id * @param {String} forceDisplayProperty Css display property to apply on show */ show: function(elm, forceDisplayProperty) { elm = Ink.i(elm); if (elm !== null) { elm.style.display = (forceDisplayProperty) ? forceDisplayProperty : ''; } }, /** * Hides an element * * @method hide * @param {DOMElement|String} elm DOM element or element id */ hide: function(elm) { elm = Ink.i(elm); if (elm !== null) { elm.style.display = 'none'; } }, /** * shows or hides according to param show * * @method showHide * @param {DOMElement|String} elm DOM element or element id * @param {boolean} [show=false] Whether to show or hide `elm`. */ showHide: function(elm, show) { elm = Ink.i(elm); if (elm) { elm.style.display = show ? '' : 'none'; } }, /** * Shows or hides an element depending on current state * @method toggle * @param {DOMElement|String} elm DOM element or element id * @param {Boolean} forceShow Forces showing if element is hidden */ toggle: function(elm, forceShow) { elm = Ink.i(elm); if (elm !== null) { if (typeof forceShow !== 'undefined') { if (forceShow === true) { this.show(elm); } else { this.hide(elm); } } else { if (elm.style.display === 'none') { this.show(elm); } else { this.hide(elm); } } } }, _getRefTag: function(head){ if (head.firstElementChild) { return head.firstElementChild; } for (var child = head.firstChild; child; child = child.nextSibling){ if (child.nodeType === 1){ return child; } } return null; }, /** * Adds css style tags to the head section of a page * * @method appendStyleTag * @param {String} selector The css selector for the rule * @param {String} style The content of the style rule * @param {Object} options Options for the tag * @param {String} [options.type] file type * @param {Boolean} [options.force] if true, style tag will be appended to end of head */ appendStyleTag: function(selector, style, options){ options = Ink.extendObj({ type: 'text/css', force: false }, options || {}); var styles = document.getElementsByTagName("style"), oldStyle = false, setStyle = true, i, l; for (i=0, l=styles.length; i<l; i++) { oldStyle = styles[i].innerHTML; if (oldStyle.indexOf(selector) >= 0) { setStyle = false; } } if (setStyle) { var defStyle = document.createElement("style"), head = document.getElementsByTagName("head")[0], refTag = false, styleStr = ''; defStyle.type = options.type; styleStr += selector +" {"; styleStr += style; styleStr += "} "; if (typeof defStyle.styleSheet !== "undefined") { defStyle.styleSheet.cssText = styleStr; } else { defStyle.appendChild(document.createTextNode(styleStr)); } if (options.force){ head.appendChild(defStyle); } else { refTag = this._getRefTag(head); if (refTag){ head.insertBefore(defStyle, refTag); } } } }, /** * Adds a link tag for a stylesheet to the head section of a page * * @method appendStylesheet * @param {String} path File path * @param {Object} options Options for the tag * @param {String} [options.media='screen'] media type * @param {String} [options.type='text/css'] file type * @param {Boolean} [options.force=false] if true, tag will be appended to end of head */ appendStylesheet: function(path, options){ options = Ink.extendObj({ media: 'screen', type: 'text/css', force: false }, options || {}); var refTag, style = document.createElement("link"), head = document.getElementsByTagName("head")[0]; style.media = options.media; style.type = options.type; style.href = path; style.rel = "Stylesheet"; if (options.force){ head.appendChild(style); } else { refTag = this._getRefTag(head); if (refTag){ head.insertBefore(style, refTag); } } }, /** * Loads CSS via LINK element inclusion in HEAD (skips append if already there) * * Works similarly to appendStylesheet but: * a) supports all browsers; * b) supports optional callback which gets invoked once the CSS has been applied * * @method appendStylesheetCb * @param {String} cssURI URI of the CSS to load, if empty ignores and just calls back directly * @param {Function(cssURI)} [callback] optional callback which will be called once the CSS is loaded */ _loadingCSSFiles: {}, _loadedCSSFiles: {}, appendStylesheetCb: function(url, callback) { if (!url) { return callback(url); } if (this._loadedCSSFiles[url]) { return callback(url); } var cbs = this._loadingCSSFiles[url]; if (cbs) { return cbs.push(callback); } this._loadingCSSFiles[url] = [callback]; var linkEl = document.createElement('link'); linkEl.type = 'text/css'; linkEl.rel = 'stylesheet'; linkEl.href = url; var headEl = document.getElementsByTagName('head')[0]; headEl.appendChild(linkEl); var imgEl = document.createElement('img'); /* var _self = this; (function(_url) { imgEl.onerror = function() { //var url = this; var url = _url; _self._loadedCSSFiles[url] = true; var callbacks = _self._loadingCSSFiles[url]; for (var i = 0, f = callbacks.length; i < f; ++i) { callbacks[i](url); } delete _self._loadingCSSFiles[url]; }; })(url); */ imgEl.onerror = Ink.bindEvent(function(event, _url) { //var url = this; var url = _url; this._loadedCSSFiles[url] = true; var callbacks = this._loadingCSSFiles[url]; for (var i = 0, f = callbacks.length; i < f; ++i) { callbacks[i](url); } delete this._loadingCSSFiles[url]; }, this, url); imgEl.src = url; }, /** * Converts decimal to hexadecimal values, for use with colors * * @method decToHex * @param {String} dec Either a single decimal value, * an rgb(r, g, b) string or an Object with r, g and b properties * @return Hexadecimal value */ decToHex: function(dec) { var normalizeTo2 = function(val) { if (val.length === 1) { val = '0' + val; } val = val.toUpperCase(); return val; }; if (typeof dec === 'object') { var rDec = normalizeTo2(parseInt(dec.r, 10).toString(16)); var gDec = normalizeTo2(parseInt(dec.g, 10).toString(16)); var bDec = normalizeTo2(parseInt(dec.b, 10).toString(16)); return rDec+gDec+bDec; } else { dec += ''; var rgb = dec.match(/\((\d+),\s?(\d+),\s?(\d+)\)/); if (rgb !== null) { return normalizeTo2(parseInt(rgb[1], 10).toString(16)) + normalizeTo2(parseInt(rgb[2], 10).toString(16)) + normalizeTo2(parseInt(rgb[3], 10).toString(16)); } else { return normalizeTo2(parseInt(dec, 10).toString(16)); } } }, /** * Converts hexadecimal values to decimal, for use with colors * * @method hexToDec * @param {String} hex hexadecimal value with 6, 3, 2 or 1 characters * @return {Number} Object with properties r, g, b if length of number is >= 3 or decimal value instead. */ hexToDec: function(hex){ if (hex.indexOf('#') === 0) { hex = hex.substr(1); } if (hex.length === 6) { // will return object RGB return { r: parseInt(hex.substr(0,2), 16), g: parseInt(hex.substr(2,2), 16), b: parseInt(hex.substr(4,2), 16) }; } else if (hex.length === 3) { // will return object RGB return { r: parseInt(hex.charAt(0) + hex.charAt(0), 16), g: parseInt(hex.charAt(1) + hex.charAt(1), 16), b: parseInt(hex.charAt(2) + hex.charAt(2), 16) }; } else if (hex.length <= 2) { // will return int return parseInt(hex, 16); } }, /** * use this to obtain the value of a CSS property (searched from loaded CSS documents) * * @method getPropertyFromStylesheet * @param {String} selector a CSS rule. must be an exact match * @param {String} property a CSS property * @return {String} value of the found property, or null if it wasn't matched */ getPropertyFromStylesheet: function(selector, property) { var rule = this.getRuleFromStylesheet(selector); if (rule) { return rule.style[property]; } return null; }, getPropertyFromStylesheet2: function(selector, property) { var rules = this.getRulesFromStylesheet(selector); /* rules.forEach(function(rule) { var x = rule.style[property]; if (x !== null && x !== undefined) { return x; } }); */ var x; for(var i=0, t=rules.length; i < t; i++) { x = rules[i].style[property]; if (x !== null && x !== undefined) { return x; } } return null; }, getRuleFromStylesheet: function(selector) { var sheet, rules, ri, rf, rule; var s = document.styleSheets; if (!s) { return null; } for (var si = 0, sf = document.styleSheets.length; si < sf; ++si) { sheet = document.styleSheets[si]; rules = sheet.rules ? sheet.rules : sheet.cssRules; if (!rules) { return null; } for (ri = 0, rf = rules.length; ri < rf; ++ri) { rule = rules[ri]; if (!rule.selectorText) { continue; } if (rule.selectorText === selector) { return rule; } } } return null; }, getRulesFromStylesheet: function(selector) { var res = []; var sheet, rules, ri, rf, rule; var s = document.styleSheets; if (!s) { return res; } for (var si = 0, sf = document.styleSheets.length; si < sf; ++si) { sheet = document.styleSheets[si]; rules = sheet.rules ? sheet.rules : sheet.cssRules; if (!rules) { return null; } for (ri = 0, rf = rules.length; ri < rf; ++ri) { rule = rules[ri]; if (!rule.selectorText) { continue; } if (rule.selectorText === selector) { res.push(rule); } } } return res; }, getPropertiesFromRule: function(selector) { var rule = this.getRuleFromStylesheet(selector); var props = {}; var prop, i, f; /*if (typeof rule.style.length === 'snumber') { for (i = 0, f = rule.style.length; i < f; ++i) { prop = this._camelCase( rule.style[i] ); props[prop] = rule.style[prop]; } } else { // HANDLES IE 8, FIREFOX RULE JOINING... */ rule = rule.style.cssText; var parts = rule.split(';'); var steps, val, pre, pos; for (i = 0, f = parts.length; i < f; ++i) { if (parts[i].charAt(0) === ' ') { parts[i] = parts[i].substring(1); } steps = parts[i].split(':'); prop = this._camelCase( steps[0].toLowerCase() ); val = steps[1]; if (val) { val = val.substring(1); if (prop === 'padding' || prop === 'margin' || prop === 'borderWidth') { if (prop === 'borderWidth') { pre = 'border'; pos = 'Width'; } else { pre = prop; pos = ''; } if (val.indexOf(' ') !== -1) { val = val.split(' '); props[pre + 'Top' + pos] = val[0]; props[pre + 'Bottom'+ pos] = val[0]; props[pre + 'Left' + pos] = val[1]; props[pre + 'Right' + pos] = val[1]; } else { props[pre + 'Top' + pos] = val; props[pre + 'Bottom'+ pos] = val; props[pre + 'Left' + pos] = val; props[pre + 'Right' + pos] = val; } } else if (prop === 'borderRadius') { if (val.indexOf(' ') !== -1) { val = val.split(' '); props.borderTopLeftRadius = val[0]; props.borderBottomRightRadius = val[0]; props.borderTopRightRadius = val[1]; props.borderBottomLeftRadius = val[1]; } else { props.borderTopLeftRadius = val; props.borderTopRightRadius = val; props.borderBottomLeftRadius = val; props.borderBottomRightRadius = val; } } else { props[prop] = val; } } } //} //console.log(props); return props; }, /** * Changes the font size of the elements which match the given CSS rule * For this function to work, the CSS file must be in the same domain than the host page, otherwise JS can't access it. * * @method changeFontSize * @param {String} selector CSS selector rule * @param {Number} delta number of pixels to change on font-size * @param {String} [op] supported operations are '+' and '*'. defaults to '+' * @param {Number} [minVal] if result gets smaller than minVal, change does not occurr * @param {Number} [maxVal] if result gets bigger than maxVal, change does not occurr */ changeFontSize: function(selector, delta, op, minVal, maxVal) { var that = this; Ink.requireModules(['Ink.Dom.Selector_1'], function(Selector) { var e; if (typeof selector !== 'string') { e = '1st argument must be a CSS selector rule.'; } else if (typeof delta !== 'number') { e = '2nd argument must be a number.'; } else if (op !== undefined && op !== '+' && op !== '*') { e = '3rd argument must be one of "+", "*".'; } else if (minVal !== undefined && (typeof minVal !== 'number' || minVal <= 0)) { e = '4th argument must be a positive number.'; } else if (maxVal !== undefined && (typeof maxVal !== 'number' || maxVal < maxVal)) { e = '5th argument must be a positive number greater than minValue.'; } if (e) { throw new TypeError(e); } var val, el, els = Selector.select(selector); if (minVal === undefined) { minVal = 1; } op = (op === '*') ? function(a,b){return a*b;} : function(a,b){return a+b;}; for (var i = 0, f = els.length; i < f; ++i) { el = els[i]; val = parseFloat( that.getStyle(el, 'fontSize')); val = op(val, delta); if (val < minVal) { continue; } if (typeof maxVal === 'number' && val > maxVal) { continue; } el.style.fontSize = val + 'px'; } }); } }; return DomCss; }); /** * @author inkdev AT sapo.pt */ Ink.createModule('Ink.Dom.Element', 1, [], function() { 'use strict'; /** * @module Ink.Dom.Element_1 */ /** * @class Ink.Dom.Element */ var Element = { /** * Shortcut for `document.getElementById` * * @method get * @param {String|DOMElement} elm Either an ID of an element, or an element. * @return {DOMElement|null} The DOM element with the given id or null when it was not found */ get: function(elm) { if(typeof elm !== 'undefined') { if(typeof elm === 'string') { return document.getElementById(elm); } return elm; } return null; }, /** * Creates a DOM element * * @method create * @param {String} tag tag name * @param {Object} properties object with properties to be set on the element */ create: function(tag, properties) { var el = document.createElement(tag); //Ink.extendObj(el, properties); for(var property in properties) { if(properties.hasOwnProperty(property)) { if(property === 'className') { property = 'class'; } el.setAttribute(property, properties[property]); } } return el; }, /** * Removes a DOM Element from the DOM * * @method remove * @param {DOMElement} elm The element to remove */ remove: function(el) { var parEl; if (el && (parEl = el.parentNode)) { parEl.removeChild(el); } }, /** * Scrolls the window to an element * * @method scrollTo * @param {DOMElement|String} elm Element where to scroll */ scrollTo: function(elm) { elm = this.get(elm); if(elm) { if (elm.scrollIntoView) { return elm.scrollIntoView(); } var elmOffset = {}, elmTop = 0, elmLeft = 0; do { elmTop += elm.offsetTop || 0; elmLeft += elm.offsetLeft || 0; elm = elm.offsetParent; } while(elm); elmOffset = {x: elmLeft, y: elmTop}; window.scrollTo(elmOffset.x, elmOffset.y); } }, /** * Gets the top cumulative offset for an element * * Requires Ink.Dom.Browser * * @method offsetTop * @param {DOMElement|String} elm target element * @return {Number} Offset from the target element to the top of the document */ offsetTop: function(elm) { return this.offset(elm)[1]; }, /** * Gets the left cumulative offset for an element * * Requires Ink.Dom.Browser * * @method offsetLeft * @param {DOMElement|String} elm target element * @return {Number} Offset from the target element to the left of the document */ offsetLeft: function(elm) { return this.offset(elm)[0]; }, /** * Gets the element offset relative to its closest positioned ancestor * * @method positionedOffset * @param {DOMElement|String} elm target element * @return {Array} Array with the element offsetleft and offsettop relative to the closest positioned ancestor */ positionedOffset: function(element) { var valueTop = 0, valueLeft = 0; element = this.get(element); do { valueTop += element.offsetTop || 0; valueLeft += element.offsetLeft || 0; element = element.offsetParent; if (element) { if (element.tagName.toLowerCase() === 'body') { break; } var value = element.style.position; if (!value && element.currentStyle) { value = element.currentStyle.position; } if ((!value || value === 'auto') && typeof getComputedStyle !== 'undefined') { var css = getComputedStyle(element, null); value = css ? css.position : null; } if (value === 'relative' || value === 'absolute') { break; } } } while (element); return [valueLeft, valueTop]; }, /** * Gets the cumulative offset for an element * * Returns the top left position of the element on the page * * Requires Ink.Dom.Browser * * @method offset * @param {DOMElement|String} elm Target element * @return {[Number, Number]} Array with pixel distance from the target element to the top left corner of the document */ offset: function(el) { /*jshint boss:true */ el = Ink.i(el); var bProp = ['border-left-width', 'border-top-width']; var res = [0, 0]; var dRes, bRes, parent, cs; var getPropPx = this._getPropPx; var InkBrowser = Ink.getModule('Ink.Dom.Browser', 1); do { cs = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle; dRes = [el.offsetLeft | 0, el.offsetTop | 0]; bRes = [getPropPx(cs, bProp[0]), getPropPx(cs, bProp[1])]; if( InkBrowser.OPERA ){ res[0] += dRes[0]; res[1] += dRes[1]; } else { res[0] += dRes[0] + bRes[0]; res[1] += dRes[1] + bRes[1]; } parent = el.offsetParent; } while (el = parent); bRes = [getPropPx(cs, bProp[0]), getPropPx(cs, bProp[1])]; if (InkBrowser.GECKO) { res[0] += bRes[0]; res[1] += bRes[1]; } else if( !InkBrowser.OPERA ) { res[0] -= bRes[0]; res[1] -= bRes[1]; } return res; }, /** * Gets the scroll of the element * * @method scroll * @param {DOMElement|String} [elm] target element or document.body * @returns {Array} offset values for x and y scroll */ scroll: function(elm) { elm = elm ? Ink.i(elm) : document.body; return [ ( ( !window.pageXOffset ) ? elm.scrollLeft : window.pageXOffset ), ( ( !window.pageYOffset ) ? elm.scrollTop : window.pageYOffset ) ]; }, _getPropPx: function(cs, prop) { var n, c; var val = cs.getPropertyValue ? cs.getPropertyValue(prop) : cs[prop]; if (!val) { n = 0; } else { c = val.indexOf('px'); if (c === -1) { n = 0; } else { n = parseInt(val, 10); } } //console.log([prop, ' "', val, '" ', n].join('')); return n; }, /** * Alias for offset() * * @method offset2 * @deprecated Kept for historic reasons. Use offset() instead. */ offset2: function(el) { return this.offset(el); }, /** * Verifies the existence of an attribute * * @method hasAttribute * @param {Object} elm target element * @param {String} attr attribute name * @return {Boolean} Boolean based on existance of attribute */ hasAttribute: function(elm, attr){ return elm.hasAttribute ? elm.hasAttribute(attr) : !!elm.getAttribute(attr); }, /** * Inserts a element immediately after a target element * * @method insertAfter * @param {DOMElement} newElm element to be inserted * @param {DOMElement|String} targetElm key element */ insertAfter: function(newElm, targetElm) { /*jshint boss:true */ if (targetElm = this.get(targetElm)) { targetElm.parentNode.insertBefore(newElm, targetElm.nextSibling); } }, /** * Inserts a element at the top of the childNodes of a target element * * @method insertTop * @param {DOMElement} newElm element to be inserted * @param {DOMElement|String} targetElm key element */ insertTop: function(newElm,targetElm) { // TODO check first child exists /*jshint boss:true */ if (targetElm = this.get(targetElm)) { targetElm.insertBefore(newElm, targetElm.firstChild); } }, /** * Retreives textContent from node * * @method textContent * @param {DOMNode} node from which to retreive text from. Can be any node type. * @return {String} the text */ textContent: function(node){ node = Ink.i(node); var text, k, cs, m; switch(node && node.nodeType) { case 9: /*DOCUMENT_NODE*/ // IE quirks mode does not have documentElement return this.textContent(node.documentElement || node.body && node.body.parentNode || node.body); case 1: /*ELEMENT_NODE*/ text = node.innerText; if (typeof text !== 'undefined') { return text; } /* falls through */ case 11: /*DOCUMENT_FRAGMENT_NODE*/ text = node.textContent; if (typeof text !== 'undefined') { return text; } if (node.firstChild === node.lastChild) { // Common case: 0 or 1 children return this.textContent(node.firstChild); } text = []; cs = node.childNodes; for (k = 0, m = cs.length; k < m; ++k) { text.push( this.textContent( cs[k] ) ); } return text.join(''); case 3: /*TEXT_NODE*/ case 4: /*CDATA_SECTION_NODE*/ return node.nodeValue; } return ''; }, /** * Removes all nodes children and adds the text * * @method setTextContent * @param {DOMNode} node node to add the text to. Can be any node type. * @param {String} text text to be appended to the node. */ setTextContent: function(node, text){ node = Ink.i(node); switch(node && node.nodeType) { case 1: /*ELEMENT_NODE*/ if ('innerText' in node) { node.innerText = text; break; } /* falls through */ case 11: /*DOCUMENT_FRAGMENT_NODE*/ if ('textContent' in node) { node.textContent = text; break; } /* falls through */ case 9: /*DOCUMENT_NODE*/ while(node.firstChild) { node.removeChild(node.firstChild); } if (text !== '') { var doc = node.ownerDocument || node; node.appendChild(doc.createTextNode(text)); } break; case 3: /*TEXT_NODE*/ case 4: /*CDATA_SECTION_NODE*/ node.nodeValue = text; break; } }, /** * Tells if element is a clickable link * * @method isLink * @param {DOMNode} node node to check if it's link * @return {Boolean} */ isLink: function(element){ var b = element && element.nodeType === 1 && ((/^a|area$/i).test(element.tagName) || element.hasAttributeNS && element.hasAttributeNS('http://www.w3.org/1999/xlink','href')); return !!b; }, /** * Tells if ancestor is ancestor of node * * @method isAncestorOf * @param {DOMNode} ancestor ancestor node * @param {DOMNode} node descendant node * @return {Boolean} */ isAncestorOf: function(ancestor, node){ /*jshint boss:true */ if (!node || !ancestor) { return false; } if (node.compareDocumentPosition) { return (ancestor.compareDocumentPosition(node) & 0x10) !== 0;/*Node.DOCUMENT_POSITION_CONTAINED_BY*/ } while (node = node.parentNode){ if (node === ancestor){ return true; } } return false; }, /** * Tells if descendant is descendant of node * * @method descendantOf * @param {DOMNode} node the ancestor * @param {DOMNode} descendant the descendant * @return {Boolean} true if 'descendant' is descendant of 'node' */ descendantOf: function(node, descendant){ return node !== descendant && this.isAncestorOf(node, descendant); }, /** * Get first child in document order of node type 1 * @method firstElementChild * @param {DOMNode} elm parent node * @return {DOMNode} the element child */ firstElementChild: function(elm){ if(!elm) { return null; } if ('firstElementChild' in elm) { return elm.firstElementChild; } var child = elm.firstChild; while(child && child.nodeType !== 1) { child = child.nextSibling; } return child; }, /** * Get last child in document order of node type 1 * @method lastElementChild * @param {DOMNode} elm parent node * @return {DOMNode} the element child */ lastElementChild: function(elm){ if(!elm) { return null; } if ('lastElementChild' in elm) { return elm.lastElementChild; } var child = elm.lastChild; while(child && child.nodeType !== 1) { child = child.previousSibling; } return child; }, /** * Get the first element sibling after the node * * @method nextElementSibling * @param {DOMNode} node current node * @return {DOMNode|Null} the first element sibling after node or null if none is found */ nextElementSibling: function(node){ var sibling = null; if(!node){ return sibling; } if("nextElementSibling" in node){ return node.nextElementSibling; } else { sibling = node.nextSibling; // 1 === Node.ELEMENT_NODE while(sibling && sibling.nodeType !== 1){ sibling = sibling.nextSibling; } return sibling; } }, /** * Get the first element sibling before the node * * @method previousElementSibling * @param {DOMNode} node current node * @return {DOMNode|Null} the first element sibling before node or null if none is found */ previousElementSibling: function(node){ var sibling = null; if(!node){ return sibling; } if("previousElementSibling" in node){ return node.previousElementSibling; } else { sibling = node.previousSibling; // 1 === Node.ELEMENT_NODE while(sibling && sibling.nodeType !== 1){ sibling = sibling.previousSibling; } return sibling; } }, /** * Returns the width of the given element, in pixels * * @method elementWidth * @param {DOMElement|string} element target DOM element or target ID * @return {Number} the element's width */ elementWidth: function(element) { if(typeof element === "string") { element = document.getElementById(element); } return element.offsetWidth; }, /** * Returns the height of the given element, in pixels * * @method elementHeight * @param {DOMElement|string} element target DOM element or target ID * @return {Number} the element's height */ elementHeight: function(element) { if(typeof element === "string") { element = document.getElementById(element); } return element.offsetHeight; }, /** * Returns the element's left position in pixels * * @method elementLeft * @param {DOMElement|string} element target DOM element or target ID * @return {Number} element's left position */ elementLeft: function(element) { if(typeof element === "string") { element = document.getElementById(element); } return element.offsetLeft; }, /** * Returns the element's top position in pixels * * @method elementTop * @param {DOMElement|string} element target DOM element or target ID * @return {Number} element's top position */ elementTop: function(element) { if(typeof element === "string") { element = document.getElementById(element); } return element.offsetTop; }, /** * Returns the dimensions of the given element, in pixels * * @method elementDimensions * @param {element} element target element * @return {Array} array with element's width and height */ elementDimensions: function(element) { element = Ink.i(element); return [element.offsetWidth, element.offsetHeight]; }, /** * Returns the outer (width + margin + padding included) dimensions of an element, in pixels. * * Requires Ink.Dom.Css * * @method uterDimensions * @param {DOMElement} element Target element * @return {Array} Array with element width and height. */ outerDimensions: function (element) { var bbox = Element.elementDimensions(element); var Css = Ink.getModule('Ink.Dom.Css_1'); return [ bbox[0] + parseFloat(Css.getStyle(element, 'marginLeft') || 0) + parseFloat(Css.getStyle(element, 'marginRight') || 0), // w bbox[1] + parseFloat(Css.getStyle(element, 'marginTop') || 0) + parseFloat(Css.getStyle(element, 'marginBottom') || 0) // h ]; }, /** * Check whether an element is inside the viewport * * @method inViewport * @param {DOMElement} element Element to check * @param {Boolean} [partial=false] Return `true` even if it is only partially visible. * @return {Boolean} */ inViewport: function (element, partial) { var rect = Ink.i(element).getBoundingClientRect(); if (partial) { return rect.bottom > 0 && // from the top rect.left < Element.viewportWidth() && // from the right rect.top < Element.viewportHeight() && // from the bottom rect.right > 0; // from the left } else { return rect.top > 0 && // from the top rect.right < Element.viewportWidth() && // from the right rect.bottom < Element.viewportHeight() && // from the bottom rect.left > 0; // from the left } }, /** * Applies the cloneFrom's dimensions to cloneTo * * @method clonePosition * @param {DOMElement} cloneTo element to be position cloned * @param {DOMElement} cloneFrom element to get the cloned position * @return {DOMElement} the element with positionClone */ clonePosition: function(cloneTo, cloneFrom){ var pos = this.offset(cloneFrom); cloneTo.style.left = pos[0]+'px'; cloneTo.style.top = pos[1]+'px'; return cloneTo; }, /** * Slices off a piece of text at the end of the element and adds the ellipsis * so all text fits in the element. * * @method ellipsizeText * @param {DOMElement} element which text is to add the ellipsis * @param {String} [ellipsis] String to append to the chopped text */ ellipsizeText: function(element, ellipsis){ /*jshint boss:true */ if (element = Ink.i(element)){ while (element && element.scrollHeight > (element.offsetHeight + 8)) { element.textContent = element.textContent.replace(/(\s+\S+)\s*$/, ellipsis || '\u2026'); } } }, /** * Searches up the DOM tree for an element fulfilling the boolTest function (returning trueish) * * @method findUpwardsHaving * @param {HtmlElement} element * @param {Function} boolTest * @return {HtmlElement|false} the matched element or false if did not match */ findUpwardsHaving: function(element, boolTest) { while (element && element.nodeType === 1) { if (boolTest(element)) { return element; } element = element.parentNode; } return false; }, /** * Śearches up the DOM tree for an element of specified class name * * @method findUpwardsByClass * @param {HtmlElement} element * @param {String} className * @returns {HtmlElement|false} the matched element or false if did not match */ findUpwardsByClass: function(element, className) { var re = new RegExp("(^|\\s)" + className + "(\\s|$)"); var tst = function(el) { var cls = el.className; return cls && re.test(cls); }; return this.findUpwardsHaving(element, tst); }, /** * Śearches up the DOM tree for an element of specified tag * * @method findUpwardsByTag * @param {HtmlElement} element * @param {String} tag * @returns {HtmlElement|false} the matched element or false if did not match */ findUpwardsByTag: function(element, tag) { tag = tag.toUpperCase(); var tst = function(el) { return el.nodeName && el.nodeName.toUpperCase() === tag; }; return this.findUpwardsHaving(element, tst); }, /** * Śearches up the DOM tree for an element of specified id * * @method findUpwardsById * @param {HtmlElement} element * @param {String} id * @returns {HtmlElement|false} the matched element or false if did not match */ findUpwardsById: function(element, id) { var tst = function(el) { return el.id === id; }; return this.findUpwardsHaving(element, tst); }, /** * Śearches up the DOM tree for an element matching the given selector * * @method findUpwardsBySelector * @param {HtmlElement} element * @param {String} sel * @returns {HtmlElement|false} the matched element or false if did not match */ findUpwardsBySelector: function(element, sel) { if (typeof Ink.Dom === 'undefined' || typeof Ink.Dom.Selector === 'undefined') { throw new Error('This method requires Ink.Dom.Selector'); } var tst = function(el) { return Ink.Dom.Selector.matchesSelector(el, sel); }; return this.findUpwardsHaving(element, tst); }, /** * Returns trimmed text content of descendants * * @method getChildrenText * @param {DOMElement} el element being seeked * @param {Boolean} [removeIt] whether to remove the found text nodes or not * @return {String} text found */ getChildrenText: function(el, removeIt) { var node, j, part, nodes = el.childNodes, jLen = nodes.length, text = ''; if (!el) { return text; } for (j = 0; j < jLen; ++j) { node = nodes[j]; if (!node) { continue; } if (node.nodeType === 3) { // TEXT NODE part = this._trimString( String(node.data) ); if (part.length > 0) { text += part; if (removeIt) { el.removeChild(node); } } else { el.removeChild(node); } } } return text; }, /** * String trim implementation * Used by getChildrenText * * function _trimString * param {String} text * return {String} trimmed text */ _trimString: function(text) { return (String.prototype.trim) ? text.trim() : text.replace(/^\s*/, '').replace(/\s*$/, ''); }, /** * Returns the values of a select element * * @method getSelectValues * @param {DomElement|String} select element * @return {Array} selected values */ getSelectValues: function (select) { var selectEl = Ink.i(select); var values = []; for (var i = 0; i < selectEl.options.length; ++i) { values.push( selectEl.options[i].value ); } return values; }, /* used by fills */ _normalizeData: function(data) { var d, data2 = []; for (var i = 0, f = data.length; i < f; ++i) { d = data[i]; if (!(d instanceof Array)) { // if not array, wraps primitive twice: val -> [val, val] d = [d, d]; } else if (d.length === 1) { // if 1 element array: [val] -> [val, val] d.push(d[0]); } data2.push(d); } return data2; }, /** * Fills select element with choices * * @method fillSelect * @param {DomElement|String} container select element which will get filled * @param {Array} data data which will populate the component * @param {Boolean} [skipEmpty] true to skip empty option * @param {String|Number} [defaultValue] primitive value to select at beginning */ fillSelect: function(container, data, skipEmpty, defaultValue) { var containerEl = Ink.i(container); if (!containerEl) { return; } containerEl.innerHTML = ''; var d, optionEl; if (!skipEmpty) { // add initial empty option optionEl = document.createElement('option'); optionEl.setAttribute('value', ''); containerEl.appendChild(optionEl); } data = this._normalizeData(data); for (var i = 0, f = data.length; i < f; ++i) { d = data[i]; optionEl = document.createElement('option'); optionEl.setAttribute('value', d[0]); if (d.length > 2) { optionEl.setAttribute('extra', d[2]); } optionEl.appendChild( document.createTextNode(d[1]) ); if (d[0] === defaultValue) { optionEl.setAttribute('selected', 'selected'); } containerEl.appendChild(optionEl); } }, /** * Select element on steroids - allows the creation of new values * * @method fillSelect2 * @param {DomElement|String} ctn select element which will get filled * @param {Object} opts * @param {Array} [opts.data] data which will populate the component * @param {Boolean} [opts.skipEmpty] if true empty option is not created (defaults to false) * @param {String} [opts.emptyLabel] label to display on empty option * @param {String} [opts.createLabel] label to display on create option * @param {String} [opts.optionsGroupLabel] text to display on group surrounding value options * @param {String} [opts.defaultValue] option to select initially * @param {Function(selEl, addOptFn)} [opts.onCreate] callback that gets called once user selects the create option */ fillSelect2: function(ctn, opts) { ctn = Ink.i(ctn); ctn.innerHTML = ''; var defs = { skipEmpty: false, skipCreate: false, emptyLabel: 'none', createLabel: 'create', optionsGroupLabel: 'groups', emptyOptionsGroupLabel: 'none exist', defaultValue: '' }; if (!opts) { throw 'param opts is a requirement!'; } if (!opts.data) { throw 'opts.data is a requirement!'; } opts = Ink.extendObj(defs, opts); var optionEl, d; var optGroupValuesEl = document.createElement('optgroup'); optGroupValuesEl.setAttribute('label', opts.optionsGroupLabel); opts.data = this._normalizeData(opts.data); if (!opts.skipCreate) { opts.data.unshift(['$create$', opts.createLabel]); } if (!opts.skipEmpty) { opts.data.unshift(['', opts.emptyLabel]); } for (var i = 0, f = opts.data.length; i < f; ++i) { d = opts.data[i]; optionEl = document.createElement('option'); optionEl.setAttribute('value', d[0]); optionEl.appendChild( document.createTextNode(d[1]) ); if (d[0] === opts.defaultValue) { optionEl.setAttribute('selected', 'selected'); } if (d[0] === '' || d[0] === '$create$') { ctn.appendChild(optionEl); } else { optGroupValuesEl.appendChild(optionEl); } } var lastValIsNotOption = function(data) { var lastVal = data[data.length-1][0]; return (lastVal === '' || lastVal === '$create$'); }; if (lastValIsNotOption(opts.data)) { optionEl = document.createElement('option'); optionEl.setAttribute('value', '$dummy$'); optionEl.setAttribute('disabled', 'disabled'); optionEl.appendChild( document.createTextNode(opts.emptyOptionsGroupLabel) ); optGroupValuesEl.appendChild(optionEl); } ctn.appendChild(optGroupValuesEl); var addOption = function(v, l) { var optionEl = ctn.options[ctn.options.length - 1]; if (optionEl.getAttribute('disabled')) { optionEl.parentNode.removeChild(optionEl); } // create it optionEl = document.createElement('option'); optionEl.setAttribute('value', v); optionEl.appendChild( document.createTextNode(l) ); optGroupValuesEl.appendChild(optionEl); // select it ctn.options[ctn.options.length - 1].setAttribute('selected', true); }; if (!opts.skipCreate) { ctn.onchange = function() { if ((ctn.value === '$create$') && (typeof opts.onCreate === 'function')) { opts.onCreate(ctn, addOption); } }; } }, /** * Creates set of radio buttons, returns wrapper * * @method fillRadios * @param {DomElement|String} insertAfterEl element which will precede the input elements * @param {String} name name to give to the form field ([] is added if not as suffix already) * @param {Array} data data which will populate the component * @param {Boolean} [skipEmpty] true to skip empty option * @param {String|Number} [defaultValue] primitive value to select at beginning * @param {String} [splitEl] name of element to add after each input element (example: 'br') * @return {DOMElement} wrapper element around radio buttons */ fillRadios: function(insertAfterEl, name, data, skipEmpty, defaultValue, splitEl) { var afterEl = Ink.i(insertAfterEl); afterEl = afterEl.nextSibling; while (afterEl && afterEl.nodeType !== 1) { afterEl = afterEl.nextSibling; } var containerEl = document.createElement('span'); if (afterEl) { afterEl.parentNode.insertBefore(containerEl, afterEl); } else { Ink.i(insertAfterEl).appendChild(containerEl); } data = this._normalizeData(data); if (name.substring(name.length - 1) !== ']') { name += '[]'; } var d, inputEl; if (!skipEmpty) { // add initial empty option inputEl = document.createElement('input'); inputEl.setAttribute('type', 'radio'); inputEl.setAttribute('name', name); inputEl.setAttribute('value', ''); containerEl.appendChild(inputEl); if (splitEl) { containerEl.appendChild( document.createElement(splitEl) ); } } for (var i = 0; i < data.length; ++i) { d = data[i]; inputEl = document.createElement('input'); inputEl.setAttribute('type', 'radio'); inputEl.setAttribute('name', name); inputEl.setAttribute('value', d[0]); containerEl.appendChild(inputEl); containerEl.appendChild( document.createTextNode(d[1]) ); if (splitEl) { containerEl.appendChild( document.createElement(splitEl) ); } if (d[0] === defaultValue) { inputEl.checked = true; } } return containerEl; }, /** * Creates set of checkbox buttons, returns wrapper * * @method fillChecks * @param {DomElement|String} insertAfterEl element which will precede the input elements * @param {String} name name to give to the form field ([] is added if not as suffix already) * @param {Array} data data which will populate the component * @param {Boolean} [skipEmpty] true to skip empty option * @param {String|Number} [defaultValue] primitive value to select at beginning * @param {String} [splitEl] name of element to add after each input element (example: 'br') * @return {DOMElement} wrapper element around checkboxes */ fillChecks: function(insertAfterEl, name, data, defaultValue, splitEl) { var afterEl = Ink.i(insertAfterEl); afterEl = afterEl.nextSibling; while (afterEl && afterEl.nodeType !== 1) { afterEl = afterEl.nextSibling; } var containerEl = document.createElement('span'); if (afterEl) { afterEl.parentNode.insertBefore(containerEl, afterEl); } else { Ink.i(insertAfterEl).appendChild(containerEl); } data = this._normalizeData(data); if (name.substring(name.length - 1) !== ']') { name += '[]'; } var d, inputEl; for (var i = 0; i < data.length; ++i) { d = data[i]; inputEl = document.createElement('input'); inputEl.setAttribute('type', 'checkbox'); inputEl.setAttribute('name', name); inputEl.setAttribute('value', d[0]); containerEl.appendChild(inputEl); containerEl.appendChild( document.createTextNode(d[1]) ); if (splitEl) { containerEl.appendChild( document.createElement(splitEl) ); } if (d[0] === defaultValue) { inputEl.checked = true; } } return containerEl; }, /** * Returns index of element from parent, -1 if not child of parent... * * @method parentIndexOf * @param {DOMElement} parentEl Element to parse * @param {DOMElement} childEl Child Element to look for * @return {Number} */ parentIndexOf: function(parentEl, childEl) { var node, idx = 0; for (var i = 0, f = parentEl.childNodes.length; i < f; ++i) { node = parentEl.childNodes[i]; if (node.nodeType === 1) { // ELEMENT if (node === childEl) { return idx; } ++idx; } } return -1; }, /** * Returns an array of elements - the next siblings * * @method nextSiblings * @param {String|DomElement} elm element * @return {Array} Array of next sibling elements */ nextSiblings: function(elm) { if(typeof(elm) === "string") { elm = document.getElementById(elm); } if(typeof(elm) === 'object' && elm !== null && elm.nodeType && elm.nodeType === 1) { var elements = [], siblings = elm.parentNode.children, index = this.parentIndexOf(elm.parentNode, elm); for(var i = ++index, len = siblings.length; i<len; i++) { elements.push(siblings[i]); } return elements; } return []; }, /** * Returns an array of elements - the previous siblings * * @method previousSiblings * @param {String|DomElement} elm element * @return {Array} Array of previous sibling elements */ previousSiblings: function(elm) { if(typeof(elm) === "string") { elm = document.getElementById(elm); } if(typeof(elm) === 'object' && elm !== null && elm.nodeType && elm.nodeType === 1) { var elements = [], siblings = elm.parentNode.children, index = this.parentIndexOf(elm.parentNode, elm); for(var i = 0, len = index; i<len; i++) { elements.push(siblings[i]); } return elements; } return []; }, /** * Returns an array of elements - its siblings * * @method siblings * @param {String|DomElement} elm element * @return {Array} Array of sibling elements */ siblings: function(elm) { if(typeof(elm) === "string") { elm = document.getElementById(elm); } if(typeof(elm) === 'object' && elm !== null && elm.nodeType && elm.nodeType === 1) { var elements = [], siblings = elm.parentNode.children; for(var i = 0, len = siblings.length; i<len; i++) { if(elm !== siblings[i]) { elements.push(siblings[i]); } } return elements; } return []; }, /** * fallback to elem.childElementCount * * @method childElementCount * @param {String|DomElement} elm element * @return {Number} number of child elements */ childElementCount: function(elm) { elm = Ink.i(elm); if ('childElementCount' in elm) { return elm.childElementCount; } if (!elm) { return 0; } return this.siblings(elm).length + 1; }, /** * parses and appends an html string to a container, not destroying its contents * * @method appendHTML * @param {String|DomElement} elm element * @param {String} html markup string */ appendHTML: function(elm, html){ var temp = document.createElement('div'); temp.innerHTML = html; var tempChildren = temp.children; for (var i = 0; i < tempChildren.length; i++){ elm.appendChild(tempChildren[i]); } }, /** * parses and prepends an html string to a container, not destroying its contents * * @method prependHTML * @param {String|DomElement} elm element * @param {String} html markup string */ prependHTML: function(elm, html){ var temp = document.createElement('div'); temp.innerHTML = html; var first = elm.firstChild; var tempChildren = temp.children; for (var i = tempChildren.length - 1; i >= 0; i--){ elm.insertBefore(tempChildren[i], first); first = elm.firstChild; } }, /** * Removes direct children on type text. * Useful to remove nasty layout gaps generated by whitespace on the markup. * * @method removeTextNodeChildren * @param {DOMElement} el */ removeTextNodeChildren: function(el) { var prevEl, toRemove, parent = el; el = el.firstChild; while (el) { toRemove = (el.nodeType === 3); prevEl = el; el = el.nextSibling; if (toRemove) { parent.removeChild(prevEl); } } }, /** * Pass an HTML string and receive a documentFragment with the corresponding elements * @method htmlToFragment * @param {String} html html string * @return {DocumentFragment} DocumentFragment containing all of the elements from the html string */ htmlToFragment: function(html){ /*jshint boss:true */ /*global Range:false */ if(typeof document.createRange === 'function' && typeof Range.prototype.createContextualFragment === 'function'){ this.htmlToFragment = function(html){ var range; if(typeof html !== 'string'){ return document.createDocumentFragment(); } range = document.createRange(); // set the context to document.body (firefox does this already, webkit doesn't) range.selectNode(document.body); return range.createContextualFragment(html); }; } else { this.htmlToFragment = function(html){ var fragment = document.createDocumentFragment(), tempElement, current; if(typeof html !== 'string'){ return fragment; } tempElement = document.createElement('div'); tempElement.innerHTML = html; // append child removes elements from the original parent while(current = tempElement.firstChild){ // intentional assignment fragment.appendChild(current); } return fragment; }; } return this.htmlToFragment.call(this, html); }, _camelCase: function(str) { return str ? str.replace(/-(\w)/g, function (_, $1){ return $1.toUpperCase(); }) : str; }, /** * Gets all of the data attributes from an element * * @method data * @param {String|DomElement} selector Element or CSS selector * @return {Object} Object with the data-* properties. If no data-attributes are present, an empty object is returned. */ data: function(selector) { var el; if (typeof selector !== 'object' && typeof selector !== 'string') { throw '[Ink.Dom.Element.data] :: Invalid selector defined'; } if (typeof selector === 'object') { el = selector; } else { var InkDomSelector = Ink.getModule('Ink.Dom.Selector', 1); if (!InkDomSelector) { throw "[Ink.Dom.Element.data] :: This method requires Ink.Dom.Selector - v1"; } el = InkDomSelector.select(selector); if (el.length <= 0) { throw "[Ink.Dom.Element.data] :: Can't find any element with the specified selector"; } el = el[0]; } var dataset = {}; var attrs = el.attributes || []; var curAttr, curAttrName, curAttrValue; if (attrs) { for (var i = 0, total = attrs.length; i < total; ++i) { curAttr = attrs[i]; curAttrName = curAttr.name; curAttrValue = curAttr.value; if (curAttrName && curAttrName.indexOf('data-') === 0) { dataset[this._camelCase(curAttrName.replace('data-', ''))] = curAttrValue; } } } return dataset; }, /** * @method moveCursorTo * @param {Input|Textarea} el * @param {Number} t */ moveCursorTo: function(el, t) { if (el.setSelectionRange) { el.setSelectionRange(t, t); //el.focus(); } else { var range = el.createTextRange(); range.collapse(true); range.moveEnd( 'character', t); range.moveStart('character', t); range.select(); } }, /** * @method pageWidth * @return {Number} page width */ pageWidth: function() { var xScroll; if (window.innerWidth && window.scrollMaxX) { xScroll = window.innerWidth + window.scrollMaxX; } else if (document.body.scrollWidth > document.body.offsetWidth){ xScroll = document.body.scrollWidth; } else { xScroll = document.body.offsetWidth; } var windowWidth; if (window.self.innerWidth) { if(document.documentElement.clientWidth){ windowWidth = document.documentElement.clientWidth; } else { windowWidth = window.self.innerWidth; } } else if (document.documentElement && document.documentElement.clientWidth) { windowWidth = document.documentElement.clientWidth; } else if (document.body) { windowWidth = document.body.clientWidth; } if(xScroll < windowWidth){ return xScroll; } else { return windowWidth; } }, /** * @method pageHeight * @return {Number} page height */ pageHeight: function() { var yScroll; if (window.innerHeight && window.scrollMaxY) { yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ yScroll = document.body.scrollHeight; } else { yScroll = document.body.offsetHeight; } var windowHeight; if (window.self.innerHeight) { windowHeight = window.self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { windowHeight = document.documentElement.clientHeight; } else if (document.body) { windowHeight = document.body.clientHeight; } if(yScroll < windowHeight){ return windowHeight; } else { return yScroll; } }, /** * @method viewportWidth * @return {Number} viewport width */ viewportWidth: function() { if(typeof window.innerWidth !== "undefined") { return window.innerWidth; } if (document.documentElement && typeof document.documentElement.offsetWidth !== "undefined") { return document.documentElement.offsetWidth; } }, /** * @method viewportHeight * @return {Number} viewport height */ viewportHeight: function() { if (typeof window.innerHeight !== "undefined") { return window.innerHeight; } if (document.documentElement && typeof document.documentElement.offsetHeight !== "undefined") { return document.documentElement.offsetHeight; } }, /** * @method scrollWidth * @return {Number} scroll width */ scrollWidth: function() { if (typeof window.self.pageXOffset !== 'undefined') { return window.self.pageXOffset; } if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.scrollLeft !== 'undefined') { return document.documentElement.scrollLeft; } return document.body.scrollLeft; }, /** * @method scrollHeight * @return {Number} scroll height */ scrollHeight: function() { if (typeof window.self.pageYOffset !== 'undefined') { return window.self.pageYOffset; } if (typeof document.documentElement !== 'undefined' && typeof document.documentElement.scrollTop !== 'undefined') { return document.documentElement.scrollTop; } return document.body.scrollTop; } }; return Element; }); /** * @author inkdev AT sapo.pt */ Ink.createModule('Ink.Dom.Event', 1, [], function() { 'use strict'; /** * @module Ink.Dom.Event_1 */ /** * @class Ink.Dom.Event */ var Event = { KEY_BACKSPACE: 8, KEY_TAB: 9, KEY_RETURN: 13, KEY_ESC: 27, KEY_LEFT: 37, KEY_UP: 38, KEY_RIGHT: 39, KEY_DOWN: 40, KEY_DELETE: 46, KEY_HOME: 36, KEY_END: 35, KEY_PAGEUP: 33, KEY_PAGEDOWN: 34, KEY_INSERT: 45, /** * Returns a function which calls `func`, waiting at least `wait` * milliseconds between calls. This is useful for events such as `scroll` * or `resize`, which can be triggered too many times per second, slowing * down the browser with needless function calls. * * *note:* This does not delay the first function call to the function. * * @method throttle * @param {Function} func Function to call. Arguments and context are both passed. * @param {Number} [wait=0] Milliseconds to wait between calls. * * @example * * // BEFORE * InkEvent.observe(window, 'scroll', function () { * ... * }); // When scrolling on mobile devices or on firefox's smooth scroll * // this is expensive because onscroll is called many times * * // AFTER * InkEvent.observe(window, 'scroll', InkEvent.throttle(function () { * ... * }, 100)); // The event handler is called only every 100ms. Problem solved. * * @example * var handler = InkEvent.throttle(function () { * ... * }, 100); * * InkEvent.observe(window, 'scroll', handler); * InkEvent.observe(window, 'resize', handler); * * // on resize, both the "scroll" and the "resize" events are triggered * // a LOT of times. This prevents both of them being called a lot of * // times when the window is being resized by a user. * **/ throttle: function (func, wait) { wait = wait || 0; var lastCall = 0; // Warning: This breaks on Jan 1st 1970 0:00 var timeout; var throttled = function () { var now = +new Date(); var timeDiff = now - lastCall; if (timeDiff >= wait) { lastCall = now; return func.apply(this, [].slice.call(arguments)); } else { var that = this; var args = [].slice.call(arguments); clearTimeout(timeout); timeout = setTimeout(function () { return throttled.apply(that, args); }); } }; return throttled; }, /** * Returns the target of the event object * * @method element * @param {Object} ev event object * @return {Node} The target */ element: function(ev) { var node = ev.target || // IE stuff (ev.type === 'mouseout' && ev.fromElement) || (ev.type === 'mouseleave' && ev.fromElement) || (ev.type === 'mouseover' && ev.toElement) || (ev.type === 'mouseenter' && ev.toElement) || ev.srcElement || null; return node && (node.nodeType === 3 || node.nodeType === 4) ? node.parentNode : node; }, /** * Returns the related target of the event object * * @method relatedTarget * @param {Object} ev event object * @return {Node} The related target */ relatedTarget: function(ev){ var node = ev.relatedTarget || // IE stuff (ev.type === 'mouseout' && ev.toElement) || (ev.type === 'mouseleave' && ev.toElement) || (ev.type === 'mouseover' && ev.fromElement) || (ev.type === 'mouseenter' && ev.fromElement) || null; return node && (node.nodeType === 3 || node.nodeType === 4) ? node.parentNode : node; }, /** * Navigate up the DOM tree, looking for a tag with the name `elmTagName`. * * If such tag is not found, `document` is returned. * * @method findElement * @param {Object} ev event object * @param {String} elmTagName tag name to find * @param {Boolean} [force=false] If this is true, never return `document`, and returns `false` instead. * @return {DOMElement} the first element which matches given tag name or the document element if the wanted tag is not found */ findElement: function(ev, elmTagName, force) { var node = this.element(ev); while(true) { if(node.nodeName.toLowerCase() === elmTagName.toLowerCase()) { return node; } else { node = node.parentNode; if(!node) { if(force) { return false; } return document; } if(!node.parentNode){ if(force){ return false; } return document; } } } }, /** * Dispatches an event to element * * @method fire * @param {DOMElement|String} element element id or element * @param {String} eventName event name * @param {Object} [memo] metadata for the event */ fire: function(element, eventName, memo) { element = Ink.i(element); var ev, nativeEvents; if(document.createEvent){ nativeEvents = { "DOMActivate": true, "DOMFocusIn": true, "DOMFocusOut": true, "focus": true, "focusin": true, "focusout": true, "blur": true, "load": true, "unload": true, "abort": true, "error": true, "select": true, "change": true, "submit": true, "reset": true, "resize": true, "scroll": true, "click": true, "dblclick": true, "mousedown": true, "mouseenter": true, "mouseleave": true, "mousemove": true, "mouseover": true, "mouseout": true, "mouseup": true, "mousewheel": true, "wheel": true, "textInput": true, "keydown": true, "keypress": true, "keyup": true, "compositionstart": true, "compositionupdate": true, "compositionend": true, "DOMSubtreeModified": true, "DOMNodeInserted": true, "DOMNodeRemoved": true, "DOMNodeInsertedIntoDocument": true, "DOMNodeRemovedFromDocument": true, "DOMAttrModified": true, "DOMCharacterDataModified": true, "DOMAttributeNameChanged": true, "DOMElementNameChanged": true, "hashchange": true }; } else { nativeEvents = { "onabort": true, "onactivate": true, "onafterprint": true, "onafterupdate": true, "onbeforeactivate": true, "onbeforecopy": true, "onbeforecut": true, "onbeforedeactivate": true, "onbeforeeditfocus": true, "onbeforepaste": true, "onbeforeprint": true, "onbeforeunload": true, "onbeforeupdate": true, "onblur": true, "onbounce": true, "oncellchange": true, "onchange": true, "onclick": true, "oncontextmenu": true, "oncontrolselect": true, "oncopy": true, "oncut": true, "ondataavailable": true, "ondatasetchanged": true, "ondatasetcomplete": true, "ondblclick": true, "ondeactivate": true, "ondrag": true, "ondragend": true, "ondragenter": true, "ondragleave": true, "ondragover": true, "ondragstart": true, "ondrop": true, "onerror": true, "onerrorupdate": true, "onfilterchange": true, "onfinish": true, "onfocus": true, "onfocusin": true, "onfocusout": true, "onhashchange": true, "onhelp": true, "onkeydown": true, "onkeypress": true, "onkeyup": true, "onlayoutcomplete": true, "onload": true, "onlosecapture": true, "onmessage": true, "onmousedown": true, "onmouseenter": true, "onmouseleave": true, "onmousemove": true, "onmouseout": true, "onmouseover": true, "onmouseup": true, "onmousewheel": true, "onmove": true, "onmoveend": true, "onmovestart": true, "onoffline": true, "ononline": true, "onpage": true, "onpaste": true, "onprogress": true, "onpropertychange": true, "onreadystatechange": true, "onreset": true, "onresize": true, "onresizeend": true, "onresizestart": true, "onrowenter": true, "onrowexit": true, "onrowsdelete": true, "onrowsinserted": true, "onscroll": true, "onselect": true, "onselectionchange": true, "onselectstart": true, "onstart": true, "onstop": true, "onstorage": true, "onstoragecommit": true, "onsubmit": true, "ontimeout": true, "onunload": true }; } if(element !== null && element !== undefined){ if (element === document && document.createEvent && !element.dispatchEvent) { element = document.documentElement; } if (document.createEvent) { ev = document.createEvent("HTMLEvents"); if(typeof nativeEvents[eventName] === "undefined"){ ev.initEvent("dataavailable", true, true); } else { ev.initEvent(eventName, true, true); } } else { ev = document.createEventObject(); if(typeof nativeEvents["on"+eventName] === "undefined"){ ev.eventType = "ondataavailable"; } else { ev.eventType = "on"+eventName; } } ev.eventName = eventName; ev.memo = memo || { }; try { if (document.createEvent) { element.dispatchEvent(ev); } else if(element.fireEvent){ element.fireEvent(ev.eventType, ev); } else { return; } } catch(ex) {} return ev; } }, _callbackForCustomEvents: function (element, eventName, callBack) { var isHashChangeInIE = eventName === "hashchange" && element.attachEvent && !window.onhashchange; var isCustomEvent = eventName.indexOf(':') !== -1; if (isHashChangeInIE || isCustomEvent) { /** * * prevent that each custom event fire without any test * This prevents that if you have multiple custom events * on dataavailable to trigger the callback event if it * is a different custom event * */ var argCallback = callBack; return Ink.bindEvent(function(ev, eventName, cb){ //tests if it is our event and if not //check if it is IE and our dom:loaded was overrided (IE only supports one ondatavailable) //- fix /opera also supports attachEvent and was firing two events // if(ev.eventName === eventName || (Ink.Browser.IE && eventName === 'dom:loaded')){ if(ev.eventName === eventName){ //fix for FF since it loses the event in case of using a second binObjEvent if(window.addEventListener){ window.event = ev; } cb(); } }, this, eventName, argCallback); } else { return null; } }, /** * Attaches an event to element * * @method observe * @param {DOMElement|String} element Element id or element * @param {String} eventName Event name * @param {Function} callBack Receives event object as a * parameter. If you're manually firing custom events, check the * eventName property of the event object to make sure you're handling * the right event. * @param {Boolean} [useCapture] Set to true to change event listening from bubbling to capture. * @return {Function} The event handler used. Hang on to this if you want to `stopObserving` later. */ observe: function(element, eventName, callBack, useCapture) { element = Ink.i(element); if(element !== null && element !== undefined) { /* rare corner case: some events need a different callback to be generated */ var callbackForCustomEvents = this._callbackForCustomEvents(element, eventName, callBack); if (callbackForCustomEvents) { callBack = callbackForCustomEvents; eventName = 'dataavailable'; } if(element.addEventListener) { element.addEventListener(eventName, callBack, !!useCapture); } else { element.attachEvent('on' + eventName, callBack); } return callBack; } }, /** * Attaches an event to a selector or array of elements. * * Requires Ink.Dom.Selector or a browser with Element.querySelectorAll. * * Ink.Dom.Event.observe * * @method observeMulti * @param {Array|String} elements * @param ... See the `observe` function. * @return {Function} The used callback. */ observeMulti: function (elements, eventName, callBack, useCapture) { if (typeof elements === 'string') { elements = Ink.ss(elements); } else if (elements instanceof Element) { elements = [elements]; } if (!elements[0]) { return false; } var callbackForCustomEvents = this._callbackForCustomEvents(elements[0], eventName, callBack); if (callbackForCustomEvents) { callBack = callbackForCustomEvents; eventName = 'dataavailable'; } for (var i = 0, len = elements.length; i < len; i++) { this.observe(elements[i], eventName, callBack, useCapture); } return callBack; }, /** * Remove an event attached to an element * * @method stopObserving * @param {DOMElement|String} element element id or element * @param {String} eventName event name * @param {Function} callBack callback function * @param {Boolean} [useCapture] set to true if the event was being observed with useCapture set to true as well. */ stopObserving: function(element, eventName, callBack, useCapture) { element = Ink.i(element); if(element !== null && element !== undefined) { if(element.removeEventListener) { element.removeEventListener(eventName, callBack, !!useCapture); } else { element.detachEvent('on' + eventName, callBack); } } }, /** * Stops event propagation and bubbling * * @method stop * @param {Object} event event handle */ stop: function(event) { if(event.cancelBubble !== null) { event.cancelBubble = true; } if(event.stopPropagation) { event.stopPropagation(); } if(event.preventDefault) { event.preventDefault(); } if(window.attachEvent) { event.returnValue = false; } if(event.cancel !== null) { event.cancel = true; } }, /** * Stops event propagation * * @method stopPropagation * @param {Object} event event handle */ stopPropagation: function(event) { if(event.cancelBubble !== null) { event.cancelBubble = true; } if(event.stopPropagation) { event.stopPropagation(); } }, /** * Stops event default behaviour * * @method stopDefault * @param {Object} event event handle */ stopDefault: function(event) { if(event.preventDefault) { event.preventDefault(); } if(window.attachEvent) { event.returnValue = false; } if(event.cancel !== null) { event.cancel = true; } }, /** * @method pointer * @param {Object} ev event object * @return {Object} an object with the mouse X and Y position */ pointer: function(ev) { return { x: ev.pageX || (ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)), y: ev.pageY || (ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop)) }; }, /** * @method pointerX * @param {Object} ev event object * @return {Number} mouse X position */ pointerX: function(ev) { return ev.pageX || (ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)); }, /** * @method pointerY * @param {Object} ev event object * @return {Number} mouse Y position */ pointerY: function(ev) { return ev.pageY || (ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop)); }, /** * @method isLeftClick * @param {Object} ev event object * @return {Boolean} True if the event is a left mouse click */ isLeftClick: function(ev) { if (window.addEventListener) { if(ev.button === 0){ return true; } else if(ev.type.substring(0,5) === 'touch' && ev.button === null){ return true; } } else { if(ev.button === 1){ return true; } } return false; }, /** * @method isRightClick * @param {Object} ev event object * @return {Boolean} True if there is a right click on the event */ isRightClick: function(ev) { return (ev.button === 2); }, /** * @method isMiddleClick * @param {Object} ev event object * @return {Boolean} True if there is a middle click on the event */ isMiddleClick: function(ev) { if (window.addEventListener) { return (ev.button === 1); } else { return (ev.button === 4); } return false; }, /** * Work in Progress. * Used in SAPO.Component.MaskedInput * * @method getCharFromKeyboardEvent * @param {KeyboardEvent} event keyboard event * @param {optional Boolean} [changeCasing] if true uppercases, if false lowercases, otherwise keeps casing * @return {String} character representation of pressed key combination */ getCharFromKeyboardEvent: function(event, changeCasing) { var k = event.keyCode; var c = String.fromCharCode(k); var shiftOn = event.shiftKey; if (k >= 65 && k <= 90) { // A-Z if (typeof changeCasing === 'boolean') { shiftOn = changeCasing; } return (shiftOn) ? c : c.toLowerCase(); } else if (k >= 96 && k <= 105) { // numpad digits return String.fromCharCode( 48 + (k-96) ); } switch (k) { case 109: case 189: return '-'; case 107: case 187: return '+'; } return c; }, debug: function(){} }; return Event; }); /** * @module Ink.Dom.FormSerialize * @author inkdev AT sapo.pt */ Ink.createModule('Ink.Dom.FormSerialize', 1, [], function () { 'use strict'; /** * Supports serialization of form data to/from javascript Objects. * * Valid applications are ad hoc AJAX/syndicated submission of forms, restoring form values from server side state, etc. * * @class Ink.Dom.FormSerialize * */ var FormSerialize = { /** * Serializes a form into an object, turning field names into keys, and field values into values. * * note: Multi-select and checkboxes with multiple values will yield arrays * * @method serialize * @return {Object} map of fieldName -> String|String[]|Boolean * @param {DomElement|String} form form element from which the extraction is to occur * * @example * <form id="frm"> * <input type="text" name="field1"> * <button type="submit">Submit</button> * </form> * <script type="text/javascript"> * Ink.requireModules(['Ink.Dom.FormSerialize_1', 'Ink.Dom.Event_1'], function (FormSerialize, InkEvent) { * InkEvent.observe('frm', 'submit', function (event) { * var formData = FormSerialize.serialize('frm'); // -> {field1:"123"} * InkEvent.stop(event); * }); * }); * </script> */ serialize: function(form) { form = Ink.i(form); var map = this._getFieldNameInputsMap(form); var map2 = {}; for (var k in map) if (map.hasOwnProperty(k)) { if(k !== null) { var tmpK = k.replace(/\[\]$/, ''); map2[tmpK] = this._getValuesOfField( map[k] ); } else { map2[k] = this._getValuesOfField( map[k] ); } } delete map2['null']; // this can occur. if so, delete it... return map2; }, /** * Sets form elements's values with values given from object * * One cannot restore the values of an input with `type="file"` (browser prohibits it) * * @method fillIn * @param {DomElement|String} form form element which is to be populated * @param {Object} map2 map of fieldName -> String|String[]|Boolean * @example * <form id="frm"> * <input type="text" name="field1"> * <button type="submit">Submit</button> * </form> * <script type="text/javascript"> * Ink.requireModules(['Ink.Dom.FormSerialize_1'], function (FormSerialize) { * var values = {field1: 'CTHULHU'}; * FormSerialize.fillIn('frm', values); * // At this point the form is pre-filled with the values above. * }); * </script> */ fillIn: function(form, map2) { form = Ink.i(form); var map = this._getFieldNameInputsMap(form); delete map['null']; // this can occur. if so, delete it... for (var k in map2) if (map2.hasOwnProperty(k)) { this._setValuesOfField( map[k], map2[k] ); } }, _getFieldNameInputsMap: function(formEl) { var name, nodeName, el, map = {}; for (var i = 0, f = formEl.elements.length; i < f; ++i) { el = formEl.elements[i]; name = el.getAttribute('name'); nodeName = el.nodeName.toLowerCase(); if (nodeName === 'fieldset') { continue; } else if (map[name] === undefined) { map[name] = [el]; } else { map[name].push(el); } } return map; }, _getValuesOfField: function(fieldInputs) { var nodeName = fieldInputs[0].nodeName.toLowerCase(); var type = fieldInputs[0].getAttribute('type'); var value = fieldInputs[0].value; var i, f, j, o, el, m, res = []; switch(nodeName) { case 'select': for (i = 0, f = fieldInputs.length; i < f; ++i) { res[i] = []; m = fieldInputs[i].getAttribute('multiple'); for (j = 0, o = fieldInputs[i].options.length; j < o; ++j) { el = fieldInputs[i].options[j]; if (el.selected) { if (m) { res[i].push(el.value); } else { res[i] = el.value; break; } } } } return ((fieldInputs.length > 0 && /\[[^\]]*\]$/.test(fieldInputs[0].getAttribute('name'))) ? res : res[0]); case 'textarea': case 'input': if (type === 'checkbox' || type === 'radio') { for (i = 0, f = fieldInputs.length; i < f; ++i) { el = fieldInputs[i]; if (el.checked) { res.push( el.value ); } } if (type === 'checkbox') { return (fieldInputs.length > 1) ? res : !!(res.length); } return (fieldInputs.length > 1) ? res[0] : !!(res.length); // on radios only 1 option is selected at most } else { //if (fieldInputs.length > 1) { throw 'Got multiple input elements with same name!'; } if(fieldInputs.length > 0 && /\[[^\]]*\]$/.test(fieldInputs[0].getAttribute('name'))) { var tmpValues = []; for(i=0, f = fieldInputs.length; i < f; ++i) { tmpValues.push(fieldInputs[i].value); } return tmpValues; } else { return value; } } break; // to keep JSHint happy... (reply to this comment by gamboa: - ROTFL) default: //throw 'Unsupported element: "' + nodeName + '"!'; return undefined; } }, _valInArray: function(val, arr) { for (var i = 0, f = arr.length; i < f; ++i) { if (arr[i] === val) { return true; } } return false; }, _setValuesOfField: function(fieldInputs, fieldValues) { if (!fieldInputs) { return; } var nodeName = fieldInputs[0].nodeName.toLowerCase(); var type = fieldInputs[0].getAttribute('type'); var i, f, el; switch(nodeName) { case 'select': if (fieldInputs.length > 1) { throw 'Got multiple select elements with same name!'; } for (i = 0, f = fieldInputs[0].options.length; i < f; ++i) { el = fieldInputs[0].options[i]; el.selected = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : el.value === fieldValues; } break; case 'textarea': case 'input': if (type === 'checkbox' || type === 'radio') { for (i = 0, f = fieldInputs.length; i < f; ++i) { el = fieldInputs[i]; //el.checked = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : el.value === fieldValues; el.checked = (fieldValues instanceof Array) ? this._valInArray(el.value, fieldValues) : (fieldInputs.length > 1 ? el.value === fieldValues : !!fieldValues); } } else { if (fieldInputs.length > 1) { throw 'Got multiple input elements with same name!'; } if (type !== 'file') { fieldInputs[0].value = fieldValues; } } break; default: throw 'Unsupported element: "' + nodeName + '"!'; } } }; return FormSerialize; }); /** * @module Ink.Dom.Loaded_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Dom.Loaded', 1, [], function() { 'use strict'; /** * The Loaded class provides a method that allows developers to queue functions to run when * the page is loaded (document is ready). * * @class Ink.Dom.Loaded * @version 1 * @static */ var Loaded = { /** * Callbacks and their contexts. Array of 2-arrays. * * [] * * @attribute _contexts Array * @private * */ _contexts: [], // Callbacks' queue /** * Adds a new function that will be invoked once the document is ready * * @method run * @param {Object} [win=window] Window object to attach/add the event * @param {Function} fn Callback function to be run after the page is loaded * @public * @example * Ink.requireModules(['Ink.Dom.Loaded_1'], function(Loaded){ * Loaded.run(function(){ * console.log('This will run when the page/document is ready/loaded'); * }); * }); */ run: function(win, fn) { if (!fn) { fn = win; win = window; } var context; for (var i = 0, len = this._contexts.length; i < len; i++) { if (this._contexts[i][0] === win) { context = this._contexts[i][1]; break; } } if (!context) { context = { cbQueue: [], win: win, doc: win.document, root: win.document.documentElement, done: false, top: true }; context.handlers = { checkState: Ink.bindEvent(this._checkState, this, context), poll: Ink.bind(this._poll, this, context) }; this._contexts.push( [win, context] // Javascript Objects cannot map different windows to // different values. ); } var ael = context.doc.addEventListener; context.add = ael ? 'addEventListener' : 'attachEvent'; context.rem = ael ? 'removeEventListener' : 'detachEvent'; context.pre = ael ? '' : 'on'; context.det = ael ? 'DOMContentLoaded' : 'onreadystatechange'; context.wet = context.pre + 'load'; var csf = context.handlers.checkState; var alreadyLoaded = ( context.doc.readyState === 'complete' && context.win.location.toString() !== 'about:blank'); // https://code.google.com/p/chromium/issues/detail?id=32357 if (alreadyLoaded){ setTimeout(Ink.bind(function () { fn.call(context.win, 'lazy'); }, this), 0); } else { context.cbQueue.push(fn); context.doc[context.add]( context.det , csf ); context.win[context.add]( context.wet , csf ); var frameElement = 1; try{ frameElement = context.win.frameElement; } catch(e) {} if ( !ael && context.root && context.root.doScroll ) { // IE HACK try { context.top = !frameElement; } catch(e) { } if (context.top) { this._poll(context); } } } }, /** * Function that will be running the callbacks after the page is loaded * * @method _checkState * @param {Event} event Triggered event * @private */ _checkState: function(event, context) { if ( !event || (event.type === 'readystatechange' && context.doc.readyState !== 'complete')) { return; } var where = (event.type === 'load') ? context.win : context.doc; where[context.rem](context.pre+event.type, context.handlers.checkState, false); this._ready(context); }, /** * Polls the load progress of the page to see if it has already loaded or not * * @method _poll * @private */ /** * * function _poll */ _poll: function(context) { try { context.root.doScroll('left'); } catch(e) { return setTimeout(context.handlers.poll, 50); } this._ready(context); }, /** * Function that runs the callbacks from the queue when the document is ready. * * @method _ready * @private */ _ready: function(context) { if (!context.done) { context.done = true; for (var i = 0; i < context.cbQueue.length; ++i) { context.cbQueue[i].call(context.win); } context.cbQueue = []; } } }; return Loaded; }); /** * @module Ink.Dom.Selector_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Dom.Selector', 1, [], function() { /*jshint forin:false, eqnull:true*/ 'use strict'; /** * @class Ink.Dom.Selector * @static * @version 1 */ /*! * Sizzle CSS Selector Engine * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ var i, cachedruns, Expr, getText, isXML, compile, outermostContext, recompare, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function() { return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } /* * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /* * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /* * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /* * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /* * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /* * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementsByName privileges form controls or returns elements by ID // If so, assume (for broader support) that getElementById returns elements by name support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; // Support: Windows 8 Native Apps // Assigning innerHTML with "name" attributes throws uncatchable exceptions // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx div.appendChild( document.createElement("a") ).setAttribute( "name", expando ); div.appendChild( document.createElement("i") ).setAttribute( "name", expando ); docElem.appendChild( div ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; // Cleanup docElem.removeChild( div ); return pass; }); // Support: Webkit<537.32 // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { return div1.compareDocumentPosition && // Should return 1, but Webkit returns 4 (following) (div1.compareDocumentPosition( document.createElement("div") ) & 1); }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getByName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (recompare && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && documentIsHTML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( documentIsHTML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( !documentIsHTML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; // Compensate for sort limitations recompare = !support.sortDetached; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /* * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /* * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // Check sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize with the default document setDocument(); // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; // EXPOSE /*if ( typeof define === "function" && define.amd ) { define(function() { return Sizzle; }); } else { window.Sizzle = Sizzle; }*/ // EXPOSE /** * Alias for the Sizzle selector engine * * @method select * @param {String} selector CSS selector to search for elements * @param {DOMElement} [context] By default the search is done in the document element. However, you can specify an element as search context * @param {Array} [results] By default this is considered an empty array. But if you want to merge it with other searches you did, pass their result array through here. * @param {Object} [seed] * @return {Array} Array of resulting DOM Elements */ /** * Returns elements which match with the second argument to the function. * * @method matches * @param {String} selector CSS selector to search for elements * @param {Array} matches Elements to be 'matched' with * @return {Array} Elements that matched */ /** * Returns true iif element matches given selector * * @method matchesSelector * @param {DOMElement} element to test * @param {String} selector CSS selector to test the element with * @return {Boolean} true iif element matches the CSS selector */ return { select: Sizzle, matches: Sizzle.matches, matchesSelector: Sizzle.matchesSelector }; }); //( window ); /** * @module Ink.Dom.Browser_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Dom.Browser', '1', [], function() { 'use strict'; /** * @class Ink.Dom.Browser * @version 1 * @static * @example * <input type="text" id="dPicker" /> * <script> * Ink.requireModules(['Ink.Dom.Browser_1'],function( InkBrowser ){ * if( InkBrowser.CHROME ){ * console.log( 'This is a CHROME browser.' ); * } * }); * </script> */ var Browser = { /** * True if the browser is Internet Explorer * * @property IE * @type {Boolean} * @public * @static */ IE: false, /** * True if the browser is Gecko based * * @property GECKO * @type {Boolean} * @public * @static */ GECKO: false, /** * True if the browser is Opera * * @property OPERA * @type {Boolean} * @public * @static */ OPERA: false, /** * True if the browser is Safari * * @property SAFARI * @type {Boolean} * @public * @static */ SAFARI: false, /** * True if the browser is Konqueror * * @property KONQUEROR * @type {Boolean} * @public * @static */ KONQUEROR: false, /** * True if browser is Chrome * * @property CHROME * @type {Boolean} * @public * @static */ CHROME: false, /** * The specific browser model. False if it is unavailable. * * @property model * @type {Boolean|String} * @public * @static */ model: false, /** * The browser version. False if it is unavailable. * * @property version * @type {Boolean|String} * @public * @static */ version: false, /** * The user agent string. False if it is unavailable. * * @property userAgent * @type {Boolean|String} * @public * @static */ userAgent: false, /** * Initialization function for the Browser object. * * Is called automatically when this module is loaded, and calls setDimensions, setBrowser and setReferrer. * * @method init * @public */ init: function() { this.detectBrowser(); this.setDimensions(); this.setReferrer(); }, /** * Retrieves and stores window dimensions in this object. Called automatically when this module is loaded. * * @method setDimensions * @public */ setDimensions: function() { //this.windowWidth=window.innerWidth !== null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body !== null ? document.body.clientWidth : null; //this.windowHeight=window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null; var myWidth = 0, myHeight = 0; if ( typeof window.innerWidth=== 'number' ) { myWidth = window.innerWidth; myHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { myWidth = document.body.clientWidth; myHeight = document.body.clientHeight; } this.windowWidth = myWidth; this.windowHeight = myHeight; }, /** * Stores the referrer. Called automatically when this module is loaded. * * @method setReferrer * @public */ setReferrer: function() { this.referrer = document.referrer !== undefined? document.referrer.length > 0 ? window.escape(document.referrer) : false : false; }, /** * Detects the browser and stores the found properties. Called automatically when this module is loaded. * * @method detectBrowser * @public */ detectBrowser: function() { var sAgent = navigator.userAgent; this.userAgent = sAgent; sAgent = sAgent.toLowerCase(); if((new RegExp("applewebkit\/")).test(sAgent)) { if((new RegExp("chrome\/")).test(sAgent)) { // Chrome this.CHROME = true; this.model = 'chrome'; this.version = sAgent.replace(new RegExp("(.*)chrome\/([^\\s]+)(.*)"), "$2"); this.cssPrefix = '-webkit-'; this.domPrefix = 'Webkit'; } else { // Safari this.SAFARI = true; this.model = 'safari'; this.version = sAgent.replace(new RegExp("(.*)applewebkit\/([^\\s]+)(.*)"), "$2"); this.cssPrefix = '-webkit-'; this.domPrefix = 'Webkit'; } } else if((new RegExp("opera")).test(sAgent)) { // Opera this.OPERA = true; this.model = 'opera'; this.version = sAgent.replace(new RegExp("(.*)opera.([^\\s$]+)(.*)"), "$2"); this.cssPrefix = '-o-'; this.domPrefix = 'O'; } else if((new RegExp("konqueror")).test(sAgent)) { // Konqueror this.KONQUEROR = true; this.model = 'konqueror'; this.version = sAgent.replace(new RegExp("(.*)konqueror\/([^;]+);(.*)"), "$2"); this.cssPrefix = '-khtml-'; this.domPrefix = 'Khtml'; } else if((new RegExp("msie\\ ")).test(sAgent)) { // MSIE this.IE = true; this.model = 'ie'; this.version = sAgent.replace(new RegExp("(.*)\\smsie\\s([^;]+);(.*)"), "$2"); this.cssPrefix = '-ms-'; this.domPrefix = 'ms'; } else if((new RegExp("gecko")).test(sAgent)) { // GECKO // Supports only: // Camino, Chimera, Epiphany, Minefield (firefox 3), Firefox, Firebird, Phoenix, Galeon, // Iceweasel, K-Meleon, SeaMonkey, Netscape, Songbird, Sylera, this.GECKO = true; var re = new RegExp("(camino|chimera|epiphany|minefield|firefox|firebird|phoenix|galeon|iceweasel|k\\-meleon|seamonkey|netscape|songbird|sylera)"); if(re.test(sAgent)) { this.model = sAgent.match(re)[1]; this.version = sAgent.replace(new RegExp("(.*)"+this.model+"\/([^;\\s$]+)(.*)"), "$2"); this.cssPrefix = '-moz-'; this.domPrefix = 'Moz'; } else { // probably is mozilla this.model = 'mozilla'; var reVersion = new RegExp("(.*)rv:([^)]+)(.*)"); if(reVersion.test(sAgent)) { this.version = sAgent.replace(reVersion, "$2"); } this.cssPrefix = '-moz-'; this.domPrefix = 'Moz'; } } }, /** * Debug function which displays browser (and Ink.Dom.Browser) information as an alert message. * * @method debug * @public * * @example * * The following code * * Ink.requireModules(['Ink.Dom.Browser_1'], function (Browser) { * Browser.debug(); * }); * * Alerts (On Firefox 22): * * known browsers: (ie, gecko, opera, safari, konqueror) * false,true,false,false,false * model -> firefox * version -> 22.0 * * original UA -> Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0 */ debug: function() { /*global alert:false */ var str = "known browsers: (ie, gecko, opera, safari, konqueror) \n"; str += [this.IE, this.GECKO, this.OPERA, this.SAFARI, this.KONQUEROR] +"\n"; str += "model -> "+this.model+"\n"; str += "version -> "+this.version+"\n"; str += "\n"; str += "original UA -> "+this.userAgent; alert(str); } }; Browser.init(); return Browser; }); /** * @module Ink.Util.Url_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.Url', '1', [], function() { 'use strict'; /** * Utility functions to use with URLs * * @class Ink.Util.Url * @version 1 * @static */ var Url = { /** * Auxiliary string for encoding * * @property _keyStr * @type {String} * @readOnly * @private */ _keyStr : 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', /** * Get current URL of page * * @method getUrl * @return {String} Current URL * @public * @static * @example * Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){ * console.log( InkUrl.getUrl() ); // Will return it's window URL * }); */ getUrl: function() { return window.location.href; }, /** * Generates an uri with query string based on the parameters object given * * @method genQueryString * @param {String} uri * @param {Object} params * @return {String} URI with query string set * @public * @static * @example * Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){ * var queryString = InkUrl.genQueryString( 'http://www.sapo.pt/', { * 'param1': 'valueParam1', * 'param2': 'valueParam2' * }); * * console.log( queryString ); // Result: http://www.sapo.pt/?param1=valueParam1&param2=valueParam2 * }); */ genQueryString: function(uri, params) { var hasQuestionMark = uri.indexOf('?') !== -1; var sep, pKey, pValue, parts = [uri]; for (pKey in params) { if (params.hasOwnProperty(pKey)) { if (!hasQuestionMark) { sep = '?'; hasQuestionMark = true; } else { sep = '&'; } pValue = params[pKey]; if (typeof pValue !== 'number' && !pValue) { pValue = ''; } parts = parts.concat([sep, encodeURIComponent(pKey), '=', encodeURIComponent(pValue)]); } } return parts.join(''); }, /** * Get query string of current or passed URL * * @method getQueryString * @param {String} [str] URL String. When not specified it uses the current URL. * @return {Object} Key-Value object with the pairs variable: value * @public * @static * @example * Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){ * var queryStringParams = InkUrl.getQueryString( 'http://www.sapo.pt/?var1=valueVar1&var2=valueVar2' ); * console.log( queryStringParams ); * // Result: * // { * // var1: 'valueVar1', * // var2: 'valueVar2' * // } * }); */ getQueryString: function(str) { var url; if(str && typeof(str) !== 'undefined') { url = str; } else { url = this.getUrl(); } var aParams = {}; if(url.match(/\?(.+)/i)) { var queryStr = url.replace(/^(.*)\?([^\#]+)(\#(.*))?/g, "$2"); if(queryStr.length > 0) { var aQueryStr = queryStr.split(/[;&]/); for(var i=0; i < aQueryStr.length; i++) { var pairVar = aQueryStr[i].split('='); aParams[decodeURIComponent(pairVar[0])] = (typeof(pairVar[1]) !== 'undefined' && pairVar[1]) ? decodeURIComponent(pairVar[1]) : false; } } } return aParams; }, /** * Get URL hash * * @method getAnchor * @param {String} [str] URL String. If not set, it will get the current URL. * @return {String|Boolean} Hash in the URL. If there's no hash, returns false. * @public * @static * @example * Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){ * var anchor = InkUrl.getAnchor( 'http://www.sapo.pt/page.php#TEST' ); * console.log( anchor ); // Result: TEST * }); */ getAnchor: function(str) { var url; if(str && typeof(str) !== 'undefined') { url = str; } else { url = this.getUrl(); } var anchor = false; if(url.match(/#(.+)/)) { anchor = url.replace(/([^#]+)#(.*)/, "$2"); } return anchor; }, /** * Get anchor string of current or passed URL * * @method getAnchorString * @param {String} [string] If not provided it uses the current URL. * @return {Object} Returns a key-value object of the 'variables' available in the hashtag of the URL * @public * @static * @example * Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){ * var hashParams = InkUrl.getAnchorString( 'http://www.sapo.pt/#var1=valueVar1&var2=valueVar2' ); * console.log( hashParams ); * // Result: * // { * // var1: 'valueVar1', * // var2: 'valueVar2' * // } * }); */ getAnchorString: function(string) { var url; if(string && typeof(string) !== 'undefined') { url = string; } else { url = this.getUrl(); } var aParams = {}; if(url.match(/#(.+)/i)) { var anchorStr = url.replace(/^([^#]+)#(.*)?/g, "$2"); if(anchorStr.length > 0) { var aAnchorStr = anchorStr.split(/[;&]/); for(var i=0; i < aAnchorStr.length; i++) { var pairVar = aAnchorStr[i].split('='); aParams[decodeURIComponent(pairVar[0])] = (typeof(pairVar[1]) !== 'undefined' && pairVar[1]) ? decodeURIComponent(pairVar[1]) : false; } } } return aParams; }, /** * Parse passed URL * * @method parseUrl * @param {String} url URL to be parsed * @return {Object} Parsed URL as a key-value object. * @public * @static * @example * Ink.requireModules(['Ink.Util.Url_1'], function( InkUrl ){ * var parsedURL = InkUrl.parseUrl( 'http://www.sapo.pt/index.html?var1=value1#anchor' ) * console.log( parsedURL ); * // Result: * // { * // 'scheme' => 'http', * // 'host' => 'www.sapo.pt', * // 'path' => '/index.html', * // 'query' => 'var1=value1', * // 'fragment' => 'anchor' * // } * }); * */ parseUrl: function(url) { var aURL = {}; if(url && typeof(url) !== 'undefined' && typeof(url) === 'string') { if(url.match(/^([^:]+):\/\//i)) { var re = /^([^:]+):\/\/([^\/]*)\/?([^\?#]*)\??([^#]*)#?(.*)/i; if(url.match(re)) { aURL.scheme = url.replace(re, "$1"); aURL.host = url.replace(re, "$2"); aURL.path = '/'+url.replace(re, "$3"); aURL.query = url.replace(re, "$4") || false; aURL.fragment = url.replace(re, "$5") || false; } } else { var re1 = new RegExp("^([^\\?]+)\\?([^#]+)#(.*)", "i"); var re2 = new RegExp("^([^\\?]+)\\?([^#]+)#?", "i"); var re3 = new RegExp("^([^\\?]+)\\??", "i"); if(url.match(re1)) { aURL.scheme = false; aURL.host = false; aURL.path = url.replace(re1, "$1"); aURL.query = url.replace(re1, "$2"); aURL.fragment = url.replace(re1, "$3"); } else if(url.match(re2)) { aURL.scheme = false; aURL.host = false; aURL.path = url.replace(re2, "$1"); aURL.query = url.replace(re2, "$2"); aURL.fragment = false; } else if(url.match(re3)) { aURL.scheme = false; aURL.host = false; aURL.path = url.replace(re3, "$1"); aURL.query = false; aURL.fragment = false; } } if(aURL.host) { var regPort = new RegExp("^(.*)\\:(\\d+)$","i"); // check for port if(aURL.host.match(regPort)) { var tmpHost1 = aURL.host; aURL.host = tmpHost1.replace(regPort, "$1"); aURL.port = tmpHost1.replace(regPort, "$2"); } else { aURL.port = false; } // check for user and pass if(aURL.host.match(/@/i)) { var tmpHost2 = aURL.host; aURL.host = tmpHost2.split('@')[1]; var tmpUserPass = tmpHost2.split('@')[0]; if(tmpUserPass.match(/\:/)) { aURL.user = tmpUserPass.split(':')[0]; aURL.pass = tmpUserPass.split(':')[1]; } else { aURL.user = tmpUserPass; aURL.pass = false; } } } } return aURL; }, /** * Get last loaded script element * * @method currentScriptElement * @param {String} [match] String to match against the script src attribute * @return {DOMElement|Boolean} Returns the <script> DOM Element or false if unable to find it. * @public * @static */ currentScriptElement: function(match) { var aScripts = document.getElementsByTagName('script'); if(typeof(match) === 'undefined') { if(aScripts.length > 0) { return aScripts[(aScripts.length - 1)]; } else { return false; } } else { var curScript = false; var re = new RegExp(""+match+"", "i"); for(var i=0, total = aScripts.length; i < total; i++) { curScript = aScripts[i]; if(re.test(curScript.src)) { return curScript; } } return false; } }, /* base64Encode: function(string) { /** * --function {String} ? * --Convert a string to BASE 64 * @param {String} string - string to convert * @return base64 encoded string * * if(!SAPO.Utility.String || typeof(SAPO.Utility.String) === 'undefined') { throw "SAPO.Utility.Url.base64Encode depends of SAPO.Utility.String, which has not been referred."; } var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; var input = SAPO.Utility.String.utf8Encode(string); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, base64Decode: function(string) { * --function {String} ? * Decode a BASE 64 encoded string * --param {String} string base64 encoded string * --return string decoded if(!SAPO.Utility.String || typeof(SAPO.Utility.String) === 'undefined') { throw "SAPO.Utility.Url.base64Decode depends of SAPO.Utility.String, which has not been referred."; } var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; var input = string.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } output = SAPO.Utility.String.utf8Decode(output); return output; }, */ /** * Debug function ? * * @method _debug * @private * @static */ _debug: function() {} }; return Url; }); /** * @module Ink.Util.Swipe_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.Swipe', '1', ['Ink.Dom.Event_1'], function(Event) { 'use strict'; /** * Subscribe swipe gestures! * Supports filtering swipes be any combination of the criteria supported in the options. * * @class Ink.Util.Swipe * @constructor * @version 1 * * @param {String|DOMElement} selector * @param {Object} [options] Options for the Swipe detection * @param {Function} [options.callback] Function to be called when a swipe is detected. Default is undefined. * @param {Number} [options.forceAxis] Specify in which axis the swipe will be detected (x or y). Default is both. * @param {Number} [options.maxDist] maximum allowed distance, in pixels * @param {Number} [options.maxDuration] maximum allowed duration, in seconds * @param {Number} [options.minDist] minimum allowed distance, in pixels * @param {Number} [options.minDuration] minimum allowed duration, in seconds * @param {Boolean} [options.stopEvents] Flag that specifies if it should stop events. Default is true. * @param {Boolean} [options.storeGesture] Stores the gesture to be used for other purposes. */ var Swipe = function(el, options) { this._options = Ink.extendObj({ callback: undefined, forceAxis: undefined, // x | y maxDist: undefined, maxDuration: undefined, minDist: undefined, // in pixels minDuration: undefined, // in seconds stopEvents: true, storeGesture: false }, options || {}); this._handlers = { down: Ink.bindEvent(this._onDown, this), move: Ink.bindEvent(this._onMove, this), up: Ink.bindEvent(this._onUp, this) }; this._element = Ink.i(el); this._init(); }; Swipe._supported = ('ontouchstart' in document.documentElement); Swipe.prototype = { /** * Initialization function. Called by the constructor. * * @method _init * @private */ _init: function() { var db = document.body; Event.observe(db, 'touchstart', this._handlers.down); if (this._options.storeGesture) { Event.observe(db, 'touchmove', this._handlers.move); } Event.observe(db, 'touchend', this._handlers.up); this._isOn = false; }, /** * Function to compare/get the parent of an element. * * @method _isMeOrParent * @param {DOMElement} el Element to be compared with its parent * @param {DOMElement} parentEl Element to be compared used as reference * @return {DOMElement|Boolean} ParentElement of el or false in case it can't. * @private */ _isMeOrParent: function(el, parentEl) { if (!el) { return; } do { if (el === parentEl) { return true; } el = el.parentNode; } while (el); return false; }, /** * MouseDown/TouchStart event handler * * @method _onDown * @param {EventObject} ev window.event object * @private */ _onDown: function(ev) { if (event.changedTouches.length !== 1) { return; } if (!this._isMeOrParent(ev.target, this._element)) { return; } if( this._options.stopEvents === true ){ Event.stop(ev); } ev = ev.changedTouches[0]; this._isOn = true; this._target = ev.target; this._t0 = new Date().valueOf(); this._p0 = [ev.pageX, ev.pageY]; if (this._options.storeGesture) { this._gesture = [this._p0]; this._time = [0]; } }, /** * MouseMove/TouchMove event handler * * @method _onMove * @param {EventObject} ev window.event object * @private */ _onMove: function(ev) { if (!this._isOn || event.changedTouches.length !== 1) { return; } if( this._options.stopEvents === true ){ Event.stop(ev); } ev = ev.changedTouches[0]; var t1 = new Date().valueOf(); var dt = (t1 - this._t0) * 0.001; this._gesture.push([ev.pageX, ev.pageY]); this._time.push(dt); }, /** * MouseUp/TouchEnd event handler * * @method _onUp * @param {EventObject} ev window.event object * @private */ _onUp: function(ev) { if (!this._isOn || event.changedTouches.length !== 1) { return; } if (this._options.stopEvents) { Event.stop(ev); } ev = ev.changedTouches[0]; // TODO SHOULD CHECK IT IS THE SAME TOUCH this._isOn = false; var t1 = new Date().valueOf(); var p1 = [ev.pageX, ev.pageY]; var dt = (t1 - this._t0) * 0.001; var dr = [ p1[0] - this._p0[0], p1[1] - this._p0[1] ]; var dist = Math.sqrt(dr[0]*dr[0] + dr[1]*dr[1]); var axis = Math.abs(dr[0]) > Math.abs(dr[1]) ? 'x' : 'y'; var o = this._options; if (o.minDist && dist < o.minDist) { return; } if (o.maxDist && dist > o.maxDist) { return; } if (o.minDuration && dt < o.minDuration) { return; } if (o.maxDuration && dt > o.maxDuration) { return; } if (o.forceAxis && axis !== o.forceAxis) { return; } var O = { upEvent: ev, elementId: this._element.id, duration: dt, dr: dr, dist: dist, axis: axis, target: this._target }; if (this._options.storeGesture) { O.gesture = this._gesture; O.time = this._time; } this._options.callback(this, O); } }; return Swipe; }); /** * @module Ink.Util.String_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.String', '1', [], function() { 'use strict'; /** * String Manipulation Utilities * * @class Ink.Util.String * @version 1 * @static */ var InkUtilString = { /** * List of special chars * * @property _chars * @type {Array} * @private * @readOnly * @static */ _chars: ['&','à','á','â','ã','ä','å','æ','ç','è','é', 'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô', 'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À', 'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë', 'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö', 'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<', '>','¢','£','¤','¥','¦','§','¨','©','ª','«', '¬','\xad','®','¯','°','±','²','³','´','µ','¶', '·','¸','¹','º','»','¼','½','¾'], /** * List of the special characters' html entities * * @property _entities * @type {Array} * @private * @readOnly * @static */ _entities: ['amp','agrave','aacute','acirc','atilde','auml','aring', 'aelig','ccedil','egrave','eacute','ecirc','euml','igrave', 'iacute','icirc','iuml','eth','ntilde','ograve','oacute', 'ocirc','otilde','ouml','oslash','ugrave','uacute','ucirc', 'uuml','yacute','thorn','yuml','Agrave','Aacute','Acirc', 'Atilde','Auml','Aring','AElig','Ccedil','Egrave','Eacute', 'Ecirc','Euml','Igrave','Iacute','Icirc','Iuml','ETH','Ntilde', 'Ograve','Oacute','Ocirc','Otilde','Ouml','Oslash','Ugrave', 'Uacute','Ucirc','Uuml','Yacute','THORN','euro','quot','szlig', 'lt','gt','cent','pound','curren','yen','brvbar','sect','uml', 'copy','ordf','laquo','not','shy','reg','macr','deg','plusmn', 'sup2','sup3','acute','micro','para','middot','cedil','sup1', 'ordm','raquo','frac14','frac12','frac34'], /** * List of accented chars * * @property _accentedChars * @type {Array} * @private * @readOnly * @static */ _accentedChars:['à','á','â','ã','ä','å', 'è','é','ê','ë', 'ì','í','î','ï', 'ò','ó','ô','õ','ö', 'ù','ú','û','ü', 'ç','ñ', 'À','Á','Â','Ã','Ä','Å', 'È','É','Ê','Ë', 'Ì','Í','Î','Ï', 'Ò','Ó','Ô','Õ','Ö', 'Ù','Ú','Û','Ü', 'Ç','Ñ'], /** * List of the accented chars (above), but without the accents * * @property _accentedRemovedChars * @type {Array} * @private * @readOnly * @static */ _accentedRemovedChars:['a','a','a','a','a','a', 'e','e','e','e', 'i','i','i','i', 'o','o','o','o','o', 'u','u','u','u', 'c','n', 'A','A','A','A','A','A', 'E','E','E','E', 'I','I','I','I', 'O','O','O','O','O', 'U','U','U','U', 'C','N'], /** * Object that contains the basic HTML unsafe chars, as keys, and their HTML entities as values * * @property _htmlUnsafeChars * @type {Object} * @private * @readOnly * @static */ _htmlUnsafeChars:{'<':'&lt;','>':'&gt;','&':'&amp;','"':'&quot;',"'":'&apos;'}, /** * Convert first letter of a word to upper case <br /> * If param as more than one word, it converts first letter of all words that have more than 2 letters * * @method ucFirst * @param {String} string * @param {Boolean} [firstWordOnly=false] capitalize only first word. * @return {String} string camel cased * @public * @static * * @example * InkString.ucFirst('hello world'); // -> 'Hello World' * InkString.ucFirst('hello world', true); // -> 'Hello world' */ ucFirst: function(string, firstWordOnly) { var replacer = firstWordOnly ? /(^|\s)(\w)(\S{2,})/ : /(^|\s)(\w)(\S{2,})/g; return string ? String(string).replace(replacer, function(_, $1, $2, $3){ return $1 + $2.toUpperCase() + $3.toLowerCase(); }) : string; }, /** * Remove spaces and new line from biggin and ends of string * * @method trim * @param {String} string * @return {String} string trimmed * @public * @static */ trim: function(string) { if (typeof string === 'string') { return string.replace(/^\s+|\s+$|\n+$/g, ''); } return string; }, /** * Removes HTML tags of string * * @method stripTags * @param {String} string * @param {String} allowed * @return {String} String stripped from HTML tags, leaving only the allowed ones (if any) * @public * @static * @example * <script> * var myvar='isto e um texto <b>bold</b> com imagem <img src=""> e br <br /> um <p>paragrafo</p>'; * SAPO.Utility.String.stripTags(myvar, 'b,u'); * </script> */ stripTags: function(string, allowed) { if (allowed && typeof allowed === 'string') { var aAllowed = InkUtilString.trim(allowed).split(','); var aNewAllowed = []; var cleanedTag = false; for(var i=0; i < aAllowed.length; i++) { if(InkUtilString.trim(aAllowed[i]) !== '') { cleanedTag = InkUtilString.trim(aAllowed[i].replace(/(\<|\>)/g, '').replace(/\s/, '')); aNewAllowed.push('(<'+cleanedTag+'\\s[^>]+>|<(\\s|\\/)?(\\s|\\/)?'+cleanedTag+'>)'); } } var strAllowed = aNewAllowed.join('|'); var reAllowed = new RegExp(strAllowed, "i"); var aFoundTags = string.match(new RegExp("<[^>]*>", "g")); for(var j=0; j < aFoundTags.length; j++) { if(!aFoundTags[j].match(reAllowed)) { string = string.replace((new RegExp(aFoundTags[j], "gm")), ''); } } return string; } else { return string.replace(/\<[^\>]+\>/g, ''); } }, /** * Convert listed characters to HTML entities * * @method htmlEntitiesEncode * @param {String} string * @return {String} string encoded * @public * @static */ htmlEntitiesEncode: function(string) { if (string && string.replace) { var re = false; for (var i = 0; i < InkUtilString._chars.length; i++) { re = new RegExp(InkUtilString._chars[i], "gm"); string = string.replace(re, '&' + InkUtilString._entities[i] + ';'); } } return string; }, /** * Convert listed HTML entities to character * * @method htmlEntitiesDecode * @param {String} string * @return {String} string decoded * @public * @static */ htmlEntitiesDecode: function(string) { if (string && string.replace) { var re = false; for (var i = 0; i < InkUtilString._entities.length; i++) { re = new RegExp("&"+InkUtilString._entities[i]+";", "gm"); string = string.replace(re, InkUtilString._chars[i]); } string = string.replace(/&#[^;]+;?/g, function($0){ if ($0.charAt(2) === 'x') { return String.fromCharCode(parseInt($0.substring(3), 16)); } else { return String.fromCharCode(parseInt($0.substring(2), 10)); } }); } return string; }, /** * Encode a string to UTF8 * * @method utf8Encode * @param {String} string * @return {String} string utf8 encoded * @public * @static */ utf8Encode: function(string) { string = string.replace(/\r\n/g,"\n"); var utfstring = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utfstring += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utfstring += String.fromCharCode((c >> 6) | 192); utfstring += String.fromCharCode((c & 63) | 128); } else { utfstring += String.fromCharCode((c >> 12) | 224); utfstring += String.fromCharCode(((c >> 6) & 63) | 128); utfstring += String.fromCharCode((c & 63) | 128); } } return utfstring; }, /** * Make a string shorter without cutting words * * @method shortString * @param {String} str * @param {Number} n - number of chars of the short string * @return {String} string shortened * @public * @static */ shortString: function(str,n) { var words = str.split(' '); var resultstr = ''; for(var i = 0; i < words.length; i++ ){ if((resultstr + words[i] + ' ').length>=n){ resultstr += '&hellip;'; break; } resultstr += words[i] + ' '; } return resultstr; }, /** * Truncates a string, breaking words and adding ... at the end * * @method truncateString * @param {String} str * @param {Number} length - length limit for the string. String will be * at most this big, ellipsis included. * @return {String} string truncated * @public * @static */ truncateString: function(str, length) { if(str.length - 1 > length) { return str.substr(0, length - 1) + "\u2026"; } else { return str; } }, /** * Decode a string from UTF8 * * @method utf8Decode * @param {String} string * @return {String} string utf8 decoded * @public * @static */ utf8Decode: function(utfstring) { var string = ""; var i = 0, c = 0, c2 = 0, c3 = 0; while ( i < utfstring.length ) { c = utfstring.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utfstring.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utfstring.charCodeAt(i+1); c3 = utfstring.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; }, /** * Convert all accented chars to char without accent. * * @method removeAccentedChars * @param {String} string * @return {String} string without accented chars * @public * @static */ removeAccentedChars: function(string) { var newString = string; var re = false; for (var i = 0; i < InkUtilString._accentedChars.length; i++) { re = new RegExp(InkUtilString._accentedChars[i], "gm"); newString = newString.replace(re, '' + InkUtilString._accentedRemovedChars[i] + ''); } return newString; }, /** * Count the number of occurrences of a specific needle in a haystack * * @method substrCount * @param {String} haystack * @param {String} needle * @return {Number} Number of occurrences * @public * @static */ substrCount: function(haystack,needle) { return haystack ? haystack.split(needle).length - 1 : 0; }, /** * Eval a JSON string to a JS object * * @method evalJSON * @param {String} strJSON * @param {Boolean} sanitize * @return {Object} JS Object * @public * @static */ evalJSON: function(strJSON, sanitize) { /* jshint evil:true */ if( (typeof sanitize === 'undefined' || sanitize === null) || InkUtilString.isJSON(strJSON)) { try { if(typeof(JSON) !== "undefined" && typeof(JSON.parse) !== 'undefined'){ return JSON.parse(strJSON); } return eval('('+strJSON+')'); } catch(e) { throw new Error('ERROR: Bad JSON string...'); } } }, /** * Checks if a string is a valid JSON object (string encoded) * * @method isJSON * @param {String} str * @return {Boolean} * @public * @static */ isJSON: function(str) { str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); }, /** * Escapes unsafe html chars to their entities * * @method htmlEscapeUnsafe * @param {String} str String to escape * @return {String} Escaped string * @public * @static */ htmlEscapeUnsafe: function(str){ var chars = InkUtilString._htmlUnsafeChars; return str != null ? String(str).replace(/[<>&'"]/g,function(c){return chars[c];}) : str; }, /** * Normalizes whitespace in string. * String is trimmed and sequences of many * Whitespaces are collapsed. * * @method normalizeWhitespace * @param {String} str String to normalize * @return {String} string normalized * @public * @static */ normalizeWhitespace: function(str){ return str != null ? InkUtilString.trim(String(str).replace(/\s+/g,' ')) : str; }, /** * Converts string to unicode * * @method toUnicode * @param {String} str * @return {String} string unicoded * @public * @static */ toUnicode: function(str) { if (typeof str === 'string') { var unicodeString = ''; var inInt = false; var theUnicode = false; var total = str.length; var i=0; while(i < total) { inInt = str.charCodeAt(i); if( (inInt >= 32 && inInt <= 126) || inInt == 8 || inInt == 9 || inInt == 10 || inInt == 12 || inInt == 13 || inInt == 32 || inInt == 34 || inInt == 47 || inInt == 58 || inInt == 92) { /* if(inInt == 34 || inInt == 92 || inInt == 47) { theUnicode = '\\'+str.charAt(i); } else { } */ if(inInt == 8) { theUnicode = '\\b'; } else if(inInt == 9) { theUnicode = '\\t'; } else if(inInt == 10) { theUnicode = '\\n'; } else if(inInt == 12) { theUnicode = '\\f'; } else if(inInt == 13) { theUnicode = '\\r'; } else { theUnicode = str.charAt(i); } } else { theUnicode = str.charCodeAt(i).toString(16)+''.toUpperCase(); while (theUnicode.length < 4) { theUnicode = '0' + theUnicode; } theUnicode = '\\u' + theUnicode; } unicodeString += theUnicode; i++; } return unicodeString; } }, /** * Escapes a unicode character. returns \xXX if hex smaller than 0x100, otherwise \uXXXX * * @method escape * @param {String} c Char * @return {String} escaped char * @public * @static */ /** * @param {String} c char */ escape: function(c) { var hex = (c).charCodeAt(0).toString(16).split(''); if (hex.length < 3) { while (hex.length < 2) { hex.unshift('0'); } hex.unshift('x'); } else { while (hex.length < 4) { hex.unshift('0'); } hex.unshift('u'); } hex.unshift('\\'); return hex.join(''); }, /** * Unescapes a unicode character escape sequence * * @method unescape * @param {String} es Escape sequence * @return {String} String des-unicoded * @public * @static */ unescape: function(es) { var idx = es.lastIndexOf('0'); idx = idx === -1 ? 2 : Math.min(idx, 2); //console.log(idx); var hexNum = es.substring(idx); //console.log(hexNum); var num = parseInt(hexNum, 16); return String.fromCharCode(num); }, /** * Escapes a string to unicode characters * * @method escapeText * @param {String} txt * @param {Array} [whiteList] * @return {String} Escaped to Unicoded string * @public * @static */ escapeText: function(txt, whiteList) { if (whiteList === undefined) { whiteList = ['[', ']', '\'', ',']; } var txt2 = []; var c, C; for (var i = 0, f = txt.length; i < f; ++i) { c = txt[i]; C = c.charCodeAt(0); if (C < 32 || C > 126 && whiteList.indexOf(c) === -1) { c = InkUtilString.escape(c); } txt2.push(c); } return txt2.join(''); }, /** * Regex to check escaped strings * * @property escapedCharRegex * @type {Regex} * @public * @readOnly * @static */ escapedCharRegex: /(\\x[0-9a-fA-F]{2})|(\\u[0-9a-fA-F]{4})/g, /** * Unescapes a string * * @method unescapeText * @param {String} txt * @return {String} Unescaped string * @public * @static */ unescapeText: function(txt) { /*jshint boss:true */ var m; while (m = InkUtilString.escapedCharRegex.exec(txt)) { m = m[0]; txt = txt.replace(m, InkUtilString.unescape(m)); InkUtilString.escapedCharRegex.lastIndex = 0; } return txt; }, /** * Compares two strings * * @method strcmp * @param {String} str1 * @param {String} str2 * @return {Number} * @public * @static */ strcmp: function(str1, str2) { return ((str1 === str2) ? 0 : ((str1 > str2) ? 1 : -1)); }, /** * Splits long string into string of, at most, maxLen (that is, all but last have length maxLen, * last can measure maxLen or less) * * @method packetize * @param {String} string string to divide * @param {Number} maxLen packet size * @return {Array} string divided * @public * @static */ packetize: function(str, maxLen) { var len = str.length; var parts = new Array( Math.ceil(len / maxLen) ); var chars = str.split(''); var sz, i = 0; while (len) { sz = Math.min(maxLen, len); parts[i++] = chars.splice(0, sz).join(''); len -= sz; } return parts; } }; return InkUtilString; }); /** * @module Ink.Util.Json_1 * * @author inkdev AT sapo.pt */ Ink.createModule('Ink.Util.Json', '1', [], function() { 'use strict'; var function_call = Function.prototype.call; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; function twoDigits(n) { var r = '' + n; if (r.length === 1) { return '0' + r; } else { return r; } } var date_toISOString = Date.prototype.toISOString ? Ink.bind(function_call, Date.prototype.toISOString) : function(date) { // Adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString return date.getUTCFullYear() + '-' + twoDigits( date.getUTCMonth() + 1 ) + '-' + twoDigits( date.getUTCDate() ) + 'T' + twoDigits( date.getUTCHours() ) + ':' + twoDigits( date.getUTCMinutes() ) + ':' + twoDigits( date.getUTCSeconds() ) + '.' + String( (date.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 ) + 'Z'; }; /** * Use this class to convert JSON strings to JavaScript objects * `(Json.parse)` and also to do the opposite operation `(Json.stringify)`. * Internally, the standard JSON implementation is used if available * Otherwise, the functions mimic the standard implementation. * * Here's how to produce JSON from an existing object: * * Ink.requireModules(['Ink.Util.Json_1'], function (Json) { * var obj = { * key1: 'value1', * key2: 'value2', * keyArray: ['arrayValue1', 'arrayValue2', 'arrayValue3'] * }; * Json.stringify(obj); // The above object as a JSON string * }); * * And here is how to parse JSON: * * Ink.requireModules(['Ink.Util.Json_1'], function (Json) { * var source = '{"key": "value", "array": [true, null, false]}'; * Json.parse(source); // The above JSON string as an object * }); * @class Ink.Util.Json * @static * */ var InkJson = { _nativeJSON: window.JSON || null, _convertToUnicode: false, // Escape characters so as to embed them in JSON strings _escape: function (theString) { var _m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }; if (/["\\\x00-\x1f]/.test(theString)) { theString = theString.replace(/([\x00-\x1f\\"])/g, function(a, b) { var c = _m[b]; if (c) { return c; } c = b.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }); } return theString; }, // A character conversion map _toUnicode: function (theString) { if(!this._convertToUnicode) { return this._escape(theString); } else { var unicodeString = ''; var inInt = false; var theUnicode = false; var i = 0; var total = theString.length; while(i < total) { inInt = theString.charCodeAt(i); if( (inInt >= 32 && inInt <= 126) || //(inInt >= 48 && inInt <= 57) || //(inInt >= 65 && inInt <= 90) || //(inInt >= 97 && inInt <= 122) || inInt === 8 || inInt === 9 || inInt === 10 || inInt === 12 || inInt === 13 || inInt === 32 || inInt === 34 || inInt === 47 || inInt === 58 || inInt === 92) { if(inInt === 34 || inInt === 92 || inInt === 47) { theUnicode = '\\'+theString.charAt(i); } else if(inInt === 8) { theUnicode = '\\b'; } else if(inInt === 9) { theUnicode = '\\t'; } else if(inInt === 10) { theUnicode = '\\n'; } else if(inInt === 12) { theUnicode = '\\f'; } else if(inInt === 13) { theUnicode = '\\r'; } else { theUnicode = theString.charAt(i); } } else { if(this._convertToUnicode) { theUnicode = theString.charCodeAt(i).toString(16)+''.toUpperCase(); while (theUnicode.length < 4) { theUnicode = '0' + theUnicode; } theUnicode = '\\u' + theUnicode; } else { theUnicode = theString.charAt(i); } } unicodeString += theUnicode; i++; } return unicodeString; } }, _stringifyValue: function(param) { if (typeof param === 'string') { return '"' + this._toUnicode(param) + '"'; } else if (typeof param === 'number' && (isNaN(param) || !isFinite(param))) { // Unusable numbers go null return 'null'; } else if (typeof param === 'undefined' || param === null) { // And so does undefined return 'null'; } else if (typeof param.toJSON === 'function') { var t = param.toJSON(); if (typeof t === 'string') { return '"' + this._escape(t) + '"'; } else { return this._escape(t.toString()); } } else if (typeof param === 'number' || typeof param === 'boolean') { // These ones' toString methods return valid JSON. return '' + param; } else if (typeof param === 'function') { return 'null'; // match JSON.stringify } else if (param.constructor === Date) { throw '' return '"' + this._escape(date_toISOString(param)) + '"'; } else if (param.constructor === Array) { var arrayString = ''; for (var i = 0, len = param.length; i < len; i++) { if (i > 0) { arrayString += ','; } arrayString += this._stringifyValue(param[i]); } return '[' + arrayString + ']'; } else { // Object var objectString = ''; for (var k in param) { if ({}.hasOwnProperty.call(param, k)) { if (objectString !== '') { objectString += ','; } objectString += '"' + this._escape(k) + '": ' + this._stringifyValue(param[k]); } } return '{' + objectString + '}'; } }, /** * serializes a JSON object into a string. * * @method stringify * @param {Object} input Data to be serialized into JSON * @param {Boolean} convertToUnicode When `true`, converts string contents to unicode \uXXXX * @return {String} serialized string * * @example * Json.stringify({a:1.23}); // -> string: '{"a": 1.23}' */ stringify: function(input, convertToUnicode) { this._convertToUnicode = !!convertToUnicode; if(!this._convertToUnicode && this._nativeJSON) { return this._nativeJSON.stringify(input); } return this._stringifyValue(input); // And recurse. }, /** * @method parse * @param text {String} Input string * @param reviver {Function} Function receiving `(key, value)`, and `this`=(containing object), used to walk objects. * * @example * Simple example: * * Json.parse('{"a": "3","numbers":false}', * function (key, value) { * if (!this.numbers && key === 'a') { * return "NO NUMBERS"; * } else { * return value; * } * }); // -> object: {a: 'NO NUMBERS', numbers: false} */ /* From https://github.com/douglascrockford/JSON-js/blob/master/json.js */ parse: function (text, reviver) { /*jshint evil:true*/ // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); } }; return InkJson; }); /** * @module Ink.Util.I18n_1 * @author inkdev AT sapo.pt */ Ink.createModule('Ink.Util.I18n', '1', [], function () { 'use strict'; var pattrText = /\{(?:(\{.*?})|(?:%s:)?(\d+)|(?:%s)?|([\w-]+))}/g; var funcOrVal = function( ret , args ) { if ( typeof ret === 'function' ) { return ret.apply(this, args); } else if (typeof ret !== undefined) { return ret; } else { return ''; } }; /** * Creates a new internationalization helper object * * @class Ink.Util.I18n * @constructor * * @param {Object} dict object mapping language codes (in the form of `pt_PT`, `pt_BR`, `fr`, `en_US`, etc.) to their Object dictionaries. * @param {Object} dict.(dictionaries...) * @param {String} [lang='pt_PT'] language code of the target language * * @example * var dictionaries = { // This could come from a JSONP request from your server * 'pt_PT': { * 'hello': 'olá', * 'me': 'eu', * 'i have a {} for you': 'tenho um {} para ti' // Old syntax using `{%s}` tokens still available * }, * 'pt_BR': { * 'hello': 'oi', * 'me': 'eu', * 'i have a {} for you': 'tenho um {} para você' * } * }; * Ink.requireModules(['Ink.Util.I18n_1'], function (I18n) { * var i18n = new I18n(dictionaries, 'pt_PT'); * i18n.text('hello'); // returns 'olá' * i18n.text('i have a {} for you', 'IRON SWORD'); // returns 'tenho um IRON SWORD' para ti * * i18n.lang('pt_BR'); // Changes language. pt_BR dictionary is loaded * i18n.text('hello'); // returns 'oi' * * i18n.lang('en_US'); // Missing language. * i18n.text('hello'); // returns 'hello'. If testMode is on, returns '[hello]' * }); * * @example * // The old {%s} syntax from libsapo's i18n is still supported * i18n.text('hello, {%s}!', 'someone'); // -> 'olá, someone!' */ var I18n = function( dict , lang , testMode ) { if ( !( this instanceof I18n ) ) { return new I18n( dict , lang , testMode ); } this.reset( ) .lang( lang ) .testMode( testMode ) .append( dict || { } , lang ); }; I18n.prototype = { reset: function( ) { this._dicts = [ ]; this._dict = { }; this._testMode = false; this._lang = this._gLang; return this; }, /** * Adds translation strings for this helper to use. * * @method append * @param {Object} dict object containing language objects identified by their language code * @example * var i18n = new I18n({}, 'pt_PT'); * i18n.append({'pt_PT': { * 'sfraggles': 'braggles' * }}); * i18n.text('sfraggles') // -> 'braggles' */ append: function( dict ) { this._dicts.push( dict ); this._dict = Ink.extendObj(this._dict , dict[ this._lang ] ); return this; }, /** * Get the language code * * @returns {String} the language code for this instance * @method {String} lang */ /** * Set the language. If there are more dictionaries available in cache, they will be loaded. * * @method lang * @param lang {String} Language code to set this instance to. */ lang: function( lang ) { if ( !arguments.length ) { return this._lang; } if ( lang && this._lang !== lang ) { this._lang = lang; this._dict = { }; for ( var i = 0, l = this._dicts.length; i < l; i++ ) { this._dict = Ink.extendObj( this._dict , this._dicts[ i ][ lang ] || { } ); } } return this; }, /** * Get the testMode * * @returns {Boolean} the testMode for this instance * @method {Boolean} testMode */ /** * Sets or unsets test mode. In test mode, unknown strings are wrapped * in `[ ... ]`. This is useful for debugging your application and * making sure all your translation keys are in place. * * @method testMode * @param {Boolean} bool boolean value to set the test mode to. */ testMode: function( bool ) { if ( !arguments.length ) { return !!this._testMode; } if ( bool !== undefined ) { this._testMode = !!bool; } return this; }, /** * Return an arbitrary key from the current language dictionary * * @method getKey * @param {String} key * @return {Any} The object which happened to be in the current language dictionary on the given key. * * @example * _.getKey('astring'); // -> 'a translated string' * _.getKey('anobject'); // -> {'a': 'translated object'} * _.getKey('afunction'); // -> function () { return 'this is a localized function' } */ getKey: function( key ) { var ret; var gLang = this._gLang; var lang = this._lang; if ( key in this._dict ) { ret = this._dict[ key ]; } else { I18n.lang( lang ); ret = this._gDict[ key ]; I18n.lang( gLang ); } return ret; }, /** * Given a translation key, return a translated string, with replaced parameters. * When a translated string is not available, the original string is returned unchanged. * * @method {String} text * @param {String} str key to look for in i18n dictionary (which is returned verbatim if unknown) * @param {Object} [namedParms] named replacements. Replaces {named} with values in this object. * @param {String} [arg1] replacement #1 (replaces first {} and all {1}) * @param {String} [arg2] replacement #2 (replaces second {} and all {2}) * @param {String} [argn...] replacement #n (replaces nth {} and all {n}) * * @example * _('Gosto muito de {} e o céu é {}.', 'carros', 'azul'); * // returns 'Gosto muito de carros e o céu é azul.' * * @example * _('O {1} é {2} como {2} é a cor do {3}.', 'carro', 'azul', 'FCP'); * // returns 'O carro é azul como azul é o FCP.' * * @example * _('O {person1} dava-se com a {person2}', {person1: 'coisinho', person2: 'coisinha'}); * // -> 'O coisinho dava-se com a coisinha' * * @example * // This is a bit more complex * var i18n = make().lang('pt_PT').append({ * pt_PT: { * array: [1, 2], * object: {'a': '-a-', 'b': '-b-'}, * func: function (a, b) {return '[[' + a + ',' + b + ']]';} * } * }); * i18n.text('array', 0); // -> '1' * i18n.text('object', 'a'); // -> '-a-' * i18n.text('func', 'a', 'b'); // -> '[[a,b]]' */ text: function( str /*, replacements...*/ ) { if ( typeof str !== 'string' ) { return; } // Backwards-compat var pars = Array.prototype.slice.call( arguments , 1 ); var idx = 0; var isObj = typeof pars[ 0 ] === 'object'; var original = this.getKey( str ); if ( original === undefined ) { original = this._testMode ? '[' + str + ']' : str; } if ( typeof original === 'number' ) { original += ''; } if (typeof original === 'string') { original = original.replace( pattrText , function( m , $1 , $2 , $3 ) { var ret = $1 ? $1 : $2 ? pars[ $2 - ( isObj ? 0 : 1 ) ] : $3 ? pars[ 0 ][ $3 ] || '' : pars[ (idx++) + ( isObj ? 1 : 0 ) ] return funcOrVal( ret , [idx].concat(pars) ); }); return original; } return ( typeof original === 'function' ? original.apply( this , pars ) : original instanceof Array ? funcOrVal( original[ pars[ 0 ] ] , pars ) : typeof original === 'object' ? funcOrVal( original[ pars[ 0 ] ] , pars ) : ''); }, /** * Given a singular string, a plural string, and a number, translates * either the singular or plural string. * * @method ntext * @return {String} * * @param {String} strSin word to use when count is 1 * @param {String} strPlur word to use otherwise * @param {Number} count number which defines which word to use * @param [...] extra arguments, to be passed to `text()` * * @example * i18n.ntext('platypus', 'platypuses', 1); // returns 'ornitorrinco' * i18n.ntext('platypus', 'platypuses', 2); // returns 'ornitorrincos' * * @example * // The "count" argument is passed to text() * i18n.ntext('{} platypus', '{} platypuses', 1); // returns '1 ornitorrinco' * i18n.ntext('{} platypus', '{} platypuses', 2); // returns '2 ornitorrincos' */ ntext: function( strSin , strPlur , count ) { var pars = Array.prototype.slice.apply( arguments ); var original; if ( pars.length === 2 && typeof strPlur === 'number' ) { original = this.getKey( strSin ); if ( !( original instanceof Array ) ) { return ''; } pars.splice( 0 , 1 ); original = original[ strPlur === 1 ? 0 : 1 ]; } else { pars.splice( 0 , 2 ); original = count === 1 ? strSin : strPlur; } return this.text.apply( this , [ original ].concat( pars ) ); }, /** * Returns the ordinal suffix of `num` (For example, 1 > 'st', 2 > 'nd', 5 > 'th', ...). * * This works by using transforms (in the form of Objects or Functions) passed into the * function or found in the special key `_ordinals` in the active language dictionary. * * @method ordinal * * @param {Number} num Input number * * @param {Object|Function} [options={}] * * Maps for translating. Each of these options' fallback is found in the current * language's dictionary. The lookup order is the following: * * 1. `exceptions` * 2. `byLastDigit` * 3. `default` * * Each of these may be either an `Object` or a `Function`. If it's a function, it * is called (with `number` and `digit` for any function except for byLastDigit, * which is called with the `lastDigit` of the number in question), and if the * function returns a string, that is used. If it's an object, the property is * looked up using `[...]`. If what is found is a string, it is used. * * @param {Object|Function} [options.byLastDigit={}] * If the language requires the last digit to be considered, mappings of last digits * to ordinal suffixes can be created here. * * @param {Object|Function} [options.exceptions={}] * Map unique, special cases to their ordinal suffixes. * * @returns {String} Ordinal suffix for `num`. * * @example * var i18n = new I18n({ * pt_PT: { // 1º, 2º, 3º, 4º, ... * _ordinal: { // The _ordinals key each translation dictionary is special. * 'default': "º" // Usually the suffix is "º" in portuguese... * } * }, * fr: { // 1er, 2e, 3e, 4e, ... * _ordinal: { // The _ordinals key is special. * 'default': "e", // Usually the suffix is "e" in french... * exceptions: { * 1: "er" // ... Except for the number one. * } * } * }, * en_US: { // 1st, 2nd, 3rd, 4th, ..., 11th, 12th, ... 21st, 22nd... * _ordinal: { * 'default': "th",// Usually the digit is "th" in english... * byLastDigit: { * 1: "st", // When the last digit is 1, use "th"... * 2: "nd", // When the last digit is 2, use "nd"... * 3: "rd" // When the last digit is 3, use "rd"... * }, * exceptions: { // But these numbers are special * 0: "", * 11: "th", * 12: "th", * 13: "th" * } * } * } * }, 'pt_PT'); * * i18n.ordinal(1); // returns 'º' * i18n.ordinal(2); // returns 'º' * i18n.ordinal(11); // returns 'º' * * i18n.lang('fr'); * i18n.ordinal(1); // returns 'er' * i18n.ordinal(2); // returns 'e' * i18n.ordinal(11); // returns 'e' * * i18n.lang('en_US'); * i18n.ordinal(1); // returns 'st' * i18n.ordinal(2); // returns 'nd' * i18n.ordinal(12); // returns 'th' * i18n.ordinal(22); // returns 'nd' * i18n.ordinal(3); // returns 'rd' * i18n.ordinal(4); // returns 'th' * i18n.ordinal(5); // returns 'th' * **/ ordinal: function( num ) { if ( num === undefined ) { return ''; } var lastDig = +num.toString( ).slice( -1 ); var ordDict = this.getKey( '_ordinals' ); if ( ordDict === undefined ) { return ''; } if ( typeof ordDict === 'string' ) { return ordDict; } var ret; if ( typeof ordDict === 'function' ) { ret = ordDict( num , lastDig ); if ( typeof ret === 'string' ) { return ret; } } if ( 'exceptions' in ordDict ) { ret = typeof ordDict.exceptions === 'function' ? ordDict.exceptions( num , lastDig ) : num in ordDict.exceptions ? funcOrVal( ordDict.exceptions[ num ] , [num , lastDig] ) : undefined; if ( typeof ret === 'string' ) { return ret; } } if ( 'byLastDigit' in ordDict ) { ret = typeof ordDict.byLastDigit === 'function' ? ordDict.byLastDigit( lastDig , num ) : lastDig in ordDict.byLastDigit ? funcOrVal( ordDict.byLastDigit[ lastDig ] , [lastDig , num] ) : undefined; if ( typeof ret === 'string' ) { return ret; } } if ( 'default' in ordDict ) { ret = funcOrVal( ordDict['default'] , [ num , lastDig ] ); if ( typeof ret === 'string' ) { return ret; } } return ''; }, /** * Returns an alias to `text()`, for convenience. The resulting function is * traditionally assigned to "_". * * @method alias * @returns {Function} an alias to `text()`. You can also access the rest of the translation API through this alias. * * @example * var i18n = new I18n({ * 'pt_PT': { * 'hi': 'olá', * '{} day': '{} dia', * '{} days': '{} dias', * '_ordinals': { * 'default': 'º' * } * } * }, 'pt_PT'); * var _ = i18n.alias(); * _('hi'); // -> 'olá' * _('{} days', 3); // -> '3 dias' * _.ntext('{} day', '{} days', 2); // -> '2 dias' * _.ntext('{} day', '{} days', 1); // -> '1 dia' * _.ordinal(3); // -> 'º' */ alias: function( ) { var ret = Ink.bind( I18n.prototype.text , this ); ret.ntext = Ink.bind( I18n.prototype.ntext , this ); ret.append = Ink.bind( I18n.prototype.append , this ); ret.ordinal = Ink.bind( I18n.prototype.ordinal , this ); ret.testMode = Ink.bind( I18n.prototype.testMode , this ); return ret; } }; /** * @static * @method I18n.reset * * Reset I18n global state (global dictionaries, and default language for instances) **/ I18n.reset = function( ) { I18n.prototype._gDicts = [ ]; I18n.prototype._gDict = { }; I18n.prototype._gLang = 'pt_PT'; }; I18n.reset( ); /** * @static * @method I18n.append * * @param dict {Object} Dictionary to be added * @param lang {String} Language to be added to * * Add a dictionary to be used in all I18n instances for the corresponding language */ I18n.append = function( dict , lang ) { if ( lang ) { if ( !( lang in dict ) ) { var obj = { }; obj[ lang ] = dict; dict = obj; } if ( lang !== I18n.prototype._gLang ) { I18n.lang( lang ); } } I18n.prototype._gDicts.push( dict ); Ink.extendObj( I18n.prototype._gDict , dict[ I18n.prototype._gLang ] ); }; /** * @static * @method I18n.lang * * @param lang {String} String in the format `"pt_PT"`, `"fr"`, etc. * * Set global default language of I18n instances to `lang` */ /** * @static * @method I18n.lang * * Get the current default language of I18n instances. * * @return {String} language code */ I18n.lang = function( lang ) { if ( !arguments.length ) { return I18n.prototype._gLang; } if ( lang && I18n.prototype._gLang !== lang ) { I18n.prototype._gLang = lang; I18n.prototype._gDict = { }; for ( var i = 0, l = I18n.prototype._gDicts.length; i < l; i++ ) { Ink.extendObj( I18n.prototype._gDict , I18n.prototype._gDicts[ i ][ lang ] || { } ); } } }; return I18n; }); /** * @module Ink.Util.Dumper_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.Dumper', '1', [], function() { 'use strict'; /** * Dump/Profiling Utilities * * @class Ink.Util.Dumper * @version 1 * @static */ var Dumper = { /** * Hex code for the 'tab' * * @property _tab * @type {String} * @private * @readOnly * @static * */ _tab: '\xA0\xA0\xA0\xA0', /** * Function that returns the argument passed formatted * * @method _formatParam * @param {Mixed} param * @return {String} The argument passed formatted * @private * @static */ _formatParam: function(param) { var formated = ''; switch(typeof(param)) { case 'string': formated = '(string) '+param; break; case 'number': formated = '(number) '+param; break; case 'boolean': formated = '(boolean) '+param; break; case 'object': if(param !== null) { if(param.constructor === Array) { formated = 'Array \n{\n' + this._outputFormat(param, 0) + '\n}'; } else { formated = 'Object \n{\n' + this._outputFormat(param, 0) + '\n}'; } } else { formated = 'null'; } break; default: formated = false; } return formated; }, /** * Function that returns the tabs concatenated * * @method _getTabs * @param {Number} numberOfTabs Number of Tabs * @return {String} Tabs concatenated * @private * @static */ _getTabs: function(numberOfTabs) { var tabs = ''; for(var _i = 0; _i < numberOfTabs; _i++) { tabs += this._tab; } return tabs; }, /** * Function that formats the parameter to display * * @method _outputFormat * @param {Any} param * @param {Number} dim * @return {String} The parameter passed formatted to displat * @private * @static */ _outputFormat: function(param, dim) { var formated = ''; //var _strVal = false; var _typeof = false; for(var key in param) { if(param[key] !== null) { if(typeof(param[key]) === 'object' && (param[key].constructor === Array || param[key].constructor === Object)) { if(param[key].constructor === Array) { _typeof = 'Array'; } else if(param[key].constructor === Object) { _typeof = 'Object'; } formated += this._tab + this._getTabs(dim) + '[' + key + '] => <b>'+_typeof+'</b>\n'; formated += this._tab + this._getTabs(dim) + '{\n'; formated += this._outputFormat(param[key], dim + 1) + this._tab + this._getTabs(dim) + '}\n'; } else if(param[key].constructor === Function) { continue; } else { formated = formated + this._tab + this._getTabs(dim) + '[' + key + '] => ' + param[key] + '\n'; } } else { formated = formated + this._tab + this._getTabs(dim) + '[' + key + '] => null \n'; } } return formated; }, /** * Print variable structure. Can be passed an output target * * @method printDump * @param {Object|String|Boolean} param * @param {optional String|Object} target (can be an element ID or an element) * @public * @static */ printDump: function(param, target) { if(!target || typeof(target) === 'undefined') { document.write('<pre>'+this._formatParam(param)+'</pre>'); } else { if(typeof(target) === 'string') { document.getElementById(target).innerHTML = '<pre>' + this._formatParam(param) + '</pre>'; } else if(typeof(target) === 'object') { target.innerHTML = '<pre>'+this._formatParam(param)+'</pre>'; } else { throw "TARGET must be an element or an element ID"; } } }, /** * Function that returns the variable's structure * * @method returnDump * @param {Object|String|Boolean} param * @return {String} The variable structure * @public * @static */ returnDump: function(param) { return this._formatParam(param); }, /** * Function that alerts the variable structure * * @method alertDump * @param {Object|String|Boolean} param * @public * @static */ alertDump: function(param) { window.alert(this._formatParam(param).replace(/(<b>)(Array|Object)(<\/b>)/g, "$2")); }, /** * Print to new window the variable structure * * @method windowDump * @param {Object|String|Boolean} param * @public * @static */ windowDump: function(param) { var dumperwindow = 'dumperwindow_'+(Math.random() * 10000); var win = window.open('', dumperwindow, 'width=400,height=300,left=50,top=50,status,menubar,scrollbars,resizable' ); win.document.open(); win.document.write('<pre>'+this._formatParam(param)+'</pre>'); win.document.close(); win.focus(); } }; return Dumper; }); /** * @module Ink.Util.Date_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.Date', '1', [], function() { 'use strict'; /** * Class to provide the same features that php date does * * @class Ink.Util.Date * @version 1 * @static */ var InkDate = { /** * Function that returns the string representation of the month [PT only] * * @method _months * @param {Number} index Month javascript (0 to 11) * @return {String} The month's name * @private * @static * @example * console.log( InkDate._months(0) ); // Result: Janeiro */ _months: function(index){ var _m = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']; return _m[index]; }, /** * Function that returns the month [PT only] ( 0 to 11 ) * * @method _iMonth * @param {String} month Month javascript (0 to 11) * @return {Number} The month's number * @private * @static * @example * console.log( InkDate._iMonth('maio') ); // Result: 4 */ _iMonth : function( month ) { if ( Number( month ) ) { return +month - 1; } return { 'janeiro' : 0 , 'jan' : 0 , 'fevereiro' : 1 , 'fev' : 1 , 'março' : 2 , 'mar' : 2 , 'abril' : 3 , 'abr' : 3 , 'maio' : 4 , 'mai' : 4 , 'junho' : 5 , 'jun' : 5 , 'julho' : 6 , 'jul' : 6 , 'agosto' : 7 , 'ago' : 7 , 'setembro' : 8 , 'set' : 8 , 'outubro' : 9 , 'out' : 9 , 'novembro' : 10 , 'nov' : 10 , 'dezembro' : 11 , 'dez' : 11 }[ month.toLowerCase( ) ]; } , /** * Function that returns the representation the day of the week [PT Only] * * @method _wDays * @param {Number} index Week's day index * @return {String} The week's day name * @private * @static * @example * console.log( InkDate._wDays(0) ); // Result: Domingo */ _wDays: function(index){ var _d = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado']; return _d[index]; }, /** * Function that returns day of the week in javascript 1 to 7 * * @method _iWeek * @param {String} week Week's day name * @return {Number} The week's day index * @private * @static * @example * console.log( InkDate._iWeek('quarta') ); // Result: 3 */ _iWeek: function( week ) { if ( Number( week ) ) { return +week || 7; } return { 'segunda' : 1 , 'seg' : 1 , 'terça' : 2 , 'ter' : 2 , 'quarta' : 3 , 'qua' : 3 , 'quinta' : 4 , 'qui' : 4 , 'sexta' : 5 , 'sex' : 5 , 'sábado' : 6 , 'sáb' : 6 , 'domingo' : 7 , 'dom' : 7 }[ week.toLowerCase( ) ]; }, /** * Function that returns the number of days of a given month (m) on a given year (y) * * @method _daysInMonth * @param {Number} _m Month * @param {Number} _y Year * @return {Number} Number of days of a give month on a given year * @private * @static * @example * console.log( InkDate._daysInMonth(2,2013) ); // Result: 28 */ _daysInMonth: function(_m,_y){ var nDays; if(_m===1 || _m===3 || _m===5 || _m===7 || _m===8 || _m===10 || _m===12) { nDays= 31; } else if ( _m===4 || _m===6 || _m===9 || _m===11) { nDays = 30; } else { if((_y%400===0) || (_y%4===0 && _y%100!==0)) { nDays = 29; } else { nDays = 28; } } return nDays; }, /** * Function that works exactly as php date() function * Works like PHP 5.2.2 <a href="http://php.net/manual/en/function.date.php" target="_blank">PHP Date function</a> * * @method get * @param {String} format - as the string in which the date it will be formatted - mandatory * @param {Date} [_date] - the date to format. If undefined it will do it on now() date. Can receive unix timestamp or a date object * @return {String} Formatted date * @public * @static * @example * <script> * Ink.requireModules( ['Ink.Util.Date_1'], function( InkDate ){ * console.log( InkDate.get('Y-m-d') ); // Result (at the time of writing): 2013-05-07 * }); * </script> */ get: function(format, _date){ /*jshint maxcomplexity:50 */ if(typeof(format) === 'undefined' || format === ''){ format = "Y-m-d"; } var iFormat = format.split(""); var result = new Array(iFormat.length); var escapeChar = "\\"; var jsDate; if (typeof(_date) === 'undefined'){ jsDate = new Date(); } else if (typeof(_date)==='number'){ jsDate = new Date(_date*1000); } else { jsDate = new Date(_date); } var jsFirstDay, jsThisDay, jsHour; /* This switch is presented in the same order as in php date function (PHP 5.2.2) */ for (var i = 0; i < iFormat.length; i++) { switch(iFormat[i]) { case escapeChar: result[i] = iFormat[i+1]; i++; break; /* DAY */ case "d": /* Day of the month, 2 digits with leading zeros; ex: 01 to 31 */ var jsDay = jsDate.getDate(); result[i] = (String(jsDay).length > 1) ? jsDay : "0" + jsDay; break; case "D": /* A textual representation of a day, three letters; Seg to Dom */ result[i] = this._wDays(jsDate.getDay()).substring(0, 3); break; case "j": /* Day of the month without leading zeros; ex: 1 to 31 */ result[i] = jsDate.getDate(); break; case "l": /* A full textual representation of the day of the week; Domingo to Sabado */ result[i] = this._wDays(jsDate.getDay()); break; case "N": /* ISO-8601 numeric representation of the day of the week; 1 (Segunda) to 7 (Domingo) */ result[i] = jsDate.getDay() || 7; break; case "S": /* English ordinal suffix for the day of the month, 2 characters; st, nd, rd or th. Works well with j */ var temp = jsDate.getDate(); var suffixes = ["st", "nd", "rd"]; var suffix = ""; if (temp >= 11 && temp <= 13) { result[i] = "th"; } else { result[i] = (suffix = suffixes[String(temp).substr(-1) - 1]) ? (suffix) : ("th"); } break; case "w": /* Numeric representation of the day of the week; 0 (for Sunday) through 6 (for Saturday) */ result[i] = jsDate.getDay(); break; case "z": /* The day of the year (starting from 0); 0 to 365 */ jsFirstDay = Date.UTC(jsDate.getFullYear(), 0, 0); jsThisDay = Date.UTC(jsDate.getFullYear(), jsDate.getMonth(), jsDate.getDate()); result[i] = Math.floor((jsThisDay - jsFirstDay) / (1000 * 60 * 60 * 24)); break; /* WEEK */ case "W": /* ISO-8601 week number of year, weeks starting on Monday; ex: 42 (the 42nd week in the year) */ var jsYearStart = new Date( jsDate.getFullYear( ) , 0 , 1 ); jsFirstDay = jsYearStart.getDay() || 7; var days = Math.floor( ( jsDate - jsYearStart ) / ( 24 * 60 * 60 * 1000 ) + 1 ); result[ i ] = Math.ceil( ( days - ( 8 - jsFirstDay ) ) / 7 ) + 1; break; /* MONTH */ case "F": /* A full textual representation of a month, such as Janeiro or Marco; Janeiro a Dezembro */ result[i] = this._months(jsDate.getMonth()); break; case "m": /* Numeric representation of a month, with leading zeros; 01 to 12 */ var jsMonth = String(jsDate.getMonth() + 1); result[i] = (jsMonth.length > 1) ? jsMonth : "0" + jsMonth; break; case "M": /* A short textual representation of a month, three letters; Jan a Dez */ result[i] = this._months(jsDate.getMonth()).substring(0,3); break; case "n": /* Numeric representation of a month, without leading zeros; 1 a 12 */ result[i] = jsDate.getMonth() + 1; break; case "t": /* Number of days in the given month; ex: 28 */ result[i] = this._daysInMonth(jsDate.getMonth()+1,jsDate.getYear()); break; /* YEAR */ case "L": /* Whether it's a leap year; 1 if it is a leap year, 0 otherwise. */ var jsYear = jsDate.getFullYear(); result[i] = (jsYear % 4) ? false : ( (jsYear % 100) ? true : ( (jsYear % 400) ? false : true ) ); break; case "o": /* ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. */ throw '"o" not implemented!'; case "Y": /* A full numeric representation of a year, 4 digits; 1999 */ result[i] = jsDate.getFullYear(); break; case "y": /* A two digit representation of a year; 99 */ result[i] = String(jsDate.getFullYear()).substring(2); break; /* TIME */ case "a": /* Lowercase Ante meridiem and Post meridiem; am or pm */ result[i] = (jsDate.getHours() < 12) ? "am" : "pm"; break; case "A": /* Uppercase Ante meridiem and Post meridiem; AM or PM */ result[i] = (jsDate.getHours < 12) ? "AM" : "PM"; break; case "B": /* Swatch Internet time; 000 through 999 */ throw '"B" not implemented!'; case "g": /* 12-hour format of an hour without leading zeros; 1 to 12 */ jsHour = jsDate.getHours(); result[i] = (jsHour <= 12) ? jsHour : (jsHour - 12); break; case "G": /* 24-hour format of an hour without leading zeros; 1 to 23 */ result[i] = String(jsDate.getHours()); break; case "h": /* 12-hour format of an hour with leading zeros; 01 to 12 */ jsHour = String(jsDate.getHours()); jsHour = (jsHour <= 12) ? jsHour : (jsHour - 12); result[i] = (jsHour.length > 1) ? jsHour : "0" + jsHour; break; case "H": /* 24-hour format of an hour with leading zeros; 01 to 24 */ jsHour = String(jsDate.getHours()); result[i] = (jsHour.length > 1) ? jsHour : "0" + jsHour; break; case "i": /* Minutes with leading zeros; 00 to 59 */ var jsMinute = String(jsDate.getMinutes()); result[i] = (jsMinute.length > 1) ? jsMinute : "0" + jsMinute; break; case "s": /* Seconds with leading zeros; 00 to 59; */ var jsSecond = String(jsDate.getSeconds()); result[i] = (jsSecond.length > 1) ? jsSecond : "0" + jsSecond; break; case "u": /* Microseconds */ throw '"u" not implemented!'; /* TIMEZONE */ case "e": /* Timezone identifier */ throw '"e" not implemented!'; case "I": /* "1" if Daylight Savings Time, "0" otherwise. Works only on the northern hemisphere */ jsFirstDay = new Date(jsDate.getFullYear(), 0, 1); result[i] = (jsDate.getTimezoneOffset() !== jsFirstDay.getTimezoneOffset()) ? (1) : (0); break; case "O": /* Difference to Greenwich time (GMT) in hours */ var jsMinZone = jsDate.getTimezoneOffset(); var jsMinutes = jsMinZone % 60; jsHour = String(((jsMinZone - jsMinutes) / 60) * -1); if (jsHour.charAt(0) !== "-") { jsHour = "+" + jsHour; } jsHour = (jsHour.length === 3) ? (jsHour) : (jsHour.replace(/([+\-])(\d)/, "$1" + 0 + "$2")); result[i] = jsHour + jsMinutes + "0"; break; case "P": /* Difference to Greenwich time (GMT) with colon between hours and minutes */ throw '"P" not implemented!'; case "T": /* Timezone abbreviation */ throw '"T" not implemented!'; case "Z": /* Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. */ result[i] = jsDate.getTimezoneOffset() * 60; break; /* FULL DATE/TIME */ case "c": /* ISO 8601 date */ throw '"c" not implemented!'; case "r": /* RFC 2822 formatted date */ var jsDayName = this._wDays(jsDate.getDay()).substr(0, 3); var jsMonthName = this._months(jsDate.getMonth()).substr(0, 3); result[i] = jsDayName + ", " + jsDate.getDate() + " " + jsMonthName + this.get(" Y H:i:s O",jsDate); break; case "U": /* Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) */ result[i] = Math.floor(jsDate.getTime() / 1000); break; default: result[i] = iFormat[i]; } } return result.join(''); }, /** * Functions that works like php date() function but return a date based on the formatted string * Works like PHP 5.2.2 <a href="http://php.net/manual/en/function.date.php" target="_blank">PHP Date function</a> * * @method set * @param {String} [format] As the string in which the date it will be formatted. By default is 'Y-m-d' * @param {String} str_date The date formatted - Mandatory. * @return {Date} Date object based on the formatted date * @public * @static */ set : function( format , str_date ) { if ( typeof str_date === 'undefined' ) { return ; } if ( typeof format === 'undefined' || format === '' ) { format = "Y-m-d"; } var iFormat = format.split(""); var result = new Array( iFormat.length ); var escapeChar = "\\"; var mList; var objIndex = { year : undefined , month : undefined , day : undefined , dayY : undefined , dayW : undefined , week : undefined , hour : undefined , hourD : undefined , min : undefined , sec : undefined , msec : undefined , ampm : undefined , diffM : undefined , diffH : undefined , date : undefined }; var matches = 0; /* This switch is presented in the same order as in php date function (PHP 5.2.2) */ for ( var i = 0; i < iFormat.length; i++) { switch( iFormat[ i ] ) { case escapeChar: result[i] = iFormat[ i + 1 ]; i++; break; /* DAY */ case "d": /* Day of the month, 2 digits with leading zeros; ex: 01 to 31 */ result[ i ] = '(\\d{2})'; objIndex.day = { original : i , match : matches++ }; break; case "j": /* Day of the month without leading zeros; ex: 1 to 31 */ result[ i ] = '(\\d{1,2})'; objIndex.day = { original : i , match : matches++ }; break; case "D": /* A textual representation of a day, three letters; Seg to Dom */ result[ i ] = '([\\wá]{3})'; objIndex.dayW = { original : i , match : matches++ }; break; case "l": /* A full textual representation of the day of the week; Domingo to Sabado */ result[i] = '([\\wá]{5,7})'; objIndex.dayW = { original : i , match : matches++ }; break; case "N": /* ISO-8601 numeric representation of the day of the week; 1 (Segunda) to 7 (Domingo) */ result[ i ] = '(\\d)'; objIndex.dayW = { original : i , match : matches++ }; break; case "w": /* Numeric representation of the day of the week; 0 (for Sunday) through 6 (for Saturday) */ result[ i ] = '(\\d)'; objIndex.dayW = { original : i , match : matches++ }; break; case "S": /* English ordinal suffix for the day of the month, 2 characters; st, nd, rd or th. Works well with j */ result[ i ] = '\\w{2}'; break; case "z": /* The day of the year (starting from 0); 0 to 365 */ result[ i ] = '(\\d{1,3})'; objIndex.dayY = { original : i , match : matches++ }; break; /* WEEK */ case "W": /* ISO-8601 week number of year, weeks starting on Monday; ex: 42 (the 42nd week in the year) */ result[ i ] = '(\\d{1,2})'; objIndex.week = { original : i , match : matches++ }; break; /* MONTH */ case "F": /* A full textual representation of a month, such as Janeiro or Marco; Janeiro a Dezembro */ result[ i ] = '([\\wç]{4,9})'; objIndex.month = { original : i , match : matches++ }; break; case "M": /* A short textual representation of a month, three letters; Jan a Dez */ result[ i ] = '(\\w{3})'; objIndex.month = { original : i , match : matches++ }; break; case "m": /* Numeric representation of a month, with leading zeros; 01 to 12 */ result[ i ] = '(\\d{2})'; objIndex.month = { original : i , match : matches++ }; break; case "n": /* Numeric representation of a month, without leading zeros; 1 a 12 */ result[ i ] = '(\\d{1,2})'; objIndex.month = { original : i , match : matches++ }; break; case "t": /* Number of days in the given month; ex: 28 */ result[ i ] = '\\d{2}'; break; /* YEAR */ case "L": /* Whether it's a leap year; 1 if it is a leap year, 0 otherwise. */ result[ i ] = '\\w{4,5}'; break; case "o": /* ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. */ throw '"o" not implemented!'; case "Y": /* A full numeric representation of a year, 4 digits; 1999 */ result[ i ] = '(\\d{4})'; objIndex.year = { original : i , match : matches++ }; break; case "y": /* A two digit representation of a year; 99 */ result[ i ] = '(\\d{2})'; if ( typeof objIndex.year === 'undefined' || iFormat[ objIndex.year.original ] !== 'Y' ) { objIndex.year = { original : i , match : matches++ }; } break; /* TIME */ case "a": /* Lowercase Ante meridiem and Post meridiem; am or pm */ result[ i ] = '(am|pm)'; objIndex.ampm = { original : i , match : matches++ }; break; case "A": /* Uppercase Ante meridiem and Post meridiem; AM or PM */ result[ i ] = '(AM|PM)'; objIndex.ampm = { original : i , match : matches++ }; break; case "B": /* Swatch Internet time; 000 through 999 */ throw '"B" not implemented!'; case "g": /* 12-hour format of an hour without leading zeros; 1 to 12 */ result[ i ] = '(\\d{1,2})'; objIndex.hourD = { original : i , match : matches++ }; break; case "G": /* 24-hour format of an hour without leading zeros; 1 to 23 */ result[ i ] = '(\\d{1,2})'; objIndex.hour = { original : i , match : matches++ }; break; case "h": /* 12-hour format of an hour with leading zeros; 01 to 12 */ result[ i ] = '(\\d{2})'; objIndex.hourD = { original : i , match : matches++ }; break; case "H": /* 24-hour format of an hour with leading zeros; 01 to 24 */ result[ i ] = '(\\d{2})'; objIndex.hour = { original : i , match : matches++ }; break; case "i": /* Minutes with leading zeros; 00 to 59 */ result[ i ] = '(\\d{2})'; objIndex.min = { original : i , match : matches++ }; break; case "s": /* Seconds with leading zeros; 00 to 59; */ result[ i ] = '(\\d{2})'; objIndex.sec = { original : i , match : matches++ }; break; case "u": /* Microseconds */ throw '"u" not implemented!'; /* TIMEZONE */ case "e": /* Timezone identifier */ throw '"e" not implemented!'; case "I": /* "1" if Daylight Savings Time, "0" otherwise. Works only on the northern hemisphere */ result[i] = '\\d'; break; case "O": /* Difference to Greenwich time (GMT) in hours */ result[ i ] = '([-+]\\d{4})'; objIndex.diffH = { original : i , match : matches++ }; break; case "P": /* Difference to Greenwich time (GMT) with colon between hours and minutes */ throw '"P" not implemented!'; case "T": /* Timezone abbreviation */ throw '"T" not implemented!'; case "Z": /* Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. */ result[ i ] = '(\\-?\\d{1,5})'; objIndex.diffM = { original : i , match : matches++ }; break; /* FULL DATE/TIME */ case "c": /* ISO 8601 date */ throw '"c" not implemented!'; case "r": /* RFC 2822 formatted date */ result[ i ] = '([\\wá]{3}, \\d{1,2} \\w{3} \\d{4} \\d{2}:\\d{2}:\\d{2} [+\\-]\\d{4})'; objIndex.date = { original : i , match : matches++ }; break; case "U": /* Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) */ result[ i ] = '(\\d{1,13})'; objIndex.date = { original : i , match : matches++ }; break; default: result[ i ] = iFormat[ i ]; } } var pattr = new RegExp( result.join('') ); try { mList = str_date.match( pattr ); if ( !mList ) { return; } } catch ( e ) { return ; } var _haveDatetime = typeof objIndex.date !== 'undefined'; var _haveYear = typeof objIndex.year !== 'undefined'; var _haveYDay = typeof objIndex.dayY !== 'undefined'; var _haveDay = typeof objIndex.day !== 'undefined'; var _haveMonth = typeof objIndex.month !== 'undefined'; var _haveMonthDay = _haveMonth && _haveDay; var _haveOnlyDay = !_haveMonth && _haveDay; var _haveWDay = typeof objIndex.dayW !== 'undefined'; var _haveWeek = typeof objIndex.week !== 'undefined'; var _haveWeekWDay = _haveWeek && _haveWDay; var _haveOnlyWDay = !_haveWeek && _haveWDay; var _validDate = _haveYDay || _haveMonthDay || !_haveYear && _haveOnlyDay || _haveWeekWDay || !_haveYear && _haveOnlyWDay; var _noDate = !_haveYear && !_haveYDay && !_haveDay && !_haveMonth && !_haveWDay && !_haveWeek; var _haveHour12 = typeof objIndex.hourD !== 'undefined' && typeof objIndex.ampm !== 'undefined'; var _haveHour24 = typeof objIndex.hour !== 'undefined'; var _haveHour = _haveHour12 || _haveHour24; var _haveMin = typeof objIndex.min !== 'undefined'; var _haveSec = typeof objIndex.sec !== 'undefined'; var _haveMSec = typeof objIndex.msec !== 'undefined'; var _haveMoreM = !_noDate || _haveHour; var _haveMoreS = _haveMoreM || _haveMin; var _haveDiffM = typeof objIndex.diffM !== 'undefined'; var _haveDiffH = typeof objIndex.diffH !== 'undefined'; //var _haveGMT = _haveDiffM || _haveDiffH; var hour; var min; if ( _haveDatetime ) { if ( iFormat[ objIndex.date.original ] === 'U' ) { return new Date( +mList[ objIndex.date.match + 1 ] * 1000 ); } var dList = mList[ objIndex.date.match + 1 ].match( /\w{3}, (\d{1,2}) (\w{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+\-]\d{4})/ ); hour = +dList[ 4 ] + ( +dList[ 7 ].slice( 0 , 3 ) ); min = +dList[ 5 ] + ( dList[ 7 ].slice( 0 , 1 ) + dList[ 7 ].slice( 3 ) ) / 100 * 60; return new Date( dList[ 3 ] , this._iMonth( dList[ 2 ] ) , dList[ 1 ] , hour , min , dList[ 6 ] ); } var _d = new Date( ); var year; var month; var day; var date; var sec; var msec; var gmt; if ( !_validDate && !_noDate ) { return ; } if ( _validDate ) { if ( _haveYear ) { var _y = _d.getFullYear( ) - 50 + ''; year = mList[ objIndex.year.match + 1 ]; if ( iFormat[ objIndex.year.original ] === 'y' ) { year = +_y.slice( 0 , 2 ) + ( year >= ( _y ).slice( 2 ) ? 0 : 1 ) + year; } } else { year = _d.getFullYear(); } if ( _haveYDay ) { month = 0; day = mList[ objIndex.dayY.match + 1 ]; } else if ( _haveDay ) { if ( _haveMonth ) { month = this._iMonth( mList[ objIndex.month.match + 1 ] ); } else { month = _d.getMonth( ); } day = mList[ objIndex.day.match + 1 ]; } else { month = 0; var week; if ( _haveWeek ) { week = mList[ objIndex.week.match + 1 ]; } else { week = this.get( 'W' , _d ); } day = ( week - 2 ) * 7 + ( 8 - ( ( new Date( year , 0 , 1 ) ).getDay( ) || 7 ) ) + this._iWeek( mList[ objIndex.week.match + 1 ] ); } if ( month === 0 && day > 31 ) { var aux = new Date( year , month , day ); month = aux.getMonth( ); day = aux.getDate( ); } } else { year = _d.getFullYear( ); month = _d.getMonth( ); day = _d.getDate( ); } date = year + '-' + ( month + 1 ) + '-' + day + ' '; if ( _haveHour12 ) { hour = +mList[ objIndex.hourD.match + 1 ] + ( mList[ objIndex.ampm.match + 1 ] === 'pm' ? 12 : 0 ); } else if ( _haveHour24 ) { hour = mList[ objIndex.hour.match + 1 ]; } else if ( _noDate ) { hour = _d.getHours( ); } else { hour = '00'; } if ( _haveMin ) { min = mList[ objIndex.min.match + 1 ]; } else if ( !_haveMoreM ) { min = _d.getMinutes( ); } else { min = '00'; } if ( _haveSec ) { sec = mList[ objIndex.sec.match + 1 ]; } else if ( !_haveMoreS ) { sec = _d.getSeconds( ); } else { sec = '00'; } if ( _haveMSec ) { msec = mList[ objIndex.msec.match + 1 ]; } else { msec = '000'; } if ( _haveDiffH ) { gmt = mList[ objIndex.diffH.match + 1 ]; } else if ( _haveDiffM ) { gmt = String( -1 * mList[ objIndex.diffM.match + 1 ] / 60 * 100 ).replace( /^(\d)/ , '+$1' ).replace( /(^[\-+])(\d{3}$)/ , '$10$2' ); } else { gmt = '+0000'; } return new Date( date + hour + ':' + min + ':' + sec + '.' + msec + gmt ); } }; return InkDate; }); /** * @module Ink.Util.Cookie_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.Cookie', '1', [], function() { 'use strict'; /** * Utilities for Cookie handling * * @class Ink.Util.Cookie * @version 1 * @static */ var Cookie = { /** * Gets an object with current page cookies * * @method get * @param {String} name * @return {String|Object} If the name is specified, it returns the value related to that property. Otherwise it returns the full cookie object * @public * @static * @example * Ink.requireModules(['Ink.Util.Cookie_1'], function( InkCookie ){ * var myCookieValue = InkCookie.get('someVarThere'); * console.log( myCookieValue ); // This will output the value of the cookie 'someVarThere', from the cookie object. * }); */ get: function(name) { var cookie = document.cookie || false; var _Cookie = {}; if(cookie) { cookie = cookie.replace(new RegExp("; ", "g"), ';'); var aCookie = cookie.split(';'); var aItem = []; if(aCookie.length > 0) { for(var i=0; i < aCookie.length; i++) { aItem = aCookie[i].split('='); if(aItem.length === 2) { _Cookie[aItem[0]] = decodeURIComponent(aItem[1]); } aItem = []; } } } if(name) { if(typeof(_Cookie[name]) !== 'undefined') { return _Cookie[name]; } else { return null; } } return _Cookie; }, /** * Sets a cookie * * @method set * @param {String} name Cookie name * @param {String} value Cookie value * @param {Number} [expires] Number to add to current Date in seconds * @param {String} [path] Path to sets cookie (default '/') * @param {String} [domain] Domain to sets cookie (default current hostname) * @param {Boolean} [secure] True if wants secure, default 'false' * @public * @static * @example * Ink.requireModules(['Ink.Util.Cookie_1'], function( InkCookie ){ * var expireDate = new Date( 2014,00,01, 0,0,0); * InkCookie.set( 'someVarThere', 'anyValueHere', expireDate.getTime() ); * }); */ set: function(name, value, expires, path, domain, secure) { var sName; if(!name || value===false || typeof(name) === 'undefined' || typeof(value) === 'undefined') { return false; } else { sName = name+'='+encodeURIComponent(value); } var sExpires = false; var sPath = false; var sDomain = false; var sSecure = false; if(expires && typeof(expires) !== 'undefined' && !isNaN(expires)) { var oDate = new Date(); var sDate = (parseInt(Number(oDate.valueOf()), 10) + (Number(parseInt(expires, 10)) * 1000)); var nDate = new Date(sDate); var expiresString = nDate.toGMTString(); var re = new RegExp("([^\\s]+)(\\s\\d\\d)\\s(\\w\\w\\w)\\s(.*)"); expiresString = expiresString.replace(re, "$1$2-$3-$4"); sExpires = 'expires='+expiresString; } else { if(typeof(expires) !== 'undefined' && !isNaN(expires) && Number(parseInt(expires, 10))===0) { sExpires = ''; } else { sExpires = 'expires=Thu, 01-Jan-2037 00:00:01 GMT'; } } if(path && typeof(path) !== 'undefined') { sPath = 'path='+path; } else { sPath = 'path=/'; } if(domain && typeof(domain) !== 'undefined') { sDomain = 'domain='+domain; } else { var portClean = new RegExp(":(.*)"); sDomain = 'domain='+window.location.host; sDomain = sDomain.replace(portClean,""); } if(secure && typeof(secure) !== 'undefined') { sSecure = secure; } else { sSecure = false; } document.cookie = sName+'; '+sExpires+'; '+sPath+'; '+sDomain+'; '+sSecure; }, /** * Delete a cookie * * @method remove * @param {String} cookieName Cookie name * @param {String} [path] Path of the cookie (default '/') * @param {String} [domain] Domain of the cookie (default current hostname) * @public * @static * @example * Ink.requireModules(['Ink.Util.Cookie_1'], function( InkCookie ){ * InkCookie.remove( 'someVarThere' ); * }); */ remove: function(cookieName, path, domain) { //var expiresDate = 'Thu, 01-Jan-1970 00:00:01 GMT'; var sPath = false; var sDomain = false; var expiresDate = -999999999; if(path && typeof(path) !== 'undefined') { sPath = path; } else { sPath = '/'; } if(domain && typeof(domain) !== 'undefined') { sDomain = domain; } else { sDomain = window.location.host; } this.set(cookieName, 'deleted', expiresDate, sPath, sDomain); } }; return Cookie; }); /** * @module Ink.Util.BinPack_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.BinPack', '1', [], function() { 'use strict'; /*jshint boss:true */ // https://github.com/jakesgordon/bin-packing/ /* Copyright (c) 2011, 2012, 2013 Jake Gordon and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var Packer = function(w, h) { this.init(w, h); }; Packer.prototype = { init: function(w, h) { this.root = { x: 0, y: 0, w: w, h: h }; }, fit: function(blocks) { var n, node, block; for (n = 0; n < blocks.length; ++n) { block = blocks[n]; if (node = this.findNode(this.root, block.w, block.h)) { block.fit = this.splitNode(node, block.w, block.h); } } }, findNode: function(root, w, h) { if (root.used) { return this.findNode(root.right, w, h) || this.findNode(root.down, w, h); } else if ((w <= root.w) && (h <= root.h)) { return root; } else { return null; } }, splitNode: function(node, w, h) { node.used = true; node.down = { x: node.x, y: node.y + h, w: node.w, h: node.h - h }; node.right = { x: node.x + w, y: node.y, w: node.w - w, h: h }; return node; } }; var GrowingPacker = function() {}; GrowingPacker.prototype = { fit: function(blocks) { var n, node, block, len = blocks.length; var w = len > 0 ? blocks[0].w : 0; var h = len > 0 ? blocks[0].h : 0; this.root = { x: 0, y: 0, w: w, h: h }; for (n = 0; n < len ; n++) { block = blocks[n]; if (node = this.findNode(this.root, block.w, block.h)) { block.fit = this.splitNode(node, block.w, block.h); } else { block.fit = this.growNode(block.w, block.h); } } }, findNode: function(root, w, h) { if (root.used) { return this.findNode(root.right, w, h) || this.findNode(root.down, w, h); } else if ((w <= root.w) && (h <= root.h)) { return root; } else { return null; } }, splitNode: function(node, w, h) { node.used = true; node.down = { x: node.x, y: node.y + h, w: node.w, h: node.h - h }; node.right = { x: node.x + w, y: node.y, w: node.w - w, h: h }; return node; }, growNode: function(w, h) { var canGrowDown = (w <= this.root.w); var canGrowRight = (h <= this.root.h); var shouldGrowRight = canGrowRight && (this.root.h >= (this.root.w + w)); // attempt to keep square-ish by growing right when height is much greater than width var shouldGrowDown = canGrowDown && (this.root.w >= (this.root.h + h)); // attempt to keep square-ish by growing down when width is much greater than height if (shouldGrowRight) { return this.growRight(w, h); } else if (shouldGrowDown) { return this.growDown(w, h); } else if (canGrowRight) { return this.growRight(w, h); } else if (canGrowDown) { return this.growDown(w, h); } else { return null; // need to ensure sensible root starting size to avoid this happening } }, growRight: function(w, h) { this.root = { used: true, x: 0, y: 0, w: this.root.w + w, h: this.root.h, down: this.root, right: { x: this.root.w, y: 0, w: w, h: this.root.h } }; var node; if (node = this.findNode(this.root, w, h)) { return this.splitNode(node, w, h); } else { return null; } }, growDown: function(w, h) { this.root = { used: true, x: 0, y: 0, w: this.root.w, h: this.root.h + h, down: { x: 0, y: this.root.h, w: this.root.w, h: h }, right: this.root }; var node; if (node = this.findNode(this.root, w, h)) { return this.splitNode(node, w, h); } else { return null; } } }; var sorts = { random: function() { return Math.random() - 0.5; }, w: function(a, b) { return b.w - a.w; }, h: function(a, b) { return b.h - a.h; }, a: function(a, b) { return b.area - a.area; }, max: function(a, b) { return Math.max(b.w, b.h) - Math.max(a.w, a.h); }, min: function(a, b) { return Math.min(b.w, b.h) - Math.min(a.w, a.h); }, height: function(a, b) { return sorts.msort(a, b, ['h', 'w']); }, width: function(a, b) { return sorts.msort(a, b, ['w', 'h']); }, area: function(a, b) { return sorts.msort(a, b, ['a', 'h', 'w']); }, maxside: function(a, b) { return sorts.msort(a, b, ['max', 'min', 'h', 'w']); }, msort: function(a, b, criteria) { /* sort by multiple criteria */ var diff, n; for (n = 0; n < criteria.length; ++n) { diff = sorts[ criteria[n] ](a, b); if (diff !== 0) { return diff; } } return 0; } }; // end of Jake's code // aux, used to display blocks in unfitted property var toString = function() { return [this.w, ' x ', this.h].join(''); }; /** * Binary Packing algorithm implementation * * Based on the work of Jake Gordon * * see https://github.com/jakesgordon/bin-packing/ * * @class Ink.Util.BinPack * @version 1 * @static */ var BinPack = { /** * @method binPack * @param {Object} o options * @param {Object[]} o.blocks array of items with w and h integer attributes. * @param {Number[2]} [o.dimensions] if passed, container has fixed dimensions * @param {String} [o.sorter] sorter function. one of: random, height, width, area, maxside * @return {Object} * * {Number[2]} dimensions - resulted container size, * * {Number} filled - filled ratio, * * {Object[]} fitted, * * {Object[]} unfitted, * * {Object[]} blocks * @static */ binPack: function(o) { var i, f, bl; // calculate area if not there already for (i = 0, f = o.blocks.length; i < f; ++i) { bl = o.blocks[i]; if (! ('area' in bl) ) { bl.area = bl.w * bl.h; } } // apply algorithm var packer = o.dimensions ? new Packer(o.dimensions[0], o.dimensions[1]) : new GrowingPacker(); if (!o.sorter) { o.sorter = 'maxside'; } o.blocks.sort( sorts[ o.sorter ] ); packer.fit(o.blocks); var dims2 = [packer.root.w, packer.root.h]; // layout is done here, generating report data... var fitted = []; var unfitted = []; for (i = 0, f = o.blocks.length; i < f; ++i) { bl = o.blocks[i]; if (bl.fit) { fitted.push(bl); } else { bl.toString = toString; // TO AID SERIALIZATION unfitted.push(bl); } } var area = dims2[0] * dims2[1]; var fit = 0; for (i = 0, f = fitted.length; i < f; ++i) { bl = fitted[i]; fit += bl.area; } return { dimensions: dims2, filled: fit / area, blocks: o.blocks, fitted: fitted, unfitted: unfitted }; } }; return BinPack; }); /** * @module Ink.Util.Array_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.Array', '1', [], function() { 'use strict'; var arrayProto = Array.prototype; /** * Utility functions to use with Arrays * * @class Ink.Util.Array * @version 1 * @static */ var InkArray = { /** * Checks if value exists in array * * @method inArray * @param {Mixed} value * @param {Array} arr * @return {Boolean} True if value exists in the array * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ 'value1', 'value2', 'value3' ]; * if( InkArray.inArray( 'value2', testArray ) === true ){ * console.log( "Yep it's in the array." ); * } else { * console.log( "No it's NOT in the array." ); * } * }); */ inArray: function(value, arr) { if (typeof arr === 'object') { for (var i = 0, f = arr.length; i < f; ++i) { if (arr[i] === value) { return true; } } } return false; }, /** * Sorts an array of object by an object property * * @method sortMulti * @param {Array} arr array of objects to sort * @param {String} key property to sort by * @return {Array|Boolean} False if it's not an array, returns a sorted array if it's an array. * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ * { 'myKey': 'value1' }, * { 'myKey': 'value2' }, * { 'myKey': 'value3' } * ]; * * InkArray.sortMulti( testArray, 'myKey' ); * }); */ sortMulti: function(arr, key) { if (typeof arr === 'undefined' || arr.constructor !== Array) { return false; } if (typeof key !== 'string') { return arr.sort(); } if (arr.length > 0) { if (typeof(arr[0][key]) === 'undefined') { return false; } arr.sort(function(a, b){ var x = a[key]; var y = b[key]; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); } return arr; }, /** * Returns the associated key of an array value * * @method keyValue * @param {String} value Value to search for * @param {Array} arr Array where the search will run * @param {Boolean} [first] Flag that determines if the search stops at first occurrence. It also returns an index number instead of an array of indexes. * @return {Boolean|Number|Array} False if not exists | number if exists and 3rd input param is true | array if exists and 3rd input param is not set or it is !== true * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ 'value1', 'value2', 'value3', 'value2' ]; * console.log( InkArray.keyValue( 'value2', testArray, true ) ); // Result: 1 * console.log( InkArray.keyValue( 'value2', testArray ) ); // Result: [1, 3] * }); */ keyValue: function(value, arr, first) { if (typeof value !== 'undefined' && typeof arr === 'object' && this.inArray(value, arr)) { var aKeys = []; for (var i = 0, f = arr.length; i < f; ++i) { if (arr[i] === value) { if (typeof first !== 'undefined' && first === true) { return i; } else { aKeys.push(i); } } } return aKeys; } return false; }, /** * Returns the array shuffled, false if the param is not an array * * @method shuffle * @param {Array} arr Array to shuffle * @return {Boolean|Number|Array} False if not an array | Array shuffled * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ 'value1', 'value2', 'value3', 'value2' ]; * console.log( InkArray.shuffle( testArray ) ); // Result example: [ 'value3', 'value2', 'value2', 'value1' ] * }); */ shuffle: function(arr) { if (typeof(arr) !== 'undefined' && arr.constructor !== Array) { return false; } var total = arr.length, tmp1 = false, rnd = false; while (total--) { rnd = Math.floor(Math.random() * (total + 1)); tmp1 = arr[total]; arr[total] = arr[rnd]; arr[rnd] = tmp1; } return arr; }, /** * Runs a function through each of the elements of an array * * @method forEach * @param {Array} arr Array to be cycled/iterated * @param {Function} cb The function receives as arguments the value, index and array. * @return {Array} Array iterated. * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ 'value1', 'value2', 'value3', 'value2' ]; * InkArray.forEach( testArray, function( value, index, arr ){ * console.log( 'The value is: ' + value + ' | The index is: ' + index ); * }); * }); */ forEach: function(array, callback, context) { if (arrayProto.forEach) { return arrayProto.forEach.call(array, callback, context); } for (var i = 0, len = array.length >>> 0; i < len; i++) { callback.call(context, array[i], i, array); } }, /** * Alias for backwards compatibility. See forEach * * @method forEach */ each: function () { InkArray.forEach.apply(InkArray, [].slice.call(arguments)); }, /** * Run a `map` function for each item in the array. The function will receive each item as argument and its return value will change the corresponding array item. * @method map * @param {Array} array The array to map over * @param {Function} map The map function. Will take `(item, index, array)` and `this` will be the `context` argument. * @param {Object} [context] Object to be `this` in the map function. * * @example * InkArray.map([1, 2, 3, 4], function (item) { * return item + 1; * }); // -> [2, 3, 4, 5] */ map: function (array, callback, context) { if (arrayProto.map) { return arrayProto.map.call(array, callback, context); } var mapped = new Array(len); for (var i = 0, len = array.length >>> 0; i < len; i++) { mapped[i] = callback.call(context, array[i], i, array); } return mapped; }, /** * Run a test function through all the input array. Items which pass the test function (for which the test function returned `true`) are kept in the array. Other items are removed. * @param {Array} array * @param {Function} test A test function taking `(item, index, array)` * @param {Object} [context] Object to be `this` in the test function. * @return filtered array * * @example * InkArray.filter([1, 2, 3, 4, 5], function (val) { * return val > 2; * }) // -> [3, 4, 5] */ filter: function (array, test, context) { if (arrayProto.filter) { return arrayProto.filter.call(array, test, context); } var filtered = [], val = null; for (var i = 0, len = array.length; i < len; i++) { val = array[i]; // it might be mutated if (test.call(context, val, i, array)) { filtered.push(val); } } return filtered; }, /** * Runs a callback function, which should return true or false. * If one of the 'runs' returns true, it will return. Otherwise if none returns true, it will return false. * See more at: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some (MDN) * * @method some * @param {Array} arr The array you walk to iterate through * @param {Function} cb The callback that will be called on the array's elements. It receives the value, the index and the array as arguments. * @param {Object} Context object of the callback function * @return {Boolean} True if the callback returns true at any point, false otherwise * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray1 = [ 10, 20, 50, 100, 30 ]; * var testArray2 = [ 1, 2, 3, 4, 5 ]; * * function myTestFunction( value, index, arr ){ * if( value > 90 ){ * return true; * } * return false; * } * console.log( InkArray.some( testArray1, myTestFunction, null ) ); // Result: true * console.log( InkArray.some( testArray2, myTestFunction, null ) ); // Result: false * }); */ some: function(arr, cb, context){ if (arr === null){ throw new TypeError('First argument is invalid.'); } var t = Object(arr); var len = t.length >>> 0; if (typeof cb !== "function"){ throw new TypeError('Second argument must be a function.'); } for (var i = 0; i < len; i++) { if (i in t && cb.call(context, t[i], i, t)){ return true; } } return false; }, /** * Returns an array containing every item that is shared between the two given arrays * * @method intersect * @param {Array} arr Array1 to be intersected with Array2 * @param {Array} arr Array2 to be intersected with Array1 * @return {Array} Empty array if one of the arrays is false (or do not intersect) | Array with the intersected values * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray1 = [ 'value1', 'value2', 'value3' ]; * var testArray2 = [ 'value2', 'value3', 'value4', 'value5', 'value6' ]; * console.log( InkArray.intersect( testArray1,testArray2 ) ); // Result: [ 'value2', 'value3' ] * }); */ intersect: function(arr1, arr2) { if (!arr1 || !arr2 || arr1 instanceof Array === false || arr2 instanceof Array === false) { return []; } var shared = []; for (var i = 0, I = arr1.length; i<I; ++i) { for (var j = 0, J = arr2.length; j < J; ++j) { if (arr1[i] === arr2[j]) { shared.push(arr1[i]); } } } return shared; }, /** * Convert lists type to type array * * @method convert * @param {Array} arr Array to be converted * @return {Array} Array resulting of the conversion * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ 'value1', 'value2' ]; * testArray.myMethod = function(){ * console.log('stuff'); * } * * console.log( InkArray.convert( testArray ) ); // Result: [ 'value1', 'value2' ] * }); */ convert: function(arr) { return arrayProto.slice.call(arr || [], 0); }, /** * Insert value into the array on specified idx * * @method insert * @param {Array} arr Array where the value will be inserted * @param {Number} idx Index of the array where the value should be inserted * @param {Mixed} value Value to be inserted * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ 'value1', 'value2' ]; * console.log( InkArray.insert( testArray, 1, 'value3' ) ); // Result: [ 'value1', 'value3', 'value2' ] * }); */ insert: function(arr, idx, value) { arr.splice(idx, 0, value); }, /** * Remove a range of values from the array * * @method remove * @param {Array} arr Array where the value will be inserted * @param {Number} from Index of the array where the removal will start removing. * @param {Number} rLen Number of items to be removed from the index onwards. * @return {Array} An array with the remaining values * @public * @static * @example * Ink.requireModules(['Ink.Util.Array_1'], function( InkArray ){ * var testArray = [ 'value1', 'value2', 'value3', 'value4', 'value5' ]; * console.log( InkArray.remove( testArray, 1, 3 ) ); // Result: [ 'value1', 'value4', 'value5' ] * }); */ remove: function(arr, from, rLen){ var output = []; for(var i = 0, iLen = arr.length; i < iLen; i++){ if(i >= from && i < from + rLen){ continue; } output.push(arr[i]); } return output; } }; return InkArray; }); /** * @module Ink.Util.Validator_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.Util.Validator', '1', [], function() { 'use strict'; /** * Set of functions to provide validation * * @class Ink.Util.Validator * @version 1 * @static */ var Validator = { /** * List of country codes avaible for isPhone function * * @property _countryCodes * @type {Array} * @private * @static * @readOnly */ _countryCodes : [ 'AO', 'CV', 'MZ', 'PT' ], /** * International number for portugal * * @property _internacionalPT * @type {Number} * @private * @static * @readOnly * */ _internacionalPT: 351, /** * List of all portuguese number prefixes * * @property _indicativosPT * @type {Object} * @private * @static * @readOnly * */ _indicativosPT: { 21: 'lisboa', 22: 'porto', 231: 'mealhada', 232: 'viseu', 233: 'figueira da foz', 234: 'aveiro', 235: 'arganil', 236: 'pombal', 238: 'seia', 239: 'coimbra', 241: 'abrantes', 242: 'ponte de sôr', 243: 'santarém', 244: 'leiria', 245: 'portalegre', 249: 'torres novas', 251: 'valença', 252: 'vila nova de famalicão', 253: 'braga', 254: 'peso da régua', 255: 'penafiel', 256: 'são joão da madeira', 258: 'viana do castelo', 259: 'vila real', 261: 'torres vedras', 262: 'caldas da raínha', 263: 'vila franca de xira', 265: 'setúbal', 266: 'évora', 268: 'estremoz', 269: 'santiago do cacém', 271: 'guarda', 272: 'castelo branco', 273: 'bragança', 274: 'proença-a-nova', 275: 'covilhã', 276: 'chaves', 277: 'idanha-a-nova', 278: 'mirandela', 279: 'moncorvo', 281: 'tavira', 282: 'portimão', 283: 'odemira', 284: 'beja', 285: 'moura', 286: 'castro verde', 289: 'faro', 291: 'funchal, porto santo', 292: 'corvo, faial, flores, horta, pico', 295: 'angra do heroísmo, graciosa, são jorge, terceira', 296: 'ponta delgada, são miguel, santa maria', 91 : 'rede móvel 91 (Vodafone / Yorn)', 93 : 'rede móvel 93 (Optimus)', 96 : 'rede móvel 96 (TMN)', 92 : 'rede móvel 92 (TODOS)', //925 : 'rede móvel 925 (TMN 925)', //926 : 'rede móvel 926 (TMN 926)', //927 : 'rede móvel 927 (TMN 927)', //922 : 'rede móvel 922 (Phone-ix)', 707: 'número único', 760: 'número único', 800: 'número grátis', 808: 'chamada local', 30: 'voip' }, /** * International number for Cabo Verde * * @property _internacionalCV * @type {Number} * @private * @static * @readOnly */ _internacionalCV: 238, /** * List of all Cabo Verde number prefixes * * @property _indicativosCV * @type {Object} * @private * @static * @readOnly */ _indicativosCV: { 2: 'fixo', 91: 'móvel 91', 95: 'móvel 95', 97: 'móvel 97', 98: 'móvel 98', 99: 'móvel 99' }, /** * International number for angola * * @property _internacionalAO * @type {Number} * @private * @static * @readOnly */ _internacionalAO: 244, /** * List of all Angola number prefixes * * @property _indicativosAO * @type {Object} * @private * @static * @readOnly */ _indicativosAO: { 2: 'fixo', 91: 'móvel 91', 92: 'móvel 92' }, /** * International number for mozambique * * @property _internacionalMZ * @type {Number} * @private * @static * @readOnly */ _internacionalMZ: 258, /** * List of all Mozambique number prefixes * * @property _indicativosMZ * @type {Object} * @private * @static * @readOnly */ _indicativosMZ: { 2: 'fixo', 82: 'móvel 82', 84: 'móvel 84' }, /** * International number for Timor * * @property _internacionalTL * @type {Number} * @private * @static * @readOnly */ _internacionalTL: 670, /** * List of all Timor number prefixes * * @property _indicativosTL * @type {Object} * @private * @static * @readOnly */ _indicativosTL: { 3: 'fixo', 7: 'móvel 7' }, /** * Regular expression groups for several groups of characters * * http://en.wikipedia.org/wiki/C0_Controls_and_Basic_Latin * http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane * http://en.wikipedia.org/wiki/ISO_8859-1 * * @property _characterGroups * @type {Object} * @private * @static * @readOnly */ _characterGroups: { numbers: ['0-9'], asciiAlpha: ['a-zA-Z'], latin1Alpha: ['a-zA-Z', '\u00C0-\u00FF'], unicodeAlpha: ['a-zA-Z', '\u00C0-\u00FF', '\u0100-\u1FFF', '\u2C00-\uD7FF'], /* whitespace characters */ space: [' '], dash: ['-'], underscore: ['_'], nicknamePunctuation: ['_.-'], singleLineWhitespace: ['\t '], newline: ['\n'], whitespace: ['\t\n\u000B\f\r\u00A0 '], asciiPunctuation: ['\u0021-\u002F', '\u003A-\u0040', '\u005B-\u0060', '\u007B-\u007E'], latin1Punctuation: ['\u0021-\u002F', '\u003A-\u0040', '\u005B-\u0060', '\u007B-\u007E', '\u00A1-\u00BF', '\u00D7', '\u00F7'], unicodePunctuation: ['\u0021-\u002F', '\u003A-\u0040', '\u005B-\u0060', '\u007B-\u007E', '\u00A1-\u00BF', '\u00D7', '\u00F7', '\u2000-\u206F', '\u2E00-\u2E7F', '\u3000-\u303F'], }, /** * Create a regular expression for several character groups. * * @method createRegExp * * @param Groups... {Object} * Groups to build regular expressions for. Possible keys are: * * - **numbers**: 0-9 * - **asciiAlpha**: a-z, A-Z * - **latin1Alpha**: asciiAlpha, plus printable characters in latin-1 * - **unicodeAlpha**: unicode alphanumeric characters. * - **space**: ' ', the space character. * - **dash**: dash character. * - **underscore**: underscore character. * - **nicknamePunctuation**: dash, dot, underscore * - **singleLineWhitespace**: space and tab (whitespace which only spans one line). * - **newline**: newline character ('\n') * - **whitespace**: whitespace characters in the ASCII character set. * - **asciiPunctuation**: punctuation characters in the ASCII character set. * - **latin1Punctuation**: punctuation characters in latin-1. * - **unicodePunctuation**: punctuation characters in unicode. * */ createRegExp: function (groups) { var re = '^['; for (var key in groups) if (groups.hasOwnProperty(key)) { if (!(key in Validator._characterGroups)) { throw new Error('group ' + key + ' is not a valid character group'); } else if (groups[key]) { re += Validator._characterGroups[key].join(''); } } return new RegExp(re + ']*?$'); }, /** * Checks if a field has the required groups. Takes an options object for further configuration. * * @method checkCharacterGroups * @param {String} s The validation string * @param {Object} [groups={}] What groups are included. * @param [options.*] See createRegexp */ checkCharacterGroups: function (s, groups) { return Validator.createRegExp(groups).test(s); }, /** * Checks whether a field contains unicode printable characters. Takes an * options object for further configuration * * @method unicode * @param {String} s The validation string * @param {Object} [options={}] Optional configuration object * @param [options.*] See createRegexp */ unicode: function (s, options) { return Validator.checkCharacterGroups(s, Ink.extendObj({ unicodeAlpha: true}, options)); }, /** * Checks that a field only contains only latin-1 alphanumeric * characters. Takes options for allowing singleline whitespace, * cross-line whitespace and punctuation. * * @method latin1 * * @param {String} s The validation string * @param {Object} [options={}] Optional configuration object * @param [options.*] See createRegexp */ latin1: function (s, options) { return Validator.checkCharacterGroups(s, Ink.extendObj({ latin1Alpha: true}, options)); }, /** * Checks that a field only contains only ASCII alphanumeric * characters. Takes options for allowing singleline whitespace, * cross-line whitespace and punctuation. * * @method ascii * * @param {String} s The validation string * @param {Object} [options={}] Optional configuration object * @param [options.*] See createRegexp */ ascii: function (s, options) { return Validator.checkCharacterGroups(s, Ink.extendObj({ asciiAlpha: true}, options)); }, /** * Checks that the number is a valid number * * @method number * @param {String} numb The number * @param {Object} [options] Further options * @param [options.decimalSep='.'] Allow decimal separator. * @param [options.thousandSep=","] Strip this character from the number. * @param [options.negative=false] Allow negative numbers. * @param [options.decimalPlaces=0] Maximum number of decimal places. `0` means integer number. * @param [options.max=null] Maximum number * @param [options.min=null] Minimum number * @param [options.returnNumber=false] When this option is true, return the number itself when the value is valid. */ number: function (numb, inOptions) { numb = numb + ''; var options = Ink.extendObj({ decimalSep: '.', thousandSep: '', negative: true, decimalPlaces: null, maxDigits: null, max: null, min: null, returnNumber: false }, inOptions || {}); // smart recursion thing sets up aliases for options. if (options.thousandSep) { numb = numb.replace(new RegExp('\\' + options.thousandSep, 'g'), ''); options.thousandSep = ''; return Validator.number(numb, options); } if (options.negative === false) { options.min = 0; options.negative = true; return Validator.number(numb, options); } if (options.decimalSep !== '.') { numb = numb.replace(new RegExp('\\' + options.decimalSep, 'g'), '.'); } if (!/^(-)?(\d+)?(\.\d+)?$/.test(numb) || numb === '') { return false; // forbidden character found } var split; if (options.decimalSep && numb.indexOf(options.decimalSep) !== -1) { split = numb.split(options.decimalSep); if (options.decimalPlaces !== null && split[1].length > options.decimalPlaces) { return false; } } else { split = ['' + numb, '']; } if (options.maxDigits!== null) { if (split[0].replace(/-/g, '').length > options.maxDigits) { return split } } // Now look at the actual float var ret = parseFloat(numb); if (options.maxExcl !== null && ret >= options.maxExcl || options.minExcl !== null && ret <= options.minExcl) { return false; } if (options.max !== null && ret > options.max || options.min !== null && ret < options.min) { return false; } if (options.returnNumber) { return ret; } else { return true; } }, /** * Checks if a year is Leap "Bissexto" * * @method _isLeapYear * @param {Number} year Year to be checked * @return {Boolean} True if it is a leap year. * @private * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator._isLeapYear( 2004 ) ); // Result: true * console.log( InkValidator._isLeapYear( 2006 ) ); // Result: false * }); */ _isLeapYear: function(year){ var yearRegExp = /^\d{4}$/; if(yearRegExp.test(year)){ return ((year%4) ? false: ((year%100) ? true : ((year%400)? false : true)) ); } return false; }, /** * Object with the date formats available for validation * * @property _dateParsers * @type {Object} * @private * @static * @readOnly */ _dateParsers: { 'yyyy-mm-dd': {day:5, month:3, year:1, sep: '-', parser: /^(\d{4})(\-)(\d{1,2})(\-)(\d{1,2})$/}, 'yyyy/mm/dd': {day:5, month:3, year:1, sep: '/', parser: /^(\d{4})(\/)(\d{1,2})(\/)(\d{1,2})$/}, 'yy-mm-dd': {day:5, month:3, year:1, sep: '-', parser: /^(\d{2})(\-)(\d{1,2})(\-)(\d{1,2})$/}, 'yy/mm/dd': {day:5, month:3, year:1, sep: '/', parser: /^(\d{2})(\/)(\d{1,2})(\/)(\d{1,2})$/}, 'dd-mm-yyyy': {day:1, month:3, year:5, sep: '-', parser: /^(\d{1,2})(\-)(\d{1,2})(\-)(\d{4})$/}, 'dd/mm/yyyy': {day:1, month:3, year:5, sep: '/', parser: /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/}, 'dd-mm-yy': {day:1, month:3, year:5, sep: '-', parser: /^(\d{1,2})(\-)(\d{1,2})(\-)(\d{2})$/}, 'dd/mm/yy': {day:1, month:3, year:5, sep: '/', parser: /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{2})$/} }, /** * Calculates the number of days in a given month of a given year * * @method _daysInMonth * @param {Number} _m - month (1 to 12) * @param {Number} _y - year * @return {Number} Returns the number of days in a given month of a given year * @private * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator._daysInMonth( 2, 2004 ) ); // Result: 29 * console.log( InkValidator._daysInMonth( 2, 2006 ) ); // Result: 28 * }); */ _daysInMonth: function(_m,_y){ var nDays=0; if(_m===1 || _m===3 || _m===5 || _m===7 || _m===8 || _m===10 || _m===12) { nDays= 31; } else if ( _m===4 || _m===6 || _m===9 || _m===11) { nDays = 30; } else { if((_y%400===0) || (_y%4===0 && _y%100!==0)) { nDays = 29; } else { nDays = 28; } } return nDays; }, /** * Checks if a date is valid * * @method _isValidDate * @param {Number} year * @param {Number} month * @param {Number} day * @return {Boolean} True if it's a valid date * @private * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator._isValidDate( 2004, 2, 29 ) ); // Result: true * console.log( InkValidator._isValidDate( 2006, 2, 29 ) ); // Result: false * }); */ _isValidDate: function(year, month, day){ var yearRegExp = /^\d{4}$/; var validOneOrTwo = /^\d{1,2}$/; if(yearRegExp.test(year) && validOneOrTwo.test(month) && validOneOrTwo.test(day)){ if(month>=1 && month<=12 && day>=1 && this._daysInMonth(month,year)>=day){ return true; } } return false; }, /** * Checks if a email is valid * * @method mail * @param {String} email * @return {Boolean} True if it's a valid e-mail * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.email( 'agfsdfgfdsgdsf' ) ); // Result: false * console.log( InkValidator.email( 'inkdev\u0040sapo.pt' ) ); // Result: true (where \u0040 is at sign) * }); */ email: function(email) { var emailValido = new RegExp("^[_a-z0-9-]+((\\.|\\+)[_a-z0-9-]+)*@([\\w]*-?[\\w]*\\.)+[a-z]{2,4}$", "i"); if(!emailValido.test(email)) { return false; } else { return true; } }, /** * Deprecated. Alias for email(). Use it instead. * * @method mail * @public * @static */ mail: function (mail) { return Validator.email(mail); }, /** * Checks if a url is valid * * @method url * @param {String} url URL to be checked * @param {Boolean} [full] If true, validates a full URL (one that should start with 'http') * @return {Boolean} True if the given URL is valid * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.url( 'www.sapo.pt' ) ); // Result: true * console.log( InkValidator.url( 'http://www.sapo.pt', true ) ); // Result: true * console.log( InkValidator.url( 'meh' ) ); // Result: false * }); */ url: function(url, full) { if(typeof full === "undefined" || full === false) { var reHTTP = new RegExp("(^(http\\:\\/\\/|https\\:\\/\\/)(.+))", "i"); if(reHTTP.test(url) === false) { url = 'http://'+url; } } var reUrl = new RegExp("^(http:\\/\\/|https:\\/\\/)([\\w]*(-?[\\w]*)*\\.)+[a-z]{2,4}", "i"); if(reUrl.test(url) === false) { return false; } else { return true; } }, /** * Checks if a phone is valid in Portugal * * @method isPTPhone * @param {Number} phone Phone number to be checked * @return {Boolean} True if it's a valid Portuguese Phone * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isPTPhone( '213919264' ) ); // Result: true * console.log( InkValidator.isPTPhone( '00351213919264' ) ); // Result: true * console.log( InkValidator.isPTPhone( '+351213919264' ) ); // Result: true * console.log( InkValidator.isPTPhone( '1' ) ); // Result: false * }); */ isPTPhone: function(phone) { phone = phone.toString(); var aInd = []; for(var i in this._indicativosPT) { if(typeof(this._indicativosPT[i]) === 'string') { aInd.push(i); } } var strInd = aInd.join('|'); var re351 = /^(00351|\+351)/; if(re351.test(phone)) { phone = phone.replace(re351, ""); } var reSpecialChars = /(\s|\-|\.)+/g; phone = phone.replace(reSpecialChars, ''); //var reInt = new RegExp("\\d", "i"); var reInt = /[\d]{9}/i; if(phone.length === 9 && reInt.test(phone)) { var reValid = new RegExp("^("+strInd+")"); if(reValid.test(phone)) { return true; } } return false; }, /** * Alias function for isPTPhone * * @method isPortuguesePhone * @param {Number} phone Phone number to be checked * @return {Boolean} True if it's a valid Portuguese Phone * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isPortuguesePhone( '213919264' ) ); // Result: true * console.log( InkValidator.isPortuguesePhone( '00351213919264' ) ); // Result: true * console.log( InkValidator.isPortuguesePhone( '+351213919264' ) ); // Result: true * console.log( InkValidator.isPortuguesePhone( '1' ) ); // Result: false * }); */ isPortuguesePhone: function(phone) { return this.isPTPhone(phone); }, /** * Checks if a phone is valid in Cabo Verde * * @method isCVPhone * @param {Number} phone Phone number to be checked * @return {Boolean} True if it's a valid Cape Verdean Phone * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isCVPhone( '2610303' ) ); // Result: true * console.log( InkValidator.isCVPhone( '002382610303' ) ); // Result: true * console.log( InkValidator.isCVPhone( '+2382610303' ) ); // Result: true * console.log( InkValidator.isCVPhone( '1' ) ); // Result: false * }); */ isCVPhone: function(phone) { phone = phone.toString(); var aInd = []; for(var i in this._indicativosCV) { if(typeof(this._indicativosCV[i]) === 'string') { aInd.push(i); } } var strInd = aInd.join('|'); var re238 = /^(00238|\+238)/; if(re238.test(phone)) { phone = phone.replace(re238, ""); } var reSpecialChars = /(\s|\-|\.)+/g; phone = phone.replace(reSpecialChars, ''); //var reInt = new RegExp("\\d", "i"); var reInt = /[\d]{7}/i; if(phone.length === 7 && reInt.test(phone)) { var reValid = new RegExp("^("+strInd+")"); if(reValid.test(phone)) { return true; } } return false; }, /** * Checks if a phone is valid in Angola * * @method isAOPhone * @param {Number} phone Phone number to be checked * @return {Boolean} True if it's a valid Angolan Phone * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isAOPhone( '244222396385' ) ); // Result: true * console.log( InkValidator.isAOPhone( '00244222396385' ) ); // Result: true * console.log( InkValidator.isAOPhone( '+244222396385' ) ); // Result: true * console.log( InkValidator.isAOPhone( '1' ) ); // Result: false * }); */ isAOPhone: function(phone) { phone = phone.toString(); var aInd = []; for(var i in this._indicativosAO) { if(typeof(this._indicativosAO[i]) === 'string') { aInd.push(i); } } var strInd = aInd.join('|'); var re244 = /^(00244|\+244)/; if(re244.test(phone)) { phone = phone.replace(re244, ""); } var reSpecialChars = /(\s|\-|\.)+/g; phone = phone.replace(reSpecialChars, ''); //var reInt = new RegExp("\\d", "i"); var reInt = /[\d]{9}/i; if(phone.length === 9 && reInt.test(phone)) { var reValid = new RegExp("^("+strInd+")"); if(reValid.test(phone)) { return true; } } return false; }, /** * Checks if a phone is valid in Mozambique * * @method isMZPhone * @param {Number} phone Phone number to be checked * @return {Boolean} True if it's a valid Mozambican Phone * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isMZPhone( '21426861' ) ); // Result: true * console.log( InkValidator.isMZPhone( '0025821426861' ) ); // Result: true * console.log( InkValidator.isMZPhone( '+25821426861' ) ); // Result: true * console.log( InkValidator.isMZPhone( '1' ) ); // Result: false * }); */ isMZPhone: function(phone) { phone = phone.toString(); var aInd = []; for(var i in this._indicativosMZ) { if(typeof(this._indicativosMZ[i]) === 'string') { aInd.push(i); } } var strInd = aInd.join('|'); var re258 = /^(00258|\+258)/; if(re258.test(phone)) { phone = phone.replace(re258, ""); } var reSpecialChars = /(\s|\-|\.)+/g; phone = phone.replace(reSpecialChars, ''); //var reInt = new RegExp("\\d", "i"); var reInt = /[\d]{8,9}/i; if((phone.length === 9 || phone.length === 8) && reInt.test(phone)) { var reValid = new RegExp("^("+strInd+")"); if(reValid.test(phone)) { if(phone.indexOf('2') === 0 && phone.length === 8) { return true; } else if(phone.indexOf('8') === 0 && phone.length === 9) { return true; } } } return false; }, /** * Checks if a phone is valid in Timor * * @method isTLPhone * @param {Number} phone Phone number to be checked * @return {Boolean} True if it's a valid phone from Timor-Leste * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isTLPhone( '6703331234' ) ); // Result: true * console.log( InkValidator.isTLPhone( '006703331234' ) ); // Result: true * console.log( InkValidator.isTLPhone( '+6703331234' ) ); // Result: true * console.log( InkValidator.isTLPhone( '1' ) ); // Result: false * }); */ isTLPhone: function(phone) { phone = phone.toString(); var aInd = []; for(var i in this._indicativosTL) { if(typeof(this._indicativosTL[i]) === 'string') { aInd.push(i); } } var strInd = aInd.join('|'); var re670 = /^(00670|\+670)/; if(re670.test(phone)) { phone = phone.replace(re670, ""); } var reSpecialChars = /(\s|\-|\.)+/g; phone = phone.replace(reSpecialChars, ''); //var reInt = new RegExp("\\d", "i"); var reInt = /[\d]{7}/i; if(phone.length === 7 && reInt.test(phone)) { var reValid = new RegExp("^("+strInd+")"); if(reValid.test(phone)) { return true; } } return false; }, /** * Validates the function in all country codes available or in the ones set in the second param * * @method isPhone * @param {String} phone number * @param {optional String|Array} country or array of countries to validate * @return {Boolean} True if it's a valid phone in any country available * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isPhone( '6703331234' ) ); // Result: true * }); */ isPhone: function(){ var index; if(arguments.length===0){ return false; } var phone = arguments[0]; if(arguments.length>1){ if(arguments[1].constructor === Array){ var func; for(index=0; index<arguments[1].length; index++ ){ if(typeof(func=this['is' + arguments[1][index].toUpperCase() + 'Phone'])==='function'){ if(func(phone)){ return true; } } else { throw "Invalid Country Code!"; } } } else if(typeof(this['is' + arguments[1].toUpperCase() + 'Phone'])==='function'){ return this['is' + arguments[1].toUpperCase() + 'Phone'](phone); } else { throw "Invalid Country Code!"; } } else { for(index=0; index<this._countryCodes.length; index++){ if(this['is' + this._countryCodes[index] + 'Phone'](phone)){ return true; } } } return false; }, /** * Validates if a zip code is valid in Portugal * * @method codPostal * @param {Number|String} cp1 * @param {optional Number|String} cp2 * @param {optional Boolean} returnBothResults * @return {Boolean} True if it's a valid zip code * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.codPostal( '1069', '300' ) ); // Result: true * console.log( InkValidator.codPostal( '1069', '300', true ) ); // Result: [true, true] * }); * */ codPostal: function(cp1,cp2,returnBothResults){ var cPostalSep = /^(\s*\-\s*|\s+)$/; var trim = /^\s+|\s+$/g; var cPostal4 = /^[1-9]\d{3}$/; var cPostal3 = /^\d{3}$/; var parserCPostal = /^(.{4})(.*)(.{3})$/; returnBothResults = !!returnBothResults; cp1 = cp1.replace(trim,''); if(typeof(cp2)!=='undefined'){ cp2 = cp2.replace(trim,''); if(cPostal4.test(cp1) && cPostal3.test(cp2)){ if( returnBothResults === true ){ return [true, true]; } else { return true; } } } else { if(cPostal4.test(cp1) ){ if( returnBothResults === true ){ return [true,false]; } else { return true; } } var cPostal = cp1.match(parserCPostal); if(cPostal!==null && cPostal4.test(cPostal[1]) && cPostalSep.test(cPostal[2]) && cPostal3.test(cPostal[3])){ if( returnBothResults === true ){ return [true,false]; } else { return true; } } } if( returnBothResults === true ){ return [false,false]; } else { return false; } }, /** * Checks is a date is valid in a given format * * @method isDate * @param {String} format - defined in _dateParsers * @param {String} dateStr - date string * @return {Boolean} True if it's a valid date and in the specified format * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isDate( 'yyyy-mm-dd', '2012-05-21' ) ); // Result: true * }); */ isDate: function(format, dateStr){ if(typeof(this._dateParsers[format])==='undefined'){ return false; } var yearIndex = this._dateParsers[format].year; var monthIndex = this._dateParsers[format].month; var dayIndex = this._dateParsers[format].day; var dateParser = this._dateParsers[format].parser; var separator = this._dateParsers[format].sep; /* Trim Deactivated * var trim = /^\w+|\w+$/g; * dateStr = dateStr.replace(trim,""); */ var data = dateStr.match(dateParser); if(data!==null){ /* Trim Deactivated * for(i=1;i<=data.length;i++){ * data[i] = data[i].replace(trim,""); *} */ if(data[2]===data[4] && data[2]===separator){ var _y = ((data[yearIndex].length===2) ? "20" + data[yearIndex].toString() : data[yearIndex] ); if(this._isValidDate(_y,data[monthIndex].toString(),data[dayIndex].toString())){ return true; } } } return false; }, /** * Checks if a string is a valid color * * @method isColor * @param {String} str Color string to be checked * @return {Boolean} True if it's a valid color string * @public * @static * @example * Ink.requireModules(['Ink.Util.Validator_1'], function( InkValidator ){ * console.log( InkValidator.isColor( '#FF00FF' ) ); // Result: true * console.log( InkValidator.isColor( 'amdafasfs' ) ); // Result: false * }); */ isColor: function(str){ var match, valid = false, keyword = /^[a-zA-Z]+$/, hexa = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, rgb = /^rgb\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/, rgba = /^rgba\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/, hsl = /^hsl\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/, hsla = /^hsla\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/; // rgb(123, 123, 132) 0 to 255 // rgb(123%, 123%, 123%) 0 to 100 // rgba( 4 vals) last val: 0 to 1.0 // hsl(0 to 360, %, %) // hsla( ..., 0 to 1.0) if( keyword.test(str) || hexa.test(str) ){ return true; } var i; // rgb range check if((match = rgb.exec(str)) !== null || (match = rgba.exec(str)) !== null){ i = match.length; while(i--){ // check percentage values if((i===2 || i===4 || i===6) && typeof match[i] !== "undefined" && match[i] !== ""){ if(typeof match[i-1] !== "undefined" && match[i-1] >= 0 && match[i-1] <= 100){ valid = true; } else { return false; } } // check 0 to 255 values if(i===1 || i===3 || i===5 && (typeof match[i+1] === "undefined" || match[i+1] === "")){ if(typeof match[i] !== "undefined" && match[i] >= 0 && match[i] <= 255){ valid = true; } else { return false; } } } } // hsl range check if((match = hsl.exec(str)) !== null || (match = hsla.exec(str)) !== null){ i = match.length; while(i--){ // check percentage values if(i===3 || i===5){ if(typeof match[i-1] !== "undefined" && typeof match[i] !== "undefined" && match[i] !== "" && match[i-1] >= 0 && match[i-1] <= 100){ valid = true; } else { return false; } } // check 0 to 360 value if(i===1){ if(typeof match[i] !== "undefined" && match[i] >= 0 && match[i] <= 360){ valid = true; } else { return false; } } } } return valid; }, /** * Checks if the value is a valid IP. Supports ipv4 and ipv6 * * @method validationFunctions.ip * @param {String} value Value to be checked * @param {String} ipType Type of IP to be validated. The values are: ipv4, ipv6. By default is ipv4. * @return {Boolean} True if the value is a valid IP address. False if not. */ isIP: function( value, ipType ){ if( typeof value !== 'string' ){ return false; } ipType = (ipType || 'ipv4').toLowerCase(); switch( ipType ){ case 'ipv4': return (/^(?:(?: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]?)$/).test(value); case 'ipv6': return (/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/).test(value); default: return false; } }, /** * Credit Card specifications, to be used in the credit card verification. * * @property _creditCardSpecs * @type {Object} * @private */ _creditCardSpecs: { 'default': { 'length': '13,14,15,16,17,18,19', 'prefix': /^.+/, 'luhn': true }, 'american express': { 'length': '15', 'prefix': /^3[47]/, 'luhn' : true }, 'diners club': { 'length': '14,16', 'prefix': /^36|55|30[0-5]/, 'luhn' : true }, 'discover': { 'length': '16', 'prefix': /^6(?:5|011)/, 'luhn' : true }, 'jcb': { 'length': '15,16', 'prefix': /^3|1800|2131/, 'luhn' : true }, 'maestro': { 'length': '16,18', 'prefix': /^50(?:20|38)|6(?:304|759)/, 'luhn' : true }, 'mastercard': { 'length': '16', 'prefix': /^5[1-5]/, 'luhn' : true }, 'visa': { 'length': '13,16', 'prefix': /^4/, 'luhn' : true } }, /** * Luhn function, to be used when validating credit cards * */ _luhn: function (num){ num = parseInt(num,10); if ( (typeof num !== 'number') && (num % 1 !== 0) ){ // Luhn can only be used on nums! return false; } num = num+''; // Check num length var length = num.length; // Checksum of the card num var i, checksum = 0 ; for (i = length - 1; i >= 0; i -= 2) { // Add up every 2nd digit, starting from the right checksum += parseInt(num.substr(i, 1),10); } for (i = length - 2; i >= 0; i -= 2) { // Add up every 2nd digit doubled, starting from the right var dbl = parseInt(num.substr(i, 1) * 2,10); // Subtract 9 from the dbl where value is greater than 10 checksum += (dbl >= 10) ? (dbl - 9) : dbl; } // If the checksum is a multiple of 10, the number is valid return (checksum % 10 === 0); }, /** * Validates if a number is of a specific credit card * * @param {String} num Number to be validates * @param {String|Array} creditCardType Credit card type. See _creditCardSpecs for the list of supported values. * @return {Boolean} */ isCreditCard: function(num, creditCardType){ if ( /\d+/.test(num) === false ){ return false; } if ( typeof creditCardType === 'undefined' ){ creditCardType = 'default'; } else if ( typeof creditCardType === 'array' ){ var i, ccLength = creditCardType.length; for ( i=0; i < ccLength; i++ ){ // Test each type for validity if (this.isCreditCard(num, creditCardType[i]) ){ return true; } } return false; } // Check card type creditCardType = creditCardType.toLowerCase(); if ( typeof this._creditCardSpecs[creditCardType] === 'undefined' ){ return false; } // Check card number length var length = num.length+''; // Validate the card length by the card type if ( this._creditCardSpecs[creditCardType]['length'].split(",").indexOf(length) === -1 ){ return false; } // Check card number prefix if ( !this._creditCardSpecs[creditCardType]['prefix'].test(num) ){ return false; } // No Luhn check required if (this._creditCardSpecs[creditCardType]['luhn'] === false){ return true; } return this._luhn(num); } }; return Validator; }); /** * @module Ink.UI.Aux_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Aux', '1', ['Ink.Net.Ajax_1','Ink.Dom.Css_1','Ink.Dom.Selector_1','Ink.Util.Url_1'], function(Ajax,Css,Selector,Url) { 'use strict'; var instances = {}; var lastIdNum = 0; /** * The Aux class provides auxiliar methods to ease some of the most common/repetitive UI tasks. * * @class Ink.UI.Aux * @version 1 * @static */ var Aux = { /** * Supported Ink Layouts * * @property Layouts * @type Object * @readOnly */ Layouts: { SMALL: 'small', MEDIUM: 'medium', LARGE: 'large' }, /** * Method to check if an item is a valid DOM Element. * * @method isDOMElement * @static * @param {Mixed} o The object to be checked. * @return {Boolean} True if it's a valid DOM Element. * @example * var el = Ink.s('#element'); * if( Ink.UI.Aux.isDOMElement( el ) === true ){ * // It is a DOM Element. * } else { * // It is NOT a DOM Element. * } */ isDOMElement: function(o) { return (typeof o === 'object' && 'nodeType' in o && o.nodeType === 1); }, /** * Method to check if an item is a valid integer. * * @method isInteger * @static * @param {Mixed} n The value to be checked. * @return {Boolean} True if 'n' is a valid integer. * @example * var value = 1; * if( Ink.UI.Aux.isInteger( value ) === true ){ * // It is an integer. * } else { * // It is NOT an integer. * } */ isInteger: function(n) { return (typeof n === 'number' && n % 1 === 0); }, /** * Method to get a DOM Element. The first parameter should be either a DOM Element or a valid CSS Selector. * If not, then it will throw an exception. Otherwise, it returns a DOM Element. * * @method elOrSelector * @static * @param {DOMElement|String} elOrSelector Valid DOM Element or CSS Selector * @param {String} fieldName This field is used in the thrown Exception to identify the parameter. * @return {DOMElement} Returns the DOMElement passed or the first result of the CSS Selector. Otherwise it throws an exception. * @example * // In case there are several .myInput, it will retrieve the first found * var el = Ink.UI.Aux.elOrSelector('.myInput','My Input'); */ elOrSelector: function(elOrSelector, fieldName) { if (!this.isDOMElement(elOrSelector)) { var t = Selector.select(elOrSelector); if (t.length === 0) { throw new TypeError(fieldName + ' must either be a DOM Element or a selector expression!\nThe script element must also be after the DOM Element itself.'); } return t[0]; } return elOrSelector; }, /** * Method to make a deep copy (clone) of an object. * Note: The object cannot have loops. * * @method clone * @static * @param {Object} o The object to be cloned/copied. * @return {Object} Returns the result of the clone/copy. * @example * var originalObj = { * key1: 'value1', * key2: 'value2', * key3: 'value3' * }; * var cloneObj = Ink.UI.Aux.clone( originalObj ); */ clone: function(o) { try { if (typeof o !== 'object') { throw new Error('Given argument is not an object!'); } return JSON.parse( JSON.stringify(o) ); } catch (ex) { throw new Error('Given object cannot have loops!'); } }, /** * Method to return the 'nth' position that an element occupies relatively to its parent. * * @method childIndex * @static * @param {DOMElement} childEl Valid DOM Element. * @return {Number} Numerical position of an element relatively to its parent. * @example * <!-- Imagine the following HTML: --> * <ul> * <li>One</li> * <li>Two</li> * <li id="test">Three</li> * <li>Four</li> * </ul> * * <script> * var testLi = Ink.s('#test'); * Ink.UI.Aux.childIndex( testLi ); // Returned value: 3 * </script> */ childIndex: function(childEl) { if( Aux.isDOMElement(childEl) ){ var els = Selector.select('> *', childEl.parentNode); for (var i = 0, f = els.length; i < f; ++i) { if (els[i] === childEl) { return i; } } } throw 'not found!'; }, /** * This method provides a more convenient way to do an async AJAX request and expect a JSON response. * It offers a callback option, as third paramenter, for a better async handling. * * @method ajaxJSON * @static * @async * @param {String} endpoint Valid URL to be used as target by the request. * @param {Object} params This field is used in the thrown Exception to identify the parameter. * @example * // In case there are several .myInput, it will retrieve the first found * var el = Ink.UI.Aux.elOrSelector('.myInput','My Input'); */ ajaxJSON: function(endpoint, params, cb) { new Ajax( endpoint, { evalJS: 'force', method: 'POST', parameters: params, onSuccess: function( r) { try { r = r.responseJSON; if (r.status !== 'ok') { throw 'server error: ' + r.message; } cb(null, r); } catch (ex) { cb(ex); } }, onFailure: function() { cb('communication failure'); } } ); }, /** * Method to get the current Ink layout applied. * * @method currentLayout * @static * @return {String} Returns the value of one of the options of the property Layouts above defined. * @example * var inkLayout = Ink.UI.Aux.currentLayout(); */ currentLayout: function() { var i, f, k, v, el, detectorEl = Selector.select('#ink-layout-detector')[0]; if (!detectorEl) { detectorEl = document.createElement('div'); detectorEl.id = 'ink-layout-detector'; for (k in this.Layouts) { if (this.Layouts.hasOwnProperty(k)) { v = this.Layouts[k]; el = document.createElement('div'); el.className = 'show-' + v + ' hide-all'; el.setAttribute('data-ink-layout', v); detectorEl.appendChild(el); } } document.body.appendChild(detectorEl); } for (i = 0, f = detectorEl.childNodes.length; i < f; ++i) { el = detectorEl.childNodes[i]; if (Css.getStyle(el, 'visibility') !== 'hidden') { return el.getAttribute('data-ink-layout'); } } }, /** * Method to set the location's hash (window.location.hash). * * @method hashSet * @static * @param {Object} o Object with the info to be placed in the location's hash. * @example * // It will set the location's hash like: <url>#key1=value1&key2=value2&key3=value3 * Ink.UI.Aux.hashSet({ * key1: 'value1', * key2: 'value2', * key3: 'value3' * }); */ hashSet: function(o) { if (typeof o !== 'object') { throw new TypeError('o should be an object!'); } var hashParams = Url.getAnchorString(); hashParams = Ink.extendObj(hashParams, o); window.location.hash = Url.genQueryString('', hashParams).substring(1); }, /** * Method to remove children nodes from a given object. * This method was initially created to help solve a problem in Internet Explorer(s) that occurred when trying * to set the innerHTML of some specific elements like 'table'. * * @method cleanChildren * @static * @param {DOMElement} parentEl Valid DOM Element * @example * <!-- Imagine the following HTML: --> * <ul id="myUl"> * <li>One</li> * <li>Two</li> * <li>Three</li> * <li>Four</li> * </ul> * * <script> * Ink.UI.Aux.cleanChildren( Ink.s( '#myUl' ) ); * </script> * * <!-- After running it, the HTML changes to: --> * <ul id="myUl"></ul> */ cleanChildren: function(parentEl) { if( !Aux.isDOMElement(parentEl) ){ throw 'Please provide a valid DOMElement'; } var prevEl, el = parentEl.lastChild; while (el) { prevEl = el.previousSibling; parentEl.removeChild(el); el = prevEl; } }, /** * This method stores the id and/or the classes of a given element in a given object. * * @method storeIdAndClasses * @static * @param {DOMElement} fromEl Valid DOM Element to get the id and classes from. * @param {Object} inObj Object where the id and classes will be saved. * @example * <div id="myDiv" class="aClass"></div> * * <script> * var storageObj = {}; * Ink.UI.Aux.storeIdAndClasses( Ink.s('#myDiv'), storageObj ); * // storageObj changes to: * { * _id: 'myDiv', * _classes: 'aClass' * } * </script> */ storeIdAndClasses: function(fromEl, inObj) { if( !Aux.isDOMElement(fromEl) ){ throw 'Please provide a valid DOMElement as first parameter'; } var id = fromEl.id; if (id) { inObj._id = id; } var classes = fromEl.className; if (classes) { inObj._classes = classes; } }, /** * This method sets the id and className properties of a given DOM Element based on a given similar object * resultant of the previous function 'storeIdAndClasses'. * * @method restoreIdAndClasses * @static * @param {DOMElement} toEl Valid DOM Element to set the id and classes on. * @param {Object} inObj Object where the id and classes to be set are. * @example * <div></div> * * <script> * var storageObj = { * _id: 'myDiv', * _classes: 'aClass' * }; * * Ink.UI.Aux.storeIdAndClasses( Ink.s('div'), storageObj ); * </script> * * <!-- After the code runs the div element changes to: --> * <div id="myDiv" class="aClass"></div> */ restoreIdAndClasses: function(toEl, inObj) { if( !Aux.isDOMElement(toEl) ){ throw 'Please provide a valid DOMElement as first parameter'; } if (inObj._id && toEl.id !== inObj._id) { toEl.id = inObj._id; } if (inObj._classes && toEl.className.indexOf(inObj._classes) === -1) { if (toEl.className) { toEl.className += ' ' + inObj._classes; } else { toEl.className = inObj._classes; } } if (inObj._instanceId && !toEl.getAttribute('data-instance')) { toEl.setAttribute('data-instance', inObj._instanceId); } }, /** * This method saves a component's instance reference for later retrieval. * * @method registerInstance * @static * @param {Object} inst Object that holds the instance. * @param {DOMElement} el DOM Element to associate with the object. * @param {Object} [optionalPrefix] Defaults to 'instance' */ registerInstance: function(inst, el, optionalPrefix) { if (inst._instanceId) { return; } if (typeof inst !== 'object') { throw new TypeError('1st argument must be a JavaScript object!'); } if (inst._options && inst._options.skipRegister) { return; } if (!this.isDOMElement(el)) { throw new TypeError('2nd argument must be a DOM element!'); } if (optionalPrefix !== undefined && typeof optionalPrefix !== 'string') { throw new TypeError('3rd argument must be a string!'); } var id = (optionalPrefix || 'instance') + (++lastIdNum); instances[id] = inst; inst._instanceId = id; var dataInst = el.getAttribute('data-instance'); dataInst = (dataInst !== null) ? [dataInst, id].join(' ') : id; el.setAttribute('data-instance', dataInst); }, /** * This method deletes/destroy an instance with a given id. * * @method unregisterInstance * @static * @param {String} id Id of the instance to be destroyed. */ unregisterInstance: function(id) { delete instances[id]; }, /** * This method retrieves the registered instance(s) of a given element or instance id. * * @method getInstance * @static * @param {String|DOMElement} instanceIdOrElement Instance's id or DOM Element from which we want the instances. * @return {Object|Object[]} Returns an instance or a collection of instances. */ getInstance: function(instanceIdOrElement) { var ids; if (this.isDOMElement(instanceIdOrElement)) { ids = instanceIdOrElement.getAttribute('data-instance'); if (ids === null) { throw new Error('argument is not a DOM instance element!'); } } else { ids = instanceIdOrElement; } ids = ids.split(' '); var inst, id, i, l = ids.length; var res = []; for (i = 0; i < l; ++i) { id = ids[i]; if (!id) { throw new Error('Element is not a JS instance!'); } inst = instances[id]; if (!inst) { throw new Error('Instance "' + id + '" not found!'); } res.push(inst); } return (l === 1) ? res[0] : res; }, /** * This method retrieves the registered instance(s) of an element based on the given selector. * * @method getInstanceFromSelector * @static * @param {String} selector CSS selector to define the element from which it'll get the instance(s). * @return {Object|Object[]} Returns an instance or a collection of instances. */ getInstanceFromSelector: function(selector) { var el = Selector.select(selector)[0]; if (!el) { throw new Error('Element not found!'); } return this.getInstance(el); }, /** * This method retrieves the registered instances' ids of all instances. * * @method getInstanceIds * @static * @return {String[]} Id or collection of ids of all existing instances. */ getInstanceIds: function() { var res = []; for (var id in instances) { if (instances.hasOwnProperty(id)) { res.push( id ); } } return res; }, /** * This method retrieves all existing instances. * * @method getInstances * @static * @return {Object[]} Collection of existing instances. */ getInstances: function() { var res = []; for (var id in instances) { if (instances.hasOwnProperty(id)) { res.push( instances[id] ); } } return res; }, /** * This method is not to supposed to be invoked by the Aux component. * Components should copy this method as its destroy method. * * @method destroyComponent * @static */ destroyComponent: function() { Ink.Util.Aux.unregisterInstance(this._instanceId); this._element.parentNode.removeChild(this._element); } }; return Aux; }); /** * @module Ink.UI.Pagination_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Pagination', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1'], function(Aux, Event, Css, Element, Selector ) { 'use strict'; /** * Function to create the pagination anchors * * @method genAel * @param {String} inner HTML to be placed inside the anchor. * @return {DOMElement} Anchor created */ var genAEl = function(inner, index) { var aEl = document.createElement('a'); aEl.setAttribute('href', '#'); if (index !== undefined) { aEl.setAttribute('data-index', index); } aEl.innerHTML = inner; return aEl; }; /** * @class Ink.UI.Pagination * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} options Options * @param {Number} options.size number of pages * @param {Number} [options.maxSize] if passed, only shows at most maxSize items. displays also first|prev page and next page|last buttons * @param {Number} [options.start] start page. defaults to 1 * @param {String} [options.previousLabel] label to display on previous page button * @param {String} [options.nextLabel] label to display on next page button * @param {String} [options.previousPageLabel] label to display on previous page button * @param {String} [options.nextPageLabel] label to display on next page button * @param {String} [options.firstLabel] label to display on previous page button * @param {String} [options.lastLabel] label to display on next page button * @param {Function} [options.onChange] optional callback * @param {Function} [options.numberFormatter] optional function which takes and 0-indexed number and returns the string which appears on a numbered button * @param {Boolean} [options.setHash] if true, sets hashParameter on the location.hash. default is disabled * @param {String} [options.hashParameter] parameter to use on setHash. by default uses 'page' */ var Pagination = function(selector, options) { this._element = Aux.elOrSelector(selector, '1st argument'); this._options = Ink.extendObj( { size: undefined, start: 1, firstLabel: 'First', lastLabel: 'Last', previousLabel: 'Previous', nextLabel: 'Next', onChange: undefined, setHash: false, hashParameter: 'page', numberFormatter: function(i) { return i + 1; } }, options || {}, Element.data(this._element) ); if (!this._options.previousPageLabel) { this._options.previousPageLabel = 'Previous ' + this._options.maxSize; } if (!this._options.nextPageLabel) { this._options.nextPageLabel = 'Next ' + this._options.maxSize; } this._handlers = { click: Ink.bindEvent(this._onClick,this) }; if (!Aux.isInteger(this._options.size)) { throw new TypeError('size option is a required integer!'); } if (!Aux.isInteger(this._options.start) && this._options.start > 0 && this._options.start <= this._options.size) { throw new TypeError('start option is a required integer between 1 and size!'); } if (this._options.maxSize && !Aux.isInteger(this._options.maxSize) && this._options.maxSize > 0) { throw new TypeError('maxSize option is a positive integer!'); } else if (this._options.size < 0) { throw new RangeError('size option must be equal or more than 0!'); } if (this._options.onChange !== undefined && typeof this._options.onChange !== 'function') { throw new TypeError('onChange option must be a function!'); } if (Css.hasClassName( Ink.s('ul', this._element), 'dotted')) { this._options.numberFormatter = function() { return '<i class="icon-circle"></i>'; }; } this._current = this._options.start - 1; this._itemLiEls = []; this._init(); }; Pagination.prototype = { /** * Init function called by the constructor * * @method _init * @private */ _init: function() { // generate and apply DOM this._generateMarkup(this._element); this._updateItems(); // subscribe events this._observe(); Aux.registerInstance(this, this._element, 'pagination'); }, /** * Responsible for setting listener in the 'click' event of the Pagination element. * * @method _observe * @private */ _observe: function() { Event.observe(this._element, 'click', this._handlers.click); }, /** * Updates the markup everytime there's a change in the Pagination object. * * @method _updateItems * @private */ _updateItems: function() { var liEls = this._itemLiEls; var isSimpleToggle = this._options.size === liEls.length; var i, f, liEl; if (isSimpleToggle) { // just toggle active class for (i = 0, f = this._options.size; i < f; ++i) { Css.setClassName(liEls[i], 'active', i === this._current); } } else { // remove old items for (i = liEls.length - 1; i >= 0; --i) { this._ulEl.removeChild(liEls[i]); } // add new items liEls = []; for (i = 0, f = this._options.size; i < f; ++i) { liEl = document.createElement('li'); liEl.appendChild( genAEl( this._options.numberFormatter(i), i) ); Css.setClassName(liEl, 'active', i === this._current); this._ulEl.insertBefore(liEl, this._nextEl); liEls.push(liEl); } this._itemLiEls = liEls; } if (this._options.maxSize) { // toggle visible items var page = Math.floor( this._current / this._options.maxSize ); var pi = this._options.maxSize * page; var pf = pi + this._options.maxSize - 1; for (i = 0, f = this._options.size; i < f; ++i) { liEl = liEls[i]; Css.setClassName(liEl, 'hide-all', i < pi || i > pf); } this._pageStart = pi; this._pageEnd = pf; this._page = page; Css.setClassName(this._prevPageEl, 'disabled', !this.hasPreviousPage()); Css.setClassName(this._nextPageEl, 'disabled', !this.hasNextPage()); Css.setClassName(this._firstEl, 'disabled', this.isFirst()); Css.setClassName(this._lastEl, 'disabled', this.isLast()); } // update prev and next Css.setClassName(this._prevEl, 'disabled', !this.hasPrevious()); Css.setClassName(this._nextEl, 'disabled', !this.hasNext()); }, /** * Returns the top element for the gallery DOM representation * * @method _generateMarkup * @param {DOMElement} el * @private */ _generateMarkup: function(el) { Css.addClassName(el, 'ink-navigation'); var ulEl,liEl, hasUlAlready = false ; if( ( ulEl = Selector.select('ul.pagination',el)).length < 1 ){ ulEl = document.createElement('ul'); Css.addClassName(ulEl, 'pagination'); } else { hasUlAlready = true; ulEl = ulEl[0]; } if (this._options.maxSize) { liEl = document.createElement('li'); liEl.appendChild( genAEl(this._options.firstLabel) ); this._firstEl = liEl; Css.addClassName(liEl, 'first'); ulEl.appendChild(liEl); liEl = document.createElement('li'); liEl.appendChild( genAEl(this._options.previousPageLabel) ); this._prevPageEl = liEl; Css.addClassName(liEl, 'previousPage'); ulEl.appendChild(liEl); } liEl = document.createElement('li'); liEl.appendChild( genAEl(this._options.previousLabel) ); this._prevEl = liEl; Css.addClassName(liEl, 'previous'); ulEl.appendChild(liEl); liEl = document.createElement('li'); liEl.appendChild( genAEl(this._options.nextLabel) ); this._nextEl = liEl; Css.addClassName(liEl, 'next'); ulEl.appendChild(liEl); if (this._options.maxSize) { liEl = document.createElement('li'); liEl.appendChild( genAEl(this._options.nextPageLabel) ); this._nextPageEl = liEl; Css.addClassName(liEl, 'nextPage'); ulEl.appendChild(liEl); liEl = document.createElement('li'); liEl.appendChild( genAEl(this._options.lastLabel) ); this._lastEl = liEl; Css.addClassName(liEl, 'last'); ulEl.appendChild(liEl); } if( !hasUlAlready ){ el.appendChild(ulEl); } this._ulEl = ulEl; }, /** * Click handler * * @method _onClick * @param {Event} ev * @private */ _onClick: function(ev) { Event.stop(ev); var tgtEl = Event.element(ev); if (tgtEl.nodeName.toLowerCase() !== 'a') { do{ tgtEl = tgtEl.parentNode; }while( (tgtEl.nodeName.toLowerCase() !== 'a') && (tgtEl !== this._element) ); if( tgtEl === this._element){ return; } } var liEl = tgtEl.parentNode; if (liEl.nodeName.toLowerCase() !== 'li') { return; } if ( Css.hasClassName(liEl, 'active') || Css.hasClassName(liEl, 'disabled') ) { return; } var isPrev = Css.hasClassName(liEl, 'previous'); var isNext = Css.hasClassName(liEl, 'next'); var isPrevPage = Css.hasClassName(liEl, 'previousPage'); var isNextPage = Css.hasClassName(liEl, 'nextPage'); var isFirst = Css.hasClassName(liEl, 'first'); var isLast = Css.hasClassName(liEl, 'last'); if (isFirst) { this.setCurrent(0); } else if (isLast) { this.setCurrent(this._options.size - 1); } else if (isPrevPage || isNextPage) { this.setCurrent( (isPrevPage ? -1 : 1) * this._options.maxSize, true); } else if (isPrev || isNext) { this.setCurrent(isPrev ? -1 : 1, true); } else { var nr = parseInt( tgtEl.getAttribute('data-index'), 10); this.setCurrent(nr); } }, /************** * PUBLIC API * **************/ /** * Sets the number of pages * * @method setSize * @param {Number} sz number of pages * @public */ setSize: function(sz) { if (!Aux.isInteger(sz)) { throw new TypeError('1st argument must be an integer number!'); } this._options.size = sz; this._updateItems(); this._current = 0; }, /** * Sets the current page * * @method setCurrent * @param {Number} nr sets the current page to given number * @param {Boolean} isRelative trueish to set relative change instead of absolute (default) * @public */ setCurrent: function(nr, isRelative) { if (!Aux.isInteger(nr)) { throw new TypeError('1st argument must be an integer number!'); } if (isRelative) { nr += this._current; } if (nr < 0) { nr = 0; } else if (nr > this._options.size - 1) { nr = this._options.size - 1; } this._current = nr; this._updateItems(); /*if (this._options.setHash) { var o = {}; o[this._options.hashParameter] = nr; Aux.setHash(o); }*/ if (this._options.onChange) { this._options.onChange(this); } }, /** * Returns the number of pages * * @method getSize * @return {Number} Number of pages * @public */ getSize: function() { return this._options.size; }, /** * Returns current page * * @method getCurrent * @return {Number} Current page * @public */ getCurrent: function() { return this._current; }, /** * Returns true iif at first page * * @method isFirst * @return {Boolean} True if at first page * @public */ isFirst: function() { return this._current === 0; }, /** * Returns true iif at last page * * @method isLast * @return {Boolean} True if at last page * @public */ isLast: function() { return this._current === this._options.size - 1; }, /** * Returns true iif has prior pages * * @method hasPrevious * @return {Boolean} True if has prior pages * @public */ hasPrevious: function() { return this._current > 0; }, /** * Returns true iif has pages ahead * * @method hasNext * @return {Boolean} True if has pages ahead * @public */ hasNext: function() { return this._current < this._options.size - 1; }, /** * Returns true iif has prior set of page(s) * * @method hasPreviousPage * @return {Boolean} Returns true iif has prior set of page(s) * @public */ hasPreviousPage: function() { return this._options.maxSize && this._current > this._options.maxSize - 1; }, /** * Returns true iif has set of page(s) ahead * * @method hasNextPage * @return {Boolean} Returns true iif has set of page(s) ahead * @public */ hasNextPage: function() { return this._options.maxSize && this._options.size - this._current >= this._options.maxSize + 1; }, /** * Unregisters the component and removes its markup from the DOM * * @method destroy * @public */ destroy: Aux.destroyComponent }; return Pagination; }); /** * @module Ink.UI.SortableList_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.SortableList', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) { 'use strict'; /** * Adds sortable behaviour to any list! * * @class Ink.UI.SortableList * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {String} [options.dragObject] CSS Selector. The element that will trigger the dragging in the list. Default is 'li'. * @example * <ul class="unstyled ink-sortable-list" id="slist" data-instance="sortableList9"> * <li><span class="ink-label info"><i class="icon-reorder"></i>drag here</span>primeiro</li> * <li><span class="ink-label info"><i class="icon-reorder"></i>drag here</span>segundo</li> * <li><span class="ink-label info"><i class="icon-reorder"></i>drag here</span>terceiro</li> * </ul> * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.SortableList_1'], function( Selector, SortableList ){ * var sortableListElement = Ink.s('.ink-sortable-list'); * var sortableListObj = new SortableList( sortableListElement ); * }); * </script> */ var SortableList = function(selector, options) { this._element = Aux.elOrSelector(selector, '1st argument'); if( !Aux.isDOMElement(selector) && (typeof selector !== 'string') ){ throw '[Ink.UI.SortableList] :: Invalid selector'; } else if( typeof selector === 'string' ){ this._element = Ink.Dom.Selector.select( selector ); if( this._element.length < 1 ){ throw '[Ink.UI.SortableList] :: Selector has returned no elements'; } this._element = this._element[0]; } else { this._element = selector; } this._options = Ink.extendObj({ dragObject: 'li' }, Ink.Dom.Element.data(this._element)); this._options = Ink.extendObj( this._options, options || {}); this._handlers = { down: Ink.bindEvent(this._onDown,this), move: Ink.bindEvent(this._onMove,this), up: Ink.bindEvent(this._onUp,this) }; this._model = []; this._index = undefined; this._isMoving = false; if (this._options.model instanceof Array) { this._model = this._options.model; this._createdFrom = 'JSON'; } else if (this._element.nodeName.toLowerCase() === 'ul') { this._createdFrom = 'DOM'; } else { throw new TypeError('You must pass a selector expression/DOM element as 1st option or provide a model on 2nd argument!'); } this._dragTriggers = Selector.select( this._options.dragObject, this._element ); if( !this._dragTriggers ){ throw "[Ink.UI.SortableList] :: Drag object not found"; } this._init(); }; SortableList.prototype = { /** * Init function called by the constructor. * * @method _init * @private */ _init: function() { // extract model if (this._createdFrom === 'DOM') { this._extractModelFromDOM(); this._createdFrom = 'JSON'; } var isTouch = 'ontouchstart' in document.documentElement; this._down = isTouch ? 'touchstart': 'mousedown'; this._move = isTouch ? 'touchmove' : 'mousemove'; this._up = isTouch ? 'touchend' : 'mouseup'; // subscribe events var db = document.body; Event.observe(db, this._move, this._handlers.move); Event.observe(db, this._up, this._handlers.up); this._observe(); Aux.registerInstance(this, this._element, 'sortableList'); }, /** * Sets the event handlers. * * @method _observe * @private */ _observe: function() { Event.observe(this._element, this._down, this._handlers.down); }, /** * Updates the model from the UL representation * * @method _extractModelFromDOM * @private */ _extractModelFromDOM: function() { this._model = []; var that = this; var liEls = Selector.select('> li', this._element); InkArray.each(liEls,function(liEl) { //var t = Element.getChildrenText(liEl); var t = liEl.innerHTML; that._model.push(t); }); }, /** * Returns the top element for the gallery DOM representation * * @method _generateMarkup * @return {DOMElement} * @private */ _generateMarkup: function() { var el = document.createElement('ul'); el.className = 'unstyled ink-sortable-list'; var that = this; InkArray.each(this._model,function(label, idx) { var liEl = document.createElement('li'); if (idx === that._index) { liEl.className = 'drag'; } liEl.innerHTML = [ // '<span class="ink-label ink-info"><i class="icon-reorder"></i>', that._options.dragLabel, '</span>', label label ].join(''); el.appendChild(liEl); }); return el; }, /** * Extracts the Y coordinate of the mouse from the given MouseEvent * * @method _getY * @param {Event} ev * @return {Number} * @private */ _getY: function(ev) { if (ev.type.indexOf('touch') === 0) { //console.log(ev.type, ev.changedTouches[0].pageY); return ev.changedTouches[0].pageY; } if (typeof ev.pageY === 'number') { return ev.pageY; } return ev.clientY; }, /** * Refreshes the markup. * * @method _refresh * @param {Boolean} skipObs True if needs to set the event handlers, false if not. * @private */ _refresh: function(skipObs) { var el = this._generateMarkup(); this._element.parentNode.replaceChild(el, this._element); this._element = el; Aux.restoreIdAndClasses(this._element, this); this._dragTriggers = Selector.select( this._options.dragObject, this._element ); // subscribe events if (!skipObs) { this._observe(); } }, /** * Mouse down handler * * @method _onDown * @param {Event} ev * @return {Boolean|undefined} [description] * @private */ _onDown: function(ev) { if (this._isMoving) { return; } var tgtEl = Event.element(ev); if( !InkArray.inArray(tgtEl,this._dragTriggers) ){ while( !InkArray.inArray(tgtEl,this._dragTriggers) && (tgtEl.nodeName.toLowerCase() !== 'body') ){ tgtEl = tgtEl.parentNode; } if( tgtEl.nodeName.toLowerCase() === 'body' ){ return; } } Event.stop(ev); var liEl; if( tgtEl.nodeName.toLowerCase() !== 'li' ){ while( (tgtEl.nodeName.toLowerCase() !== 'li') && (tgtEl.nodeName.toLowerCase() !== 'body') ){ tgtEl = tgtEl.parentNode; } } liEl = tgtEl; this._index = Aux.childIndex(liEl); this._height = liEl.offsetHeight; this._startY = this._getY(ev); this._isMoving = true; document.body.style.cursor = 'move'; this._refresh(false); return false; }, /** * Mouse move handler * * @method _onMove * @param {Event} ev * @private */ _onMove: function(ev) { if (!this._isMoving) { return; } Event.stop(ev); var y = this._getY(ev); //console.log(y); var dy = y - this._startY; var sign = dy > 0 ? 1 : -1; var di = sign * Math.floor( Math.abs(dy) / this._height ); if (di === 0) { return; } di = di / Math.abs(di); if ( (di === -1 && this._index === 0) || (di === 1 && this._index === this._model.length - 1) ) { return; } var a = di > 0 ? this._index : this._index + di; var b = di < 0 ? this._index : this._index + di; //console.log(a, b); this._model.splice(a, 2, this._model[b], this._model[a]); this._index += di; this._startY = y; this._refresh(false); }, /** * Mouse up handler * * @method _onUp * @param {Event} ev * @private */ _onUp: function(ev) { if (!this._isMoving) { return; } Event.stop(ev); this._index = undefined; this._isMoving = false; document.body.style.cursor = ''; this._refresh(); }, /************** * PUBLIC API * **************/ /** * Returns a copy of the model * * @method getModel * @return {Array} Copy of the model * @public */ getModel: function() { return this._model.slice(); }, /** * Unregisters the component and removes its markup from the DOM * * @method destroy * @public */ destroy: Aux.destroyComponent }; return SortableList; }); /** * @module Ink.UI.Spy_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Spy', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) { 'use strict'; /** * Spy is a component that 'spies' an element (or a group of elements) and when they leave the viewport (through the top), * highlight an option - related to that element being spied - that resides in a menu, initially identified as target. * * @class Ink.UI.Spy * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {DOMElement|String} options.target Target menu on where the spy will highlight the right option. * @example * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Spy_1'], function( Selector, Spy ){ * var menuElement = Ink.s('#menu'); * var specialAnchorToSpy = Ink.s('#specialAnchor'); * var spyObj = new Spy( specialAnchorToSpy, { * target: menuElement * }); * }); * </script> */ var Spy = function( selector, options ){ this._rootElement = Aux.elOrSelector(selector,'1st argument'); /** * Setting default options and - if needed - overriding it with the data attributes */ this._options = Ink.extendObj({ target: undefined }, Element.data( this._rootElement ) ); /** * In case options have been defined when creating the instance, they've precedence */ this._options = Ink.extendObj(this._options,options || {}); this._options.target = Aux.elOrSelector( this._options.target, 'Target' ); this._scrollTimeout = null; this._init(); }; Spy.prototype = { /** * Stores the spy elements * * @property _elements * @type {Array} * @readOnly * */ _elements: [], /** * Init function called by the constructor * * @method _init * @private */ _init: function(){ Event.observe( document, 'scroll', Ink.bindEvent(this._onScroll,this) ); this._elements.push(this._rootElement); }, /** * Scroll handler. Responsible for highlighting the right options of the target menu. * * @method _onScroll * @private */ _onScroll: function(){ var scrollHeight = Element.scrollHeight(); if( (scrollHeight < this._rootElement.offsetTop) ){ return; } else { for( var i = 0, total = this._elements.length; i < total; i++ ){ if( (this._elements[i].offsetTop <= scrollHeight) && (this._elements[i] !== this._rootElement) && (this._elements[i].offsetTop > this._rootElement.offsetTop) ){ return; } } } InkArray.each( Selector.select( 'a', this._options.target ), Ink.bind(function(item){ var comparisonValue = ( ("name" in this._rootElement) && this._rootElement.name ? '#' + this._rootElement.name : '#' + this._rootElement.id ); if( item.href.substr(item.href.indexOf('#')) === comparisonValue ){ Css.addClassName(Element.findUpwardsByTag(item,'li'),'active'); } else { Css.removeClassName(Element.findUpwardsByTag(item,'li'),'active'); } },this) ); } }; return Spy; }); /** * @module Ink.UI.Sticky_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Sticky', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1'], function(Aux, Event, Css, Element, Selector ) { 'use strict'; /** * The Sticky component takes an element and transforms it's behavior in order to, when the user scrolls he sets its position * to fixed and maintain it until the user scrolls back to the same place. * * @class Ink.UI.Sticky * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {Number} options.offsetBottom Number of pixels of distance from the bottomElement. * @param {Number} options.offsetTop Number of pixels of distance from the topElement. * @param {String} options.topElement CSS Selector that specifies a top element with which the component could collide. * @param {String} options.bottomElement CSS Selector that specifies a bottom element with which the component could collide. * @example * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Sticky_1'], function( Selector, Sticky ){ * var menuElement = Ink.s('#menu'); * var stickyObj = new Sticky( menuElement ); * }); * </script> */ var Sticky = function( selector, options ){ if( typeof selector !== 'object' && typeof selector !== 'string'){ throw '[Sticky] :: Invalid selector defined'; } if( typeof selector === 'object' ){ this._rootElement = selector; } else { this._rootElement = Selector.select( selector ); if( this._rootElement.length <= 0) { throw "[Sticky] :: Can't find any element with the specified selector"; } this._rootElement = this._rootElement[0]; } /** * Setting default options and - if needed - overriding it with the data attributes */ this._options = Ink.extendObj({ offsetBottom: 0, offsetTop: 0, topElement: undefined, bottomElement: undefined }, Element.data( this._rootElement ) ); /** * In case options have been defined when creating the instance, they've precedence */ this._options = Ink.extendObj(this._options,options || {}); if( typeof( this._options.topElement ) !== 'undefined' ){ this._options.topElement = Aux.elOrSelector( this._options.topElement, 'Top Element'); } else { this._options.topElement = Aux.elOrSelector( 'body', 'Top Element'); } if( typeof( this._options.bottomElement ) !== 'undefined' ){ this._options.bottomElement = Aux.elOrSelector( this._options.bottomElement, 'Bottom Element'); } else { this._options.bottomElement = Aux.elOrSelector( 'body', 'Top Element'); } this._computedStyle = window.getComputedStyle ? window.getComputedStyle(this._rootElement, null) : this._rootElement.currentStyle; this._dims = { height: this._computedStyle.height, width: this._computedStyle.width }; this._init(); }; Sticky.prototype = { /** * Init function called by the constructor * * @method _init * @private */ _init: function(){ Event.observe( document, 'scroll', Ink.bindEvent(this._onScroll,this) ); Event.observe( window, 'resize', Ink.bindEvent(this._onResize,this) ); this._calculateOriginalSizes(); this._calculateOffsets(); }, /** * Scroll handler. * * @method _onScroll * @private */ _onScroll: function(){ var viewport = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body; if( ( ( (Element.elementWidth(this._rootElement)*100)/viewport.clientWidth ) > 90 ) || ( viewport.clientWidth<=649 ) ){ if( Element.hasAttribute(this._rootElement,'style') ){ this._rootElement.removeAttribute('style'); } return; } if( this._scrollTimeout ){ clearTimeout(this._scrollTimeout); } this._scrollTimeout = setTimeout(Ink.bind(function(){ var scrollHeight = Element.scrollHeight(); if( Element.hasAttribute(this._rootElement,'style') ){ if( scrollHeight <= (this._options.originalTop-this._options.originalOffsetTop)){ this._rootElement.removeAttribute('style'); } else if( ((document.body.scrollHeight-(scrollHeight+parseInt(this._dims.height,10))) < this._options.offsetBottom) ){ this._rootElement.style.position = 'fixed'; this._rootElement.style.top = 'auto'; this._rootElement.style.left = this._options.originalLeft + 'px'; if( this._options.offsetBottom < parseInt(document.body.scrollHeight - (document.documentElement.clientHeight+scrollHeight),10) ){ this._rootElement.style.bottom = this._options.originalOffsetBottom + 'px'; } else { this._rootElement.style.bottom = this._options.offsetBottom - parseInt(document.body.scrollHeight - (document.documentElement.clientHeight+scrollHeight),10) + 'px'; } this._rootElement.style.width = this._options.originalWidth + 'px'; } else if( ((document.body.scrollHeight-(scrollHeight+parseInt(this._dims.height,10))) >= this._options.offsetBottom) ){ this._rootElement.style.left = this._options.originalLeft + 'px'; this._rootElement.style.position = 'fixed'; this._rootElement.style.bottom = 'auto'; this._rootElement.style.left = this._options.originalLeft + 'px'; this._rootElement.style.top = this._options.originalOffsetTop + 'px'; this._rootElement.style.width = this._options.originalWidth + 'px'; } } else { if( scrollHeight <= (this._options.originalTop-this._options.originalOffsetTop)){ return; } this._rootElement.style.left = this._options.originalLeft + 'px'; this._rootElement.style.position = 'fixed'; this._rootElement.style.bottom = 'auto'; this._rootElement.style.left = this._options.originalLeft + 'px'; this._rootElement.style.top = this._options.originalOffsetTop + 'px'; this._rootElement.style.width = this._options.originalWidth + 'px'; } this._scrollTimeout = undefined; },this), 0); }, /** * Resize handler * * @method _onResize * @private */ _onResize: function(){ if( this._resizeTimeout ){ clearTimeout(this._resizeTimeout); } this._resizeTimeout = setTimeout(Ink.bind(function(){ this._rootElement.removeAttribute('style'); this._calculateOriginalSizes(); this._calculateOffsets(); }, this),0); }, /** * On each resizing (and in the beginning) the component recalculates the offsets, since * the top and bottom element heights might have changed. * * @method _calculateOffsets * @private */ _calculateOffsets: function(){ /** * Calculating the offset top */ if( typeof this._options.topElement !== 'undefined' ){ if( this._options.topElement.nodeName.toLowerCase() !== 'body' ){ var topElementHeight = Element.elementHeight( this._options.topElement ), topElementTop = Element.elementTop( this._options.topElement ) ; this._options.offsetTop = ( parseInt(topElementHeight,10) + parseInt(topElementTop,10) ) + parseInt(this._options.originalOffsetTop,10); } else { this._options.offsetTop = parseInt(this._options.originalOffsetTop,10); } } /** * Calculating the offset bottom */ if( typeof this._options.bottomElement !== 'undefined' ){ if( this._options.bottomElement.nodeName.toLowerCase() !== 'body' ){ var bottomElementHeight = Element.elementHeight(this._options.bottomElement) ; this._options.offsetBottom = parseInt(bottomElementHeight,10) + parseInt(this._options.originalOffsetBottom,10); } else { this._options.offsetBottom = parseInt(this._options.originalOffsetBottom,10); } } this._onScroll(); }, /** * Function to calculate the 'original size' of the element. * It's used in the begining (_init method) and when a scroll happens * * @method _calculateOriginalSizes * @private */ _calculateOriginalSizes: function(){ if( typeof this._options.originalOffsetTop === 'undefined' ){ this._options.originalOffsetTop = parseInt(this._options.offsetTop,10); this._options.originalOffsetBottom = parseInt(this._options.offsetBottom,10); } this._options.originalTop = parseInt(this._rootElement.offsetTop,10); this._options.originalLeft = parseInt(this._rootElement.offsetLeft,10); if(isNaN(this._options.originalWidth = parseInt(this._dims.width,10))) { this._options.originalWidth = 0; } this._options.originalWidth = parseInt(this._computedStyle.width,10); } }; return Sticky; }); /** * @module Ink.UI.Table_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Table', '1', ['Ink.Net.Ajax_1','Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1','Ink.Util.String_1'], function(Ajax, Aux, Event, Css, Element, Selector, InkArray, InkString ) { 'use strict'; /** * The Table component transforms the native/DOM table element into a * sortable, paginated component. * * @class Ink.UI.Table * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {Number} options.pageSize Number of rows per page. * @param {String} options.endpoint Endpoint to get the records via AJAX * @example * <table class="ink-table alternating" data-page-size="6"> * <thead> * <tr> * <th data-sortable="true" width="75%">Pepper</th> * <th data-sortable="true" width="25%">Scoville Rating</th> * </tr> * </thead> * <tbody> * <tr> * <td>Trinidad Moruga Scorpion</td> * <td>1500000</td> * </tr> * <tr> * <td>Bhut Jolokia</td> * <td>1000000</td> * </tr> * <tr> * <td>Naga Viper</td> * <td>1463700</td> * </tr> * <tr> * <td>Red Savina Habanero</td> * <td>580000</td> * </tr> * <tr> * <td>Habanero</td> * <td>350000</td> * </tr> * <tr> * <td>Scotch Bonnet</td> * <td>180000</td> * </tr> * <tr> * <td>Malagueta</td> * <td>50000</td> * </tr> * <tr> * <td>Tabasco</td> * <td>35000</td> * </tr> * <tr> * <td>Serrano Chili</td> * <td>27000</td> * </tr> * <tr> * <td>Jalapeño</td> * <td>8000</td> * </tr> * <tr> * <td>Poblano</td> * <td>1500</td> * </tr> * <tr> * <td>Peperoncino</td> * <td>500</td> * </tr> * </tbody> * </table> * <nav class="ink-navigation"><ul class="pagination"></ul></nav> * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Table_1'], function( Selector, Table ){ * var tableElement = Ink.s('.ink-table'); * var tableObj = new Table( tableElement ); * }); * </script> */ var Table = function( selector, options ){ /** * Get the root element */ this._rootElement = Aux.elOrSelector(selector, '1st argument'); if( this._rootElement.nodeName.toLowerCase() !== 'table' ){ throw '[Ink.UI.Table] :: The element is not a table'; } this._options = Ink.extendObj({ pageSize: undefined, endpoint: undefined, loadMode: 'full', allowResetSorting: false, visibleFields: undefined },Element.data(this._rootElement)); this._options = Ink.extendObj( this._options, options || {}); /** * Checking if it's in markup mode or endpoint mode */ this._markupMode = ( typeof this._options.endpoint === 'undefined' ); if( !!this._options.visibleFields ){ this._options.visibleFields = this._options.visibleFields.split(','); } /** * Initializing variables */ this._handlers = { click: Ink.bindEvent(this._onClick,this) }; this._originalFields = []; this._sortableFields = {}; this._originalData = this._data = []; this._headers = []; this._pagination = null; this._totalRows = 0; this._init(); }; Table.prototype = { /** * Init function called by the constructor * * @method _init * @private */ _init: function(){ /** * If not is in markup mode, we have to do the initial request * to get the first data and the headers */ if( !this._markupMode ){ this._getData( this._options.endpoint, true ); } else{ this._setHeadersHandlers(); /** * Getting the table's data */ InkArray.each(Selector.select('tbody tr',this._rootElement),Ink.bind(function(tr){ this._data.push(tr); },this)); this._originalData = this._data.slice(0); this._totalRows = this._data.length; /** * Set pagination if defined * */ if( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ){ /** * Applying the pagination */ this._pagination = this._rootElement.nextSibling; while(this._pagination.nodeType !== 1){ this._pagination = this._pagination.nextSibling; } if( this._pagination.nodeName.toLowerCase() !== 'nav' ){ throw '[Ink.UI.Table] :: Missing the pagination markup or is mis-positioned'; } var Pagination = Ink.getModule('Ink.UI.Pagination',1); this._pagination = new Pagination( this._pagination, { size: Math.ceil(this._totalRows/this._options.pageSize), onChange: Ink.bind(function( pagingObj ){ this._paginate( (pagingObj._current+1) ); },this) }); this._paginate(1); } } }, /** * Click handler. This will mainly handle the sorting (when you click in the headers) * * @method _onClick * @param {Event} event Event obj * @private */ _onClick: function( event ){ var tgtEl = Event.element(event), dataset = Element.data(tgtEl), index,i, paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ) ; if( (tgtEl.nodeName.toLowerCase() !== 'th') || ( !("sortable" in dataset) || (dataset.sortable.toString() !== 'true') ) ){ return; } Event.stop(event); index = -1; if( InkArray.inArray( tgtEl,this._headers ) ){ for( i=0; i<this._headers.length; i++ ){ if( this._headers[i] === tgtEl ){ index = i; break; } } } if( !this._markupMode && paginated ){ for( var prop in this._sortableFields ){ if( prop !== ('col_' + index) ){ this._sortableFields[prop] = 'none'; this._headers[prop.replace('col_','')].innerHTML = InkString.stripTags(this._headers[prop.replace('col_','')].innerHTML); } } if( this._sortableFields['col_'+index] === 'asc' ) { this._sortableFields['col_'+index] = 'desc'; this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-down"></i>'; } else { this._sortableFields['col_'+index] = 'asc'; this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-up"></i>'; } this._pagination.setCurrent(this._pagination._current); } else { if( index === -1){ return; } if( (this._sortableFields['col_'+index] === 'desc') && (this._options.allowResetSorting && (this._options.allowResetSorting.toString() === 'true')) ) { this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML); this._sortableFields['col_'+index] = 'none'; // if( !found ){ this._data = this._originalData.slice(0); // } } else { for( var prop in this._sortableFields ){ if( prop !== ('col_' + index) ){ this._sortableFields[prop] = 'none'; this._headers[prop.replace('col_','')].innerHTML = InkString.stripTags(this._headers[prop.replace('col_','')].innerHTML); } } this._sort(index); if( this._sortableFields['col_'+index] === 'asc' ) { this._data.reverse(); this._sortableFields['col_'+index] = 'desc'; this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-down"></i>'; } else { this._sortableFields['col_'+index] = 'asc'; this._headers[index].innerHTML = InkString.stripTags(this._headers[index].innerHTML) + '<i class="icon-caret-up"></i>'; } } var tbody = Selector.select('tbody',this._rootElement)[0]; Aux.cleanChildren(tbody); InkArray.each(this._data,function(item){ tbody.appendChild(item); }); this._pagination.setCurrent(0); this._paginate(1); } }, /** * Applies and/or changes the CSS classes in order to show the right columns * * @method _paginate * @param {Number} page Current page * @private */ _paginate: function( page ){ InkArray.each(this._data,Ink.bind(function(item, index){ if( (index >= ((page-1)*parseInt(this._options.pageSize,10))) && (index < (((page-1)*parseInt(this._options.pageSize,10))+parseInt(this._options.pageSize,10)) ) ){ Css.removeClassName(item,'hide-all'); } else { Css.addClassName(item,'hide-all'); } },this)); }, /** * Sorts by a specific column. * * @method _sort * @param {Number} index Column number (starting at 0) * @private */ _sort: function( index ){ this._data.sort(Ink.bind(function(a,b){ var aValue = Element.textContent(Selector.select('td',a)[index]), bValue = Element.textContent(Selector.select('td',b)[index]) ; var regex = new RegExp(/\d/g); if( !isNaN(aValue) && regex.test(aValue) ){ aValue = parseInt(aValue,10); } else if( !isNaN(aValue) ){ aValue = parseFloat(aValue); } if( !isNaN(bValue) && regex.test(bValue) ){ bValue = parseInt(bValue,10); } else if( !isNaN(bValue) ){ bValue = parseFloat(bValue); } if( aValue === bValue ){ return 0; } else { return ( ( aValue>bValue ) ? 1 : -1 ); } },this)); }, /** * Assembles the headers markup * * @method _setHeaders * @param {Object} headers Key-value object that contains the fields as keys, their configuration (label and sorting ability) as value * @private */ _setHeaders: function( headers, rows ){ var field, header, thead, tr, th, index = 0 ; if( (thead = Selector.select('thead',this._rootElement)).length === 0 ){ thead = this._rootElement.createTHead(); tr = thead.insertRow(0); for( field in headers ){ if (headers.hasOwnProperty(field)) { if( !!this._options.visibleFields && (this._options.visibleFields.indexOf(field) === -1) ){ continue; } // th = tr.insertCell(index++); th = document.createElement('th'); header = headers[field]; if( ("sortable" in header) && (header.sortable.toString() === 'true') ){ th.setAttribute('data-sortable','true'); } if( ("label" in header) ){ Element.setTextContent(th, header.label); } this._originalFields.push(field); tr.appendChild(th); } } } else { var firstLine = rows[0]; for( field in firstLine ){ if (firstLine.hasOwnProperty(field)) { if( !!this._options.visibleFields && (this._options.visibleFields.indexOf(field) === -1) ){ continue; } this._originalFields.push(field); } } } }, /** * Method that sets the handlers for the headers * * @method _setHeadersHandlers * @private */ _setHeadersHandlers: function(){ /** * Setting the sortable columns and its event listeners */ var theads = Selector.select('thead', this._rootElement); if (!theads.length) { return; } Event.observe(theads[0],'click',this._handlers.click); this._headers = Selector.select('thead tr th',this._rootElement); InkArray.each(this._headers,Ink.bind(function(item, index){ var dataset = Element.data( item ); if( ('sortable' in dataset) && (dataset.sortable.toString() === 'true') ){ this._sortableFields['col_' + index] = 'none'; } }, this)); }, /** * This method gets the rows from AJAX and places them as <tr> and <td> * * @method _setData * @param {Object} rows Array of objects with the data to be showed * @private */ _setData: function( rows ){ var field, tbody, tr, td, trIndex, tdIndex ; tbody = Selector.select('tbody',this._rootElement); if( tbody.length === 0){ tbody = document.createElement('tbody'); this._rootElement.appendChild( tbody ); } else { tbody = tbody[0]; tbody.innerHTML = ''; } this._data = []; for( trIndex in rows ){ if (rows.hasOwnProperty(trIndex)) { tr = document.createElement('tr'); tbody.appendChild( tr ); tdIndex = 0; for( field in rows[trIndex] ){ if (rows[trIndex].hasOwnProperty(field)) { if( !!this._options.visibleFields && (this._options.visibleFields.indexOf(field) === -1) ){ continue; } td = tr.insertCell(tdIndex++); td.innerHTML = rows[trIndex][field]; } } this._data.push(tr); } } this._originalData = this._data.slice(0); }, /** * Sets the endpoint. Useful for changing the endpoint in runtime. * * @method _setEndpoint * @param {String} endpoint New endpoint */ setEndpoint: function( endpoint, currentPage ){ if( !this._markupMode ){ this._options.endpoint = endpoint; this._pagination.setCurrent( (!!currentPage) ? parseInt(currentPage,10) : 0 ); } }, /** * Checks if it needs the pagination and creates the necessary markup to have pagination * * @method _setPagination * @private */ _setPagination: function(){ var paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ); /** * Set pagination if defined */ if( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ){ /** * Applying the pagination */ if( !this._pagination ){ this._pagination = document.createElement('nav'); this._pagination.className = 'ink-navigation'; this._rootElement.parentNode.insertBefore(this._pagination,this._rootElement.nextSibling); this._pagination.appendChild( document.createElement('ul') ).className = 'pagination'; var Pagination = Ink.getModule('Ink.UI.Pagination',1); this._pagination = new Pagination( this._pagination, { size: Math.ceil(this._totalRows/this._options.pageSize), onChange: Ink.bind(function( ){ this._getData( this._options.endpoint ); },this) }); } } }, /** * Method to choose which is the best way to get the data based on the endpoint: * - AJAX * - JSONP * * @method _getData * @param {String} endpoint Valid endpoint * @param {Boolean} [firstRequest] If true, will make the request set the headers onSuccess * @private */ _getData: function( endpoint ){ Ink.requireModules(['Ink.Util.Url_1'],Ink.bind(function( InkURL ){ var parsedURL = InkURL.parseUrl( endpoint ), paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ), pageNum = ((!!this._pagination) ? this._pagination._current+1 : 1) ; if( parsedURL.query ){ parsedURL.query = parsedURL.query.split("&"); } else { parsedURL.query = []; } if( !paginated ){ this._getDataViaAjax( endpoint ); } else { parsedURL.query.push( 'rows_per_page=' + this._options.pageSize ); parsedURL.query.push( 'page=' + pageNum ); var sortStr = ''; for( var index in this._sortableFields ){ if( this._sortableFields[index] !== 'none' ){ parsedURL.query.push('sortField=' + this._originalFields[parseInt(index.replace('col_',''),10)]); parsedURL.query.push('sortOrder=' + this._sortableFields[index]); break; } } this._getDataViaAjax( endpoint + '?' + parsedURL.query.join('&') ); } },this)); }, /** * Gets the data via AJAX and triggers the changes in the * * @param {[type]} endpoint [description] * @param {[type]} firstRequest [description] * @return {[type]} [description] */ _getDataViaAjax: function( endpoint ){ var paginated = ( ("pageSize" in this._options) && (typeof this._options.pageSize !== 'undefined') ); new Ajax( endpoint, { method: 'GET', contentType: 'application/json', sanitizeJSON: true, onSuccess: Ink.bind(function( response ){ if( response.status === 200 ){ var jsonResponse = JSON.parse( response.responseText ); if( this._headers.length === 0 ){ this._setHeaders( jsonResponse.headers, jsonResponse.rows ); this._setHeadersHandlers(); } this._setData( jsonResponse.rows ); if( paginated ){ if( !!this._totalRows && (parseInt(jsonResponse.totalRows,10) !== parseInt(this._totalRows,10)) ){ this._totalRows = jsonResponse.totalRows; this._pagination.setSize( Math.ceil(this._totalRows/this._options.pageSize) ); } else { this._totalRows = jsonResponse.totalRows; } } else { if( !!this._totalRows && (jsonResponse.rows.length !== parseInt(this._totalRows,10)) ){ this._totalRows = jsonResponse.rows.length; this._pagination.setSize( Math.ceil(this._totalRows/this._options.pageSize) ); } else { this._totalRows = jsonResponse.rows.length; } } this._setPagination( ); } },this) } ); } }; return Table; }); /** * @module Ink.UI.Tabs_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Tabs', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) { 'use strict'; /** * Tabs component * * @class Ink.UI.Tabs * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {Boolean} [options.preventUrlChange] Flag that determines if follows the link on click or stops the event * @param {String} [options.active] ID of the tab to activate on creation * @param {Array} [options.disabled] IDs of the tabs that will be disabled on creation * @param {Function} [options.onBeforeChange] callback to be executed before changing tabs * @param {Function} [options.onChange] callback to be executed after changing tabs * @example * <div class="ink-tabs top"> <!-- replace 'top' with 'bottom', 'left' or 'right' to place navigation --> * * <!-- put navigation first if using top, left or right positioning --> * <ul class="tabs-nav"> * <li><a href="#home">Home</a></li> * <li><a href="#news">News</a></li> * <li><a href="#description">Description</a></li> * <li><a href="#stuff">Stuff</a></li> * <li><a href="#more_stuff">More stuff</a></li> * </ul> * * <!-- Put your content second if using top, left or right navigation --> * <div id="home" class="tabs-content"><p>Content</p></div> * <div id="news" class="tabs-content"><p>Content</p></div> * <div id="description" class="tabs-content"><p>Content</p></div> * <div id="stuff" class="tabs-content"><p>Content</p></div> * <div id="more_stuff" class="tabs-content"><p>Content</p></div> * <!-- If you're using bottom navigation, switch the nav block with the content blocks --> * * </div> * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Tabs_1'], function( Selector, Tabs ){ * var tabsElement = Ink.s('.ink-tabs'); * var tabsObj = new Tabs( tabsElement ); * }); * </script> */ var Tabs = function(selector, options) { if (!Aux.isDOMElement(selector)) { selector = Selector.select(selector); if (selector.length === 0) { throw new TypeError('1st argument must either be a DOM Element or a selector expression!'); } this._element = selector[0]; } else { this._element = selector; } this._options = Ink.extendObj({ preventUrlChange: false, active: undefined, disabled: [], onBeforeChange: undefined, onChange: undefined }, Element.data(selector)); this._options = Ink.extendObj(this._options,options || {}); this._handlers = { tabClicked: Ink.bindEvent(this._onTabClicked,this), disabledTabClicked: Ink.bindEvent(this._onDisabledTabClicked,this), resize: Ink.bindEvent(this._onResize,this) }; this._init(); }; Tabs.prototype = { /** * Init function called by the constructor * * @method _init * @private */ _init: function() { this._menu = Selector.select('.tabs-nav', this._element)[0]; this._menuTabs = this._getChildElements(this._menu); this._contentTabs = Selector.select('.tabs-content', this._element); //initialization of the tabs, hides all content before setting the active tab this._initializeDom(); // subscribe events this._observe(); //sets the first active tab this._setFirstActive(); //shows the active tab this._changeTab(this._activeMenuLink); this._handlers.resize(); Aux.registerInstance(this, this._element, 'tabs'); }, /** * Initialization of the tabs, hides all content before setting the active tab * * @method _initializeDom * @private */ _initializeDom: function(){ for(var i = 0; i < this._contentTabs.length; i++){ Css.hide(this._contentTabs[i]); } }, /** * Subscribe events * * @method _observe * @private */ _observe: function() { InkArray.each(this._menuTabs,Ink.bind(function(elem){ var link = Selector.select('a', elem)[0]; if(InkArray.inArray(link.getAttribute('href'), this._options.disabled)){ this.disable(link); } else { this.enable(link); } },this)); Event.observe(window, 'resize', this._handlers.resize); }, /** * Run at instantiation, to determine which is the first active tab * fallsback from window.location.href to options.active to the first not disabled tab * * @method _setFirstActive * @private */ _setFirstActive: function() { var hash = window.location.hash; this._activeContentTab = Selector.select(hash, this._element)[0] || Selector.select(this._hashify(this._options.active), this._element)[0] || Selector.select('.tabs-content', this._element)[0]; this._activeMenuLink = this._findLinkByHref(this._activeContentTab.getAttribute('id')); this._activeMenuTab = this._activeMenuLink.parentNode; }, /** * Changes to the desired tab * * @method _changeTab * @param {DOMElement} link anchor linking to the content container * @param {boolean} runCallbacks defines if the callbacks should be run or not * @private */ _changeTab: function(link, runCallbacks){ if(runCallbacks && typeof this._options.onBeforeChange !== 'undefined'){ this._options.onBeforeChange(this); } var selector = link.getAttribute('href'); Css.removeClassName(this._activeMenuTab, 'active'); Css.removeClassName(this._activeContentTab, 'active'); Css.addClassName(this._activeContentTab, 'hide-all'); this._activeMenuLink = link; this._activeMenuTab = this._activeMenuLink.parentNode; this._activeContentTab = Selector.select(selector.substr(selector.indexOf('#')), this._element)[0]; Css.addClassName(this._activeMenuTab, 'active'); Css.addClassName(this._activeContentTab, 'active'); Css.removeClassName(this._activeContentTab, 'hide-all'); Css.show(this._activeContentTab); if(runCallbacks && typeof(this._options.onChange) !== 'undefined'){ this._options.onChange(this); } }, /** * Tab clicked handler * * @method _onTabClicked * @param {Event} ev * @private */ _onTabClicked: function(ev) { Event.stop(ev); var target = Event.findElement(ev, 'A'); if(target.nodeName.toLowerCase() !== 'a') { return; } if( this._options.preventUrlChange.toString() !== 'true'){ window.location.hash = target.getAttribute('href').substr(target.getAttribute('href').indexOf('#')); } if(target === this._activeMenuLink){ return; } this.changeTab(target); }, /** * Disabled tab clicked handler * * @method _onDisabledTabClicked * @param {Event} ev * @private */ _onDisabledTabClicked: function(ev) { Event.stop(ev); }, /** * Resize handler * * @method _onResize * @private */ _onResize: function(){ var currentLayout = Aux.currentLayout(); if(currentLayout === this._lastLayout){ return; } if(currentLayout === Aux.Layouts.SMALL || currentLayout === Aux.Layouts.MEDIUM){ Css.removeClassName(this._menu, 'menu'); Css.removeClassName(this._menu, 'horizontal'); // Css.addClassName(this._menu, 'pills'); } else { Css.addClassName(this._menu, 'menu'); Css.addClassName(this._menu, 'horizontal'); // Css.removeClassName(this._menu, 'pills'); } this._lastLayout = currentLayout; }, /***************** * Aux Functions * *****************/ /** * Allows the hash to be passed with or without the cardinal sign * * @method _hashify * @param {String} hash the string to be hashified * @return {String} Resulting hash * @private */ _hashify: function(hash){ if(!hash){ return ""; } return hash.indexOf('#') === 0? hash : '#' + hash; }, /** * Returns the anchor with the desired href * * @method _findLinkBuHref * @param {String} href the href to be found on the returned link * @return {String|undefined} [description] * @private */ _findLinkByHref: function(href){ href = this._hashify(href); var ret; InkArray.each(this._menuTabs,Ink.bind(function(elem){ var link = Selector.select('a', elem)[0]; if( (link.getAttribute('href').indexOf('#') !== -1) && ( link.getAttribute('href').substr(link.getAttribute('href').indexOf('#')) === href ) ){ ret = link; } },this)); return ret; }, /** * Returns the child elements of a given parent element * * @method _getChildElements * @param {DOMElement} parent DOMElement to fetch the child elements from. * @return {Array} Child elements of the given parent. * @private */ _getChildElements: function(parent){ var childNodes = []; var children = parent.children; for(var i = 0; i < children.length; i++){ if(children[i].nodeType === 1){ childNodes.push(children[i]); } } return childNodes; }, /************** * PUBLIC API * **************/ /** * Changes to the desired tag * * @method changeTab * @param {String|DOMElement} selector the id of the desired tab or the link that links to it * @public */ changeTab: function(selector) { var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector)); if(!element || Css.hasClassName(element, 'ink-disabled')){ return; } this._changeTab(element, true); }, /** * Disables the desired tag * * @method disable * @param {String|DOMElement} selector the id of the desired tab or the link that links to it * @public */ disable: function(selector){ var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector)); if(!element){ return; } Event.stopObserving(element, 'click', this._handlers.tabClicked); Event.observe(element, 'click', this._handlers.disabledTabClicked); Css.addClassName(element, 'ink-disabled'); }, /** * Enables the desired tag * * @method enable * @param {String|DOMElement} selector the id of the desired tab or the link that links to it * @public */ enable: function(selector){ var element = (selector.nodeType === 1)? selector : this._findLinkByHref(this._hashify(selector)); if(!element){ return; } Event.stopObserving(element, 'click', this._handlers.disabledTabClicked); Event.observe(element, 'click', this._handlers.tabClicked); Css.removeClassName(element, 'ink-disabled'); }, /*********** * Getters * ***********/ /** * Returns the active tab id * * @method activeTab * @return {String} ID of the active tab. * @public */ activeTab: function(){ return this._activeContentTab.getAttribute('id'); }, /** * Returns the current active Menu LI * * @method activeMenuTab * @return {DOMElement} Active menu LI. * @public */ activeMenuTab: function(){ return this._activeMenuTab; }, /** * Returns the current active Menu anchorChanges to the desired tag * * @method activeMenuLink * @return {DOMElement} Active menu link * @public */ activeMenuLink: function(){ return this._activeMenuLink; }, /** * Returns the current active Content Tab * * @method activeContentTab * @return {DOMElement} Active Content Tab * @public */ activeContentTab: function(){ return this._activeContentTab; }, /** * Unregisters the component and removes its markup from the DOM * * @method destroy * @public */ destroy: Aux.destroyComponent }; return Tabs; }); /** * @module Ink.UI.Toggle_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Toggle', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) { 'use strict'; /** * Toggle component * * @class Ink.UI.Toggle * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {String} options.target CSS Selector that specifies the elements that will toggle * @param {String} [options.triggerEvent] Event that will trigger the toggling. Default is 'click' * @param {Boolean} [options.closeOnClick] Flag that determines if, when clicking outside of the toggled content, it should hide it. Default: true. * @example * <div class="ink-dropdown"> * <button class="ink-button toggle" data-target="#dropdown">Dropdown <span class="icon-caret-down"></span></button> * <ul id="dropdown" class="dropdown-menu"> * <li class="heading">Heading</li> * <li class="separator-above"><a href="#">Option</a></li> * <li><a href="#">Option</a></li> * <li class="separator-above disabled"><a href="#">Disabled option</a></li> * <li class="submenu"> * <a href="#" class="toggle" data-target="#submenu1">A longer option name</a> * <ul id="submenu1" class="dropdown-menu"> * <li class="submenu"> * <a href="#" class="toggle" data-target="#ultrasubmenu">Sub option</a> * <ul id="ultrasubmenu" class="dropdown-menu"> * <li><a href="#">Sub option</a></li> * <li><a href="#" data-target="ultrasubmenu">Sub option</a></li> * <li><a href="#">Sub option</a></li> * </ul> * </li> * <li><a href="#">Sub option</a></li> * <li><a href="#">Sub option</a></li> * </ul> * </li> * <li><a href="#">Option</a></li> * </ul> * </div> * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Toggle_1'], function( Selector, Toggle ){ * var toggleElement = Ink.s('.toggle'); * var toggleObj = new Toggle( toggleElement ); * }); * </script> */ var Toggle = function( selector, options ){ if( typeof selector !== 'string' && typeof selector !== 'object' ){ throw '[Ink.UI.Toggle] Invalid CSS selector to determine the root element'; } if( typeof selector === 'string' ){ this._rootElement = Selector.select( selector ); if( this._rootElement.length <= 0 ){ throw '[Ink.UI.Toggle] Root element not found'; } this._rootElement = this._rootElement[0]; } else { this._rootElement = selector; } this._options = Ink.extendObj({ target : undefined, triggerEvent: 'click', closeOnClick: true },Element.data(this._rootElement)); this._options = Ink.extendObj(this._options,options || {}); this._targets = (function (target) { if (typeof target === 'string') { return Selector.select(target); } else if (typeof target === 'object') { if (target.constructor === Array) { return target; } else { return [target]; } } }(this._options.target)); if (!this._targets.length) { throw '[Ink.UI.Toggle] Toggle target was not found! Supply a valid selector, array, or element through the `target` option.'; } this._init(); }; Toggle.prototype = { /** * Init function called by the constructor * * @method _init * @private */ _init: function(){ this._accordion = ( Css.hasClassName(this._rootElement.parentNode,'accordion') || Css.hasClassName(this._targets[0].parentNode,'accordion') ); Event.observe( this._rootElement, this._options.triggerEvent, Ink.bindEvent(this._onTriggerEvent,this) ); if( this._options.closeOnClick.toString() === 'true' ){ Event.observe( document, 'click', Ink.bindEvent(this._onClick,this)); } }, /** * Event handler. It's responsible for handling the <triggerEvent> defined in the options. * This will trigger the toggle. * * @method _onTriggerEvent * @param {Event} event * @private */ _onTriggerEvent: function( event ){ if( this._accordion ){ var elms, i, accordionElement; if( Css.hasClassName(this._targets[0].parentNode,'accordion') ){ accordionElement = this._targets[0].parentNode; } else { accordionElement = this._targets[0].parentNode.parentNode; } elms = Selector.select('.toggle',accordionElement); for( i=0; i<elms.length; i+=1 ){ var dataset = Element.data( elms[i] ), targetElm = Selector.select( dataset.target,accordionElement ) ; if( (targetElm.length > 0) && (targetElm[0] !== this._targets[0]) ){ targetElm[0].style.display = 'none'; } } } var finalClass, finalDisplay; for (var j = 0, len = this._targets.length; j < len; j++) { finalClass = ( Css.getStyle(this._targets[j],'display') === 'none') ? 'show-all' : 'hide-all'; finalDisplay = ( Css.getStyle(this._targets[j],'display') === 'none') ? 'block' : 'none'; Css.removeClassName(this._targets[j],'show-all'); Css.removeClassName(this._targets[j], 'hide-all'); Css.addClassName(this._targets[j], finalClass); this._targets[j].style.display = finalDisplay; } if( finalClass === 'show-all' ){ Css.addClassName(this._rootElement,'active'); } else { Css.removeClassName(this._rootElement,'active'); } }, /** * Click handler. Will handle clicks outside the toggle component. * * @method _onClick * @param {Event} event * @private */ _onClick: function( event ){ var tgtEl = Event.element(event), shades ; var ancestorOfTargets = InkArray.some(this._targets, function (target) { return Element.isAncestorOf(target, tgtEl); }); if( (this._rootElement === tgtEl) || Element.isAncestorOf(this._rootElement, tgtEl) || ancestorOfTargets ) { return; } else if( (shades = Ink.ss('.ink-shade')).length ) { var shadesLength = shades.length ; for( var i = 0; i < shadesLength; i++ ){ if( Element.isAncestorOf(shades[i],tgtEl) && Element.isAncestorOf(shades[i],this._rootElement) ){ return; } } } if(!Element.findUpwardsByClass(tgtEl, 'toggle')) { return; } this._dismiss( this._rootElement ); }, /** * Dismisses the toggling. * * @method _dismiss * @private */ _dismiss: function(){ if( ( Css.getStyle(this._targets[0],'display') === 'none') ){ return; } for (var i = 0, len = this._targets.length; i < len; i++) { Css.removeClassName(this._targets[i], 'show-all'); Css.addClassName(this._targets[i], 'hide-all'); this._targets[i].style.display = 'none'; } Css.removeClassName(this._rootElement,'active'); } }; return Toggle; }); /** * @module Ink.UI.Tooltip_1 * @author inkdev AT sapo.pt */ Ink.createModule('Ink.UI.Tooltip', '1', ['Ink.UI.Aux_1', 'Ink.Dom.Event_1', 'Ink.Dom.Element_1', 'Ink.Dom.Selector_1', 'Ink.Util.Array_1', 'Ink.Dom.Css_1', 'Ink.Dom.Browser_1'], function (Aux, InkEvent, InkElement, Selector, InkArray, Css) { 'use strict'; /** * @class Ink.UI.Tooltip * @constructor * * @param {DOMElement|String} target Target element or selector of elements, to display the tooltips on. * @param {Object} [options] * @param [options.text=''] Text content for the tooltip. * @param [options.where='up'] Positioning for the tooltip. Options: * @param options.where.up/down/left/right Place above, below, to the left of, or to the right of, the target. Show an arrow. * @param options.where.mousemove Place the tooltip to the bottom and to the right of the mouse when it hovers the element, and follow the mouse as it moves. * @param options.where.mousefix Place the tooltip to the bottom and to the right of the mouse when it hovers the element, keep the tooltip there motionless. * * @param [options.color=''] Color of the tooltip. Options are red, orange, blue, green and black. Default is white. * @param [options.fade=0.3] Fade time; Duration of the fade in/out effect. * @param [options.forever=0] Set to 1/true to prevent the tooltip from being erased when the mouse hovers away from the target * @param [options.timeout=0] Time for the tooltip to live. Useful together with [options.forever]. * @param [options.delay] Time the tooltip waits until it is displayed. Useful to avoid getting the attention of the user unnecessarily * @param [options.template=null] Element or selector containing HTML to be cloned into the tooltips. Can be a hidden element, because CSS `display` is set to `block`. * @param [options.templatefield=null] Selector within the template element to choose where the text is inserted into the tooltip. Useful when a wrapper DIV is required. * * @param [options.left,top=10] (Nitty-gritty) Spacing from the target to the tooltip, when `where` is `mousemove` or `mousefix` * @param [options.spacing=8] (Nitty-gritty) Spacing between the tooltip and the target element, when `where` is `up`, `down`, `left`, or `right` * * @example * <ul class="buttons"> * <li class="button" data-tip-text="Create a new document">New</li> * <li class="button" data-tip-text="Exit the program">Quit</li> * <li class="button" data-tip-text="Save the document you are working on">Save</li> * </ul> * * [...] * * <script> * Ink.requireModules(['Ink.UI.Tooltip_1'], function (Tooltip) { * new Tooltip('.button', {where: 'mousefix'}); * }); * </script> */ function Tooltip(element, options) { this._init(element, options || {}); } function EachTooltip(root, elm) { this._init(root, elm); } var transitionDurationName, transitionPropertyName, transitionTimingFunctionName; (function () { // Feature detection var test = document.createElement('DIV'); var names = ['transition', 'oTransition', 'msTransition', 'mozTransition', 'webkitTransition']; for (var i = 0; i < names.length; i++) { if (typeof test.style[names[i] + 'Duration'] !== 'undefined') { transitionDurationName = names[i] + 'Duration'; transitionPropertyName = names[i] + 'Property'; transitionTimingFunctionName = names[i] + 'TimingFunction'; break; } } }()); // Body or documentElement var bodies = document.getElementsByTagName('body'); var body = bodies && bodies.length ? bodies[0] : document.documentElement; Tooltip.prototype = { _init: function(element, options) { var elements; this.options = Ink.extendObj({ where: 'up', zIndex: 10000, left: 10, top: 10, spacing: 8, forever: 0, color: '', timeout: 0, delay: 0, template: null, templatefield: null, fade: 0.3, text: '' }, options || {}); if (typeof element === 'string') { elements = Selector.select(element); } else if (typeof element === 'object') { elements = [element]; } else { throw 'Element expected'; } this.tooltips = []; for (var i = 0, len = elements.length; i < len; i++) { this.tooltips[i] = new EachTooltip(this, elements[i]); } }, /** * Destroys the tooltips created by this instance * * @method destroy */ destroy: function () { InkArray.each(this.tooltips, function (tooltip) { tooltip._destroy(); }); this.tooltips = null; this.options = null; } }; EachTooltip.prototype = { _oppositeDirections: { left: 'right', right: 'left', up: 'down', down: 'up' }, _init: function(root, elm) { InkEvent.observe(elm, 'mouseover', Ink.bindEvent(this._onMouseOver, this)); InkEvent.observe(elm, 'mouseout', Ink.bindEvent(this._onMouseOut, this)); InkEvent.observe(elm, 'mousemove', Ink.bindEvent(this._onMouseMove, this)); this.root = root; this.element = elm; this._delayTimeout = null; this.tooltip = null; }, _makeTooltip: function (mousePosition) { if (!this._getOpt('text')) { return false; } var tooltip = this._createTooltipElement(); if (this.tooltip) { this._removeTooltip(); } this.tooltip = tooltip; this._fadeInTooltipElement(tooltip); this._placeTooltipElement(tooltip, mousePosition); InkEvent.observe(tooltip, 'mouseover', Ink.bindEvent(this._onTooltipMouseOver, this)); var timeout = this._getFloatOpt('timeout'); if (timeout) { setTimeout(Ink.bind(function () { if (this.tooltip === tooltip) { this._removeTooltip(); } }, this), timeout * 1000); } }, _createTooltipElement: function () { var template = this._getOpt('template'), // User template instead of our HTML templatefield = this._getOpt('templatefield'), tooltip, // The element we float field; // Element where we write our message. Child or same as the above if (template) { // The user told us of a template to use. We copy it. var temp = document.createElement('DIV'); temp.innerHTML = Aux.elOrSelector(template, 'options.template').outerHTML; tooltip = temp.firstChild; if (templatefield) { field = Selector.select(templatefield, tooltip); if (field) { field = field[0]; } else { throw 'options.templatefield must be a valid selector within options.template'; } } else { field = tooltip; // Assume same element if user did not specify a field } } else { // We create the default structure tooltip = document.createElement('DIV'); Css.addClassName(tooltip, 'ink-tooltip'); Css.addClassName(tooltip, this._getOpt('color')); field = document.createElement('DIV'); Css.addClassName(field, 'content'); tooltip.appendChild(field); } InkElement.setTextContent(field, this._getOpt('text')); tooltip.style.display = 'block'; tooltip.style.position = 'absolute'; tooltip.style.zIndex = this._getIntOpt('zIndex'); return tooltip; }, _fadeInTooltipElement: function (tooltip) { var fadeTime = this._getFloatOpt('fade'); if (transitionDurationName && fadeTime) { tooltip.style.opacity = '0'; tooltip.style[transitionDurationName] = fadeTime + 's'; tooltip.style[transitionPropertyName] = 'opacity'; tooltip.style[transitionTimingFunctionName] = 'ease-in-out'; setTimeout(function () { tooltip.style.opacity = '1'; }, 0); } }, _placeTooltipElement: function (tooltip, mousePosition) { var where = this._getOpt('where'); if (where === 'mousemove' || where === 'mousefix') { var mPos = mousePosition; this._setPos(mPos[0], mPos[1]); body.appendChild(tooltip); } else if (where.match(/(up|down|left|right)/)) { body.appendChild(tooltip); var targetElementPos = InkElement.offset(this.element); var tleft = targetElementPos[0], ttop = targetElementPos[1]; if (tleft instanceof Array) { // Work around a bug in Ink.Dom.Element.offsetLeft which made it return the result of offset() instead. TODO remove this check when fix is merged ttop = tleft[1]; tleft = tleft[0]; } var centerh = (InkElement.elementWidth(this.element) / 2) - (InkElement.elementWidth(tooltip) / 2), centerv = (InkElement.elementHeight(this.element) / 2) - (InkElement.elementHeight(tooltip) / 2); var spacing = this._getIntOpt('spacing'); var tooltipDims = InkElement.elementDimensions(tooltip); var elementDims = InkElement.elementDimensions(this.element); var maxX = InkElement.scrollWidth() + InkElement.viewportWidth(); var maxY = InkElement.scrollHeight() + InkElement.viewportHeight(); if (where === 'left' && tleft - tooltipDims[0] < 0) { where = 'right'; } else if (where === 'right' && tleft + tooltipDims[0] > maxX) { where = 'left'; } else if (where === 'up' && ttop - tooltipDims[1] < 0) { where = 'down'; } else if (where === 'down' && ttop + tooltipDims[1] > maxY) { where = 'up'; } if (where === 'up') { ttop -= tooltipDims[1]; ttop -= spacing; tleft += centerh; } else if (where === 'down') { ttop += elementDims[1]; ttop += spacing; tleft += centerh; } else if (where === 'left') { tleft -= tooltipDims[0]; tleft -= spacing; ttop += centerv; } else if (where === 'right') { tleft += elementDims[0]; tleft += spacing; ttop += centerv; } var arrow = null; if (where.match(/(up|down|left|right)/)) { arrow = document.createElement('SPAN'); Css.addClassName(arrow, 'arrow'); Css.addClassName(arrow, this._oppositeDirections[where]); tooltip.appendChild(arrow); } var scrl = this._getLocalScroll(); var tooltipLeft = tleft - scrl[0]; var tooltipTop = ttop - scrl[1]; var toBottom = (tooltipTop + tooltipDims[1]) - maxY; var toRight = (tooltipLeft + tooltipDims[0]) - maxX; var toLeft = 0 - tooltipLeft; var toTop = 0 - tooltipTop; if (toBottom > 0) { if (arrow) { arrow.style.top = (tooltipDims[1] / 2) + toBottom + 'px'; } tooltipTop -= toBottom; } else if (toTop > 0) { if (arrow) { arrow.style.top = (tooltipDims[1] / 2) - toTop + 'px'; } tooltipTop += toTop; } else if (toRight > 0) { if (arrow) { arrow.style.left = (tooltipDims[0] / 2) + toRight + 'px'; } tooltipLeft -= toRight; } else if (toLeft > 0) { if (arrow) { arrow.style.left = (tooltipDims[0] / 2) - toLeft + 'px'; } tooltipLeft += toLeft; } tooltip.style.left = tooltipLeft + 'px'; tooltip.style.top = tooltipTop + 'px'; } }, _removeTooltip: function() { var tooltip = this.tooltip; if (!tooltip) {return;} var remove = Ink.bind(InkElement.remove, {}, tooltip); if (this._getOpt('where') !== 'mousemove' && transitionDurationName) { tooltip.style.opacity = 0; // remove() will operate on correct tooltip, although this.tooltip === null then setTimeout(remove, this._getFloatOpt('fade') * 1000); } else { remove(); } this.tooltip = null; }, _getOpt: function (option) { var dataAttrVal = InkElement.data(this.element)[InkElement._camelCase('tip-' + option)]; if (dataAttrVal /* either null or "" may signify the absense of this attribute*/) { return dataAttrVal; } var instanceOption = this.root.options[option]; if (typeof instanceOption !== 'undefined') { return instanceOption; } }, _getIntOpt: function (option) { return parseInt(this._getOpt(option), 10); }, _getFloatOpt: function (option) { return parseFloat(this._getOpt(option), 10); }, _destroy: function () { if (this.tooltip) { InkElement.remove(this.tooltip); } this.root = null; // Cyclic reference = memory leaks this.element = null; this.tooltip = null; }, _onMouseOver: function(e) { // on IE < 10 you can't access the mouse event not even a tick after it fired var mousePosition = this._getMousePosition(e); var delay = this._getFloatOpt('delay'); if (delay) { this._delayTimeout = setTimeout(Ink.bind(function () { if (!this.tooltip) { this._makeTooltip(mousePosition); } this._delayTimeout = null; }, this), delay * 1000); } else { this._makeTooltip(mousePosition); } }, _onMouseMove: function(e) { if (this._getOpt('where') === 'mousemove' && this.tooltip) { var mPos = this._getMousePosition(e); this._setPos(mPos[0], mPos[1]); } }, _onMouseOut: function () { if (!this._getIntOpt('forever')) { this._removeTooltip(); } if (this._delayTimeout) { clearTimeout(this._delayTimeout); this._delayTimeout = null; } }, _onTooltipMouseOver: function () { if (this.tooltip) { // If tooltip is already being removed, this has no effect this._removeTooltip(); } }, _setPos: function(left, top) { left += this._getIntOpt('left'); top += this._getIntOpt('top'); var pageDims = this._getPageXY(); if (this.tooltip) { var elmDims = [InkElement.elementWidth(this.tooltip), InkElement.elementHeight(this.tooltip)]; var scrollDim = this._getScroll(); if((elmDims[0] + left - scrollDim[0]) >= (pageDims[0] - 20)) { left = (left - elmDims[0] - this._getIntOpt('left') - 10); } if((elmDims[1] + top - scrollDim[1]) >= (pageDims[1] - 20)) { top = (top - elmDims[1] - this._getIntOpt('top') - 10); } this.tooltip.style.left = left + 'px'; this.tooltip.style.top = top + 'px'; } }, _getPageXY: function() { var cWidth = 0; var cHeight = 0; if( typeof( window.innerWidth ) === 'number' ) { cWidth = window.innerWidth; cHeight = window.innerHeight; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { cWidth = document.documentElement.clientWidth; cHeight = document.documentElement.clientHeight; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { cWidth = document.body.clientWidth; cHeight = document.body.clientHeight; } return [parseInt(cWidth, 10), parseInt(cHeight, 10)]; }, _getScroll: function() { var dd = document.documentElement, db = document.body; if (dd && (dd.scrollLeft || dd.scrollTop)) { return [dd.scrollLeft, dd.scrollTop]; } else if (db) { return [db.scrollLeft, db.scrollTop]; } else { return [0, 0]; } }, _getLocalScroll: function () { var cumScroll = [0, 0]; var cursor = this.element.parentNode; var left, top; while (cursor && cursor !== document.documentElement && cursor !== document.body) { left = cursor.scrollLeft; top = cursor.scrollTop; if (left) { cumScroll[0] += left; } if (top) { cumScroll[1] += top; } cursor = cursor.parentNode; } return cumScroll; }, _getMousePosition: function(e) { return [parseInt(InkEvent.pointerX(e), 10), parseInt(InkEvent.pointerY(e), 10)]; } }; return Tooltip; }); /** * @module Ink.UI.TreeView_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.TreeView', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) { 'use strict'; /** * TreeView is an Ink's component responsible for presenting a defined set of elements in a tree-like hierarchical structure * * @class Ink.UI.TreeView * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {String} options.node CSS selector that identifies the elements that are considered nodes. * @param {String} options.child CSS selector that identifies the elements that are children of those nodes. * @example * <ul class="ink-tree-view"> * <li class="open"><span></span><a href="#">root</a> * <ul> * <li><a href="">child 1</a></li> * <li><span></span><a href="">child 2</a> * <ul> * <li><a href="">grandchild 2a</a></li> * <li><span></span><a href="">grandchild 2b</a> * <ul> * <li><a href="">grandgrandchild 1bA</a></li> * <li><a href="">grandgrandchild 1bB</a></li> * </ul> * </li> * </ul> * </li> * <li><a href="">child 3</a></li> * </ul> * </li> * </ul> * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.TreeView_1'], function( Selector, TreeView ){ * var treeViewElement = Ink.s('.ink-tree-view'); * var treeViewObj = new TreeView( treeViewElement ); * }); * </script> */ var TreeView = function(selector, options){ /** * Gets the element */ if( !Aux.isDOMElement(selector) && (typeof selector !== 'string') ){ throw '[Ink.UI.TreeView] :: Invalid selector'; } else if( typeof selector === 'string' ){ this._element = Selector.select( selector ); if( this._element.length < 1 ){ throw '[Ink.UI.TreeView] :: Selector has returned no elements'; } this._element = this._element[0]; } else { this._element = selector; } /** * Default options and they're overrided by data-attributes if any. * The parameters are: * @param {string} node Selector to define which elements are seen as nodes. Default: li * @param {string} child Selector to define which elements are represented as childs. Default: ul */ this._options = Ink.extendObj({ node: 'li', child: 'ul' },Element.data(this._element)); this._options = Ink.extendObj(this._options, options || {}); this._init(); }; TreeView.prototype = { /** * Init function called by the constructor. Sets the necessary event handlers. * * @method _init * @private */ _init: function(){ this._handlers = { click: Ink.bindEvent(this._onClick,this) }; Event.observe(this._element, 'click', this._handlers.click); var nodes = Selector.select(this._options.node,this._element), children ; InkArray.each(nodes,Ink.bind(function(item){ if( Css.hasClassName(item,'open') ) { return; } if( !Css.hasClassName(item, 'closed') ){ Css.addClassName(item,'closed'); } children = Selector.select(this._options.child,item); InkArray.each(children,Ink.bind(function( inner_item ){ if( !Css.hasClassName(inner_item, 'hide-all') ){ Css.addClassName(inner_item,'hide-all'); } },this)); },this)); }, /** * Handles the click event (as specified in the _init function). * * @method _onClick * @param {Event} event * @private */ _onClick: function(event){ /** * Summary: * If the clicked element is a "node" as defined in the options, will check if it has any "child". * If so, will show it or hide it, depending on its current state. And will stop the event's default behavior. * If not, will execute the event's default behavior. * */ var tgtEl = Event.element(event); if( this._options.node[0] === '.' ) { if( !Css.hasClassName(tgtEl,this._options.node.substr(1)) ){ while( (!Css.hasClassName(tgtEl,this._options.node.substr(1))) && (tgtEl.nodeName.toLowerCase() !== 'body') ){ tgtEl = tgtEl.parentNode; } } } else if( this._options.node[0] === '#' ){ if( tgtEl.id !== this._options.node.substr(1) ){ while( (tgtEl.id !== this._options.node.substr(1)) && (tgtEl.nodeName.toLowerCase() !== 'body') ){ tgtEl = tgtEl.parentNode; } } } else { if( tgtEl.nodeName.toLowerCase() !== this._options.node ){ while( (tgtEl.nodeName.toLowerCase() !== this._options.node) && (tgtEl.nodeName.toLowerCase() !== 'body') ){ tgtEl = tgtEl.parentNode; } } } if(tgtEl.nodeName.toLowerCase() === 'body'){ return; } var child = Selector.select(this._options.child,tgtEl); if( child.length > 0 ){ Event.stop(event); child = child[0]; if( Css.hasClassName(child,'hide-all') ){ Css.removeClassName(child,'hide-all'); Css.addClassName(tgtEl,'open'); Css.removeClassName(tgtEl,'closed'); } else { Css.addClassName(child,'hide-all'); Css.removeClassName(tgtEl,'open'); Css.addClassName(tgtEl,'closed'); } } } }; return TreeView; }); /** * @module Ink.UI.SmoothScroller_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.SmoothScroller', '1', ['Ink.Dom.Event_1','Ink.Dom.Selector_1','Ink.Dom.Loaded_1'], function(Event, Selector, Loaded ) { 'use strict'; /** * @class Ink.UI.SmoothScroller * @version 1 * @static */ var SmoothScroller = { /** * Sets the speed of the scrolling * * @property speed * @type {Number} * @readOnly * @static */ speed: 10, /** * Returns the Y position of the div * * @method gy * @param {DOMElement} d DOMElement to get the Y position from * @return {Number} Y position of div 'd' * @public * @static */ gy: function(d) { var gy; gy = d.offsetTop; if (d.offsetParent){ while ( (d = d.offsetParent) ){ gy += d.offsetTop; } } return gy; }, /** * Returns the current scroll position * * @method scrollTop * @return {Number} Current scroll position * @public * @static */ scrollTop: function() { var body = document.body, d = document.documentElement ; if (body && body.scrollTop){ return body.scrollTop; } if (d && d.scrollTop){ return d.scrollTop; } if (window.pageYOffset) { return window.pageYOffset; } return 0; }, /** * Attaches an event for an element * * @method add * @param {DOMElement} el DOMElement to make the listening of the event * @param {String} event Event name to be listened * @param {DOMElement} fn Callback function to run when the event is triggered. * @public * @static */ add: function(el, event, fn) { Event.observe(el,event,fn); return; }, /** * Kill an event of an element * * @method end * @param {String} e Event to be killed/stopped * @public * @static */ // kill an event of an element end: function(e) { if (window.event) { window.event.cancelBubble = true; window.event.returnValue = false; return; } Event.stop(e); }, /** * Moves the scrollbar to the target element * * @method scroll * @param {Number} d Y coordinate value to stop * @public * @static */ scroll: function(d) { var a = Ink.UI.SmoothScroller.scrollTop(); if (d > a) { a += Math.ceil((d - a) / Ink.UI.SmoothScroller.speed); } else { a = a + (d - a) / Ink.UI.SmoothScroller.speed; } window.scrollTo(0, a); if ((a) === d || Ink.UI.SmoothScroller.offsetTop === a) { clearInterval(Ink.UI.SmoothScroller.interval); } Ink.UI.SmoothScroller.offsetTop = a; }, /** * Initializer that adds the rendered to run when the page is ready * * @method init * @public * @static */ // initializer that adds the renderer to the onload function of the window init: function() { Loaded.run(Ink.UI.SmoothScroller.render); }, /** * This method extracts all the anchors and validates thenm as # and attaches the events * * @method render * @public * @static */ render: function() { var a = Selector.select('a.scrollableLink'); Ink.UI.SmoothScroller.end(this); for (var i = 0; i < a.length; i++) { var _elm = a[i]; if (_elm.href && _elm.href.indexOf('#') !== -1 && ((_elm.pathname === location.pathname) || ('/' + _elm.pathname === location.pathname))) { Ink.UI.SmoothScroller.add(_elm, 'click', Ink.UI.SmoothScroller.end); Event.observe(_elm,'click', Ink.bindEvent(Ink.UI.SmoothScroller.clickScroll, this, _elm)); } } }, /** * Click handler * * @method clickScroll * @public * @static */ clickScroll: function(event, _elm) { /* Ink.UI.SmoothScroller.end(this); var hash = this.hash.substr(1); var elm = Selector.select('a[name="' + hash + '"],#' + hash); if (typeof(elm[0]) !== 'undefined') { if (this.parentNode.className.indexOf('active') === -1) { var ul = this.parentNode.parentNode, li = ul.firstChild; do { if ((typeof(li.tagName) !== 'undefined') && (li.tagName.toUpperCase() === 'LI') && (li.className.indexOf('active') !== -1)) { li.className = li.className.replace('active', ''); break; } } while ((li = li.nextSibling)); this.parentNode.className += " active"; } clearInterval(Ink.UI.SmoothScroller.interval); Ink.UI.SmoothScroller.interval = setInterval('Ink.UI.SmoothScroller.scroll(' + Ink.UI.SmoothScroller.gy(elm[0]) + ')', 10); } */ Ink.UI.SmoothScroller.end(_elm); if(_elm !== null && _elm.getAttribute('href') !== null) { var hashIndex = _elm.href.indexOf('#'); if(hashIndex === -1) { return; } var hash = _elm.href.substr((hashIndex + 1)); var elm = Selector.select('a[name="' + hash + '"],#' + hash); if (typeof(elm[0]) !== 'undefined') { if (_elm.parentNode.className.indexOf('active') === -1) { var ul = _elm.parentNode.parentNode, li = ul.firstChild; do { if ((typeof(li.tagName) !== 'undefined') && (li.tagName.toUpperCase() === 'LI') && (li.className.indexOf('active') !== -1)) { li.className = li.className.replace('active', ''); break; } } while ((li = li.nextSibling)); _elm.parentNode.className += " active"; } clearInterval(Ink.UI.SmoothScroller.interval); Ink.UI.SmoothScroller.interval = setInterval('Ink.UI.SmoothScroller.scroll(' + Ink.UI.SmoothScroller.gy(elm[0]) + ')', 10); } } } }; return SmoothScroller; }); /** * @module Ink.UI.ImageQuery_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.ImageQuery', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) { 'use strict'; /** * @class Ink.UI.ImageQuery * @constructor * @version 1 * * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {String|Function} [options.src] String or Callback function (that returns a string) with the path to be used to get the images. * @param {String|Function} [options.retina] String or Callback function (that returns a string) with the path to be used to get RETINA specific images. * @param {Array} [options.queries] Array of queries * @param {String} [options.queries.label] Label of the query. Ex. 'small' * @param {Number} [options.queries.width] Min-width to use this query * @param {Function} [options.onLoad] Date format string * * @example * <div class="imageQueryExample large-100 medium-100 small-100 content-center clearfix vspace"> * <img src="/assets/imgs/imagequery/small/image.jpg" /> * </div> * <script type="text/javascript"> * Ink.requireModules( ['Ink.Dom.Selector_1', 'Ink.UI.ImageQuery_1'], function( Selector, ImageQuery ){ * var imageQueryElement = Ink.s('.imageQueryExample img'); * var imageQueryObj = new ImageQuery('.imageQueryExample img',{ * src: '/assets/imgs/imagequery/{:label}/{:file}', * queries: [ * { * label: 'small', * width: 480 * }, * { * label: 'medium', * width: 640 * }, * { * label: 'large', * width: 1024 * } * ] * }); * } ); * </script> */ var ImageQuery = function(selector, options){ /** * Selector's type checking */ if( !Aux.isDOMElement(selector) && (typeof selector !== 'string') ){ throw '[ImageQuery] :: Invalid selector'; } else if( typeof selector === 'string' ){ this._element = Selector.select( selector ); if( this._element.length < 1 ){ throw '[ImageQuery] :: Selector has returned no elements'; } else if( this._element.length > 1 ){ var i; for( i=1;i<this._element.length;i+=1 ){ new Ink.UI.ImageQuery(this._element[i],options); } } this._element = this._element[0]; } else { this._element = selector; } /** * Default options and they're overrided by data-attributes if any. * The parameters are: * @param {array} queries Array of objects that determine the label/name and its min-width to be applied. * @param {boolean} allowFirstLoad Boolean flag to allow the loading of the first element. */ this._options = Ink.extendObj({ queries:[], onLoad: null },Element.data(this._element)); this._options = Ink.extendObj(this._options, options || {}); /** * Determining the original basename (with the querystring) of the file. */ var pos; if( (pos=this._element.src.lastIndexOf('?')) !== -1 ){ var search = this._element.src.substr(pos); this._filename = this._element.src.replace(search,'').split('/').pop()+search; } else { this._filename = this._element.src.split('/').pop(); } this._init(); }; ImageQuery.prototype = { /** * Init function called by the constructor * * @method _init * @private */ _init: function(){ // Sort queries by width, in descendant order. this._options.queries = InkArray.sortMulti(this._options.queries,'width').reverse(); // Declaring the event handlers, in this case, the window.resize and the (element) load. this._handlers = { resize: Ink.bindEvent(this._onResize,this), load: Ink.bindEvent(this._onLoad,this) }; if( typeof this._options.onLoad === 'function' ){ Event.observe(this._element, 'onload', this._handlers.load); } Event.observe(window, 'resize', this._handlers.resize); // Imediate call to apply the right images based on the current viewport this._handlers.resize.call(this); }, /** * Handles the resize event (as specified in the _init function) * * @method _onResize * @private */ _onResize: function(){ clearTimeout(timeout); var timeout = setTimeout(Ink.bind(function(){ if( !this._options.queries || (this._options.queries === {}) ){ clearTimeout(timeout); return; } var query, selected, viewportWidth ; /** * Gets viewport width */ if( typeof( window.innerWidth ) === 'number' ) { viewportWidth = window.innerWidth; } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { viewportWidth = document.documentElement.clientWidth; } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { viewportWidth = document.body.clientWidth; } /** * Queries are in a descendant order. We want to find the query with the highest width that fits * the viewport, therefore the first one. */ for( query=0; query < this._options.queries.length; query+=1 ){ if (this._options.queries[query].width <= viewportWidth){ selected = query; break; } } /** * If it doesn't find any selectable query (because they don't meet the requirements) * let's select the one with the smallest width */ if( typeof selected === 'undefined' ){ selected = this._options.queries.length-1; } /** * Choosing the right src. The rule is: * * "If there is specifically defined in the query object, use that. Otherwise uses the global src." * * The above rule applies to a retina src. */ var src = this._options.queries[selected].src || this._options.src; if ( ("devicePixelRatio" in window && window.devicePixelRatio>1) && ('retina' in this._options ) ) { src = this._options.queries[selected].retina || this._options.retina; } /** * Injects the file variable for usage in the 'templating system' below */ this._options.queries[selected].file = this._filename; /** * Since we allow the src to be a callback, let's run it and get the results. * For the inside, we're passing the element (img) being processed and the object of the selected * query. */ if( typeof src === 'function' ){ src = src.apply(this,[this._element,this._options.queries[selected]]); if( typeof src !== 'string' ){ throw '[ImageQuery] :: "src" callback does not return a string'; } } /** * Replace the values of the existing properties on the query object (except src and retina) in the * defined src and/or retina. */ var property; for( property in this._options.queries[selected] ){ if (this._options.queries[selected].hasOwnProperty(property)) { if( ( property === 'src' ) || ( property === 'retina' ) ){ continue; } src = src.replace("{:" + property + "}",this._options.queries[selected][property]); } } this._element.src = src; // Removes the injected file property delete this._options.queries[selected].file; timeout = undefined; },this),300); }, /** * Handles the element loading (img onload) event * * @method _onLoad * @private */ _onLoad: function(){ /** * Since we allow a callback for this let's run it. */ this._options.onLoad.call(this); } }; return ImageQuery; }); /** * @module Ink.UI.FormValidator_2 * @author inkdev AT sapo.pt * @version 2 */ Ink.createModule('Ink.UI.FormValidator', '2', [ 'Ink.UI.Aux_1','Ink.Dom.Element_1','Ink.Dom.Event_1','Ink.Dom.Selector_1','Ink.Dom.Css_1','Ink.Util.Array_1','Ink.Util.I18n_1','Ink.Util.Validator_1'], function( Aux, Element, Event, Selector, Css, InkArray, I18n, InkValidator ) { 'use strict'; /** * Validation Functions to be used * Some functions are a port from PHP, others are the 'best' solutions available * * @type {Object} * @private * @static */ var validationFunctions = { /** * Checks if the value is actually defined and is not empty * * @method validationFunctions.required * @param {String} value Value to be checked * @return {Boolean} True case is defined, false if it's empty or not defined. */ 'required': function( value ){ return ( (typeof value !== 'undefined') && ( !(/^\s*$/).test(value) ) ); }, /** * Checks if the value has a minimum length * * @method validationFunctions.min_length * @param {String} value Value to be checked * @param {String|Number} minSize Number of characters that the value at least must have. * @return {Boolean} True if the length of value is equal or bigger than the minimum chars defined. False if not. */ 'min_length': function( value, minSize ){ return ( (typeof value === 'string') && ( value.length >= parseInt(minSize,10) ) ); }, /** * Checks if the value has a maximum length * * @method validationFunctions.max_length * @param {String} value Value to be checked * @param {String|Number} maxSize Number of characters that the value at maximum can have. * @return {Boolean} True if the length of value is equal or smaller than the maximum chars defined. False if not. */ 'max_length': function( value, maxSize ){ return ( (typeof value === 'string') && ( value.length <= parseInt(maxSize,10) ) ); }, /** * Checks if the value has an exact length * * @method validationFunctions.exact_length * @param {String} value Value to be checked * @param {String|Number} exactSize Number of characters that the value must have. * @return {Boolean} True if the length of value is equal to the size defined. False if not. */ 'exact_length': function( value, exactSize ){ return ( (typeof value === 'string') && ( value.length === parseInt(exactSize,10) ) ); }, /** * Checks if the value has a valid e-mail address * * @method validationFunctions.email * @param {String} value Value to be checked * @return {Boolean} True if the value is a valid e-mail address. False if not. */ 'email': function( value ){ return ( ( typeof value === 'string' ) && InkValidator.mail( value ) ); }, /** * Checks if the value has a valid URL * * @method validationFunctions.url * @param {String} value Value to be checked * @param {Boolean} fullCheck Flag that specifies if the value must be validated as a full url (with the protocol) or not. * @return {Boolean} True if the URL is considered valid. False if not. */ 'url': function( value, fullCheck ){ fullCheck = fullCheck || false; return ( (typeof value === 'string') && InkValidator.url( value, fullCheck ) ); }, /** * Checks if the value is a valid IP. Supports ipv4 and ipv6 * * @method validationFunctions.ip * @param {String} value Value to be checked * @param {String} ipType Type of IP to be validated. The values are: ipv4, ipv6. By default is ipv4. * @return {Boolean} True if the value is a valid IP address. False if not. */ 'ip': function( value, ipType ){ if( typeof value !== 'string' ){ return false; } return InkValidator.isIP(value, ipType); }, /** * Checks if the value is a valid phone number. Supports several countries, based in the Ink.Util.Validator class. * * @method validationFunctions.phone * @param {String} value Value to be checked * @param {String} phoneType Country's initials to specify the type of phone number to be validated. Ex: 'AO'. * @return {Boolean} True if it's a valid phone number. False if not. */ 'phone': function( value, phoneType ){ if( typeof value !== 'string' ){ return false; } var countryCode = phoneType ? phoneType.toUpperCase() : ''; return InkValidator['is' + countryCode + 'Phone'](value); }, /** * Checks if it's a valid credit card. * * @method validationFunctions.credit_card * @param {String} value Value to be checked * @param {String} cardType Type of credit card to be validated. The card types available are in the Ink.Util.Validator class. * @return {Boolean} True if the value is a valid credit card number. False if not. */ 'credit_card': function( value, cardType ){ if( typeof value !== 'string' ){ return false; } return InkValidator.isCreditCard( value, cardType || 'default' ); }, /** * Checks if the value is a valid date. * * @method validationFunctions.date * @param {String} value Value to be checked * @param {String} format Specific format of the date. * @return {Boolean} True if the value is a valid date. False if not. */ 'date': function( value, format ){ return ( (typeof value === 'string' ) && InkValidator.isDate(format, value) ); }, /** * Checks if the value only contains alphabetical values. * * @method validationFunctions.alpha * @param {String} value Value to be checked * @param {Boolean} supportSpaces Allow whitespace * @return {Boolean} True if the value is alphabetical-only. False if not. */ 'alpha': function( value, supportSpaces ){ return InkValidator.ascii(value, {singleLineWhitespace: supportSpaces}); }, /* * Check that the value contains only printable unicode text characters * from the Basic Multilingual plane (BMP) * Optionally allow punctuation and whitespace * * @method validationFunctions.text * @param {String} value Value to be checked * @return {Boolean} Whether the value only contains printable text characters **/ 'text': function (value, whitespace, punctuation) { return InkValidator.unicode(value, { singleLineWhitespace: whitespace, unicodePunctuation: punctuation}); }, /* * Check that the value contains only printable text characters * available in the latin-1 encoding. * * Optionally allow punctuation and whitespace * * @method validationFunctions.text * @param {String} value Value to be checked * @return {Boolean} Whether the value only contains printable text characters **/ 'latin': function (value, punctuation, whitespace) { if ( typeof value !== 'string') { return false; } return InkValidator.latin1(value, {latin1Punctuation: punctuation, singleLineWhitespace: whitespace}); }, /** * Checks if the value only contains alphabetical and numerical characters. * * @method validationFunctions.alpha_numeric * @param {String} value Value to be checked * @return {Boolean} True if the value is a valid alphanumerical. False if not. */ 'alpha_numeric': function( value ){ return InkValidator.ascii(value, {numbers: true}); }, /** * Checks if the value only contains alphabetical, dash or underscore characteres. * * @method validationFunctions.alpha_dashes * @param {String} value Value to be checked * @return {Boolean} True if the value is a valid. False if not. */ 'alpha_dash': function( value ){ return InkValidator.ascii(value, {dash: true, underscore: true}); }, /** * Checks if the value is a digit (an integer of length = 1). * * @method validationFunctions.digit * @param {String} value Value to be checked * @return {Boolean} True if the value is a valid digit. False if not. */ 'digit': function( value ){ return ((typeof value === 'string') && /^[0-9]{1}$/.test(value)); }, /** * Checks if the value is a valid integer. * * @method validationFunctions.integer * @param {String} value Value to be checked * @param {String} positive Flag that specifies if the integer is must be positive (unsigned). * @return {Boolean} True if the value is a valid integer. False if not. */ 'integer': function( value, positive ){ return InkValidator.number(value, { negative: !positive, decimalPlaces: 0 }); }, /** * Checks if the value is a valid decimal number. * * @method validationFunctions.decimal * @param {String} value Value to be checked * @param {String} decimalSeparator Character that splits the integer part from the decimal one. By default is '.'. * @param {String} [decimalPlaces] Maximum number of digits that the decimal part must have. * @param {String} [leftDigits] Maximum number of digits that the integer part must have, when provided. * @return {Boolean} True if the value is a valid decimal number. False if not. */ 'decimal': function( value, decimalSeparator, decimalPlaces, leftDigits ){ return InkValidator.number(value, { decimalSep: decimalSeparator || '.', decimalPlaces: +decimalPlaces || null, maxDigits: +leftDigits }); }, /** * Checks if it is a numeric value. * * @method validationFunctions.numeric * @param {String} value Value to be checked * @param {String} decimalSeparator Verifies if it's a valid decimal. Otherwise checks if it's a valid integer. * @param {String} [decimalPlaces] (when the number is decimal) Maximum number of digits that the decimal part must have. * @param {String} [leftDigits] (when the number is decimal) Maximum number of digits that the integer part must have, when provided. * @return {Boolean} True if the value is numeric. False if not. */ 'numeric': function( value, decimalSeparator, decimalPlaces, leftDigits ){ decimalSeparator = decimalSeparator || '.'; if( value.indexOf(decimalSeparator) !== -1 ){ return validationFunctions.decimal( value, decimalSeparator, decimalPlaces, leftDigits ); } else { return validationFunctions.integer( value ); } }, /** * Checks if the value is in a specific range of values. The parameters after the first one are used for specifying the range, and are similar in function to python's range() function. * * @method validationFunctions.range * @param {String} value Value to be checked * @param {String} minValue Left limit of the range. * @param {String} maxValue Right limit of the range. * @param {String} [multipleOf] In case you want numbers that are only multiples of another number. * @return {Boolean} True if the value is within the range. False if not. */ 'range': function( value, minValue, maxValue, multipleOf ){ value = +value; minValue = +minValue; maxValue = +maxValue; if (isNaN(value) || isNaN(minValue) || isNaN(maxValue)) { return false; } if( value < minValue || value > maxValue ){ return false; } if (multipleOf) { return (value - minValue) % multipleOf === 0; } else { return true; } }, /** * Checks if the value is a valid color. * * @method validationFunctions.color * @param {String} value Value to be checked * @return {Boolean} True if the value is a valid color. False if not. */ 'color': function( value ){ return InkValidator.isColor(value); }, /** * Checks if the value matches the value of a different field. * * @method validationFunctions.matches * @param {String} value Value to be checked * @param {String} fieldToCompare Name or ID of the field to compare. * @return {Boolean} True if the values match. False if not. */ 'matches': function( value, fieldToCompare ){ return ( value === this.getFormElements()[fieldToCompare][0].getValue() ); } }; /** * Error messages for the validation functions above * @type {Object} * @private * @static */ var validationMessages = new I18n({ en_US: { 'formvalidator.required' : 'The {field} filling is mandatory', 'formvalidator.min_length': 'The {field} must have a minimum size of {param1} characters', 'formvalidator.max_length': 'The {field} must have a maximum size of {param1} characters', 'formvalidator.exact_length': 'The {field} must have an exact size of {param1} characters', 'formvalidator.email': 'The {field} must have a valid e-mail address', 'formvalidator.url': 'The {field} must have a valid URL', 'formvalidator.ip': 'The {field} does not contain a valid {param1} IP address', 'formvalidator.phone': 'The {field} does not contain a valid {param1} phone number', 'formvalidator.credit_card': 'The {field} does not contain a valid {param1} credit card', 'formvalidator.date': 'The {field} should contain a date in the {param1} format', 'formvalidator.alpha': 'The {field} should only contain letters', 'formvalidator.text': 'The {field} should only contain alphabetic characters', 'formvalidator.latin': 'The {field} should only contain alphabetic characters', 'formvalidator.alpha_numeric': 'The {field} should only contain letters or numbers', 'formvalidator.alpha_dashes': 'The {field} should only contain letters or dashes', 'formvalidator.digit': 'The {field} should only contain a digit', 'formvalidator.integer': 'The {field} should only contain an integer', 'formvalidator.decimal': 'The {field} should contain a valid decimal number', 'formvalidator.numeric': 'The {field} should contain a number', 'formvalidator.range': 'The {field} should contain a number between {param1} and {param2}', 'formvalidator.color': 'The {field} should contain a valid color', 'formvalidator.matches': 'The {field} should match the field {param1}', 'formvalidator.validation_function_not_found': 'The rule {rule} has not been defined' }, pt_PT: { 'formvalidator.required' : 'Preencher {field} é obrigatório', 'formvalidator.min_length': '{field} deve ter no mínimo {param1} caracteres', 'formvalidator.max_length': '{field} tem um tamanho máximo de {param1} caracteres', 'formvalidator.exact_length': '{field} devia ter exactamente {param1} caracteres', 'formvalidator.email': '{field} deve ser um e-mail válido', 'formvalidator.url': 'O {field} deve ser um URL válido', 'formvalidator.ip': '{field} não tem um endereço IP {param1} válido', 'formvalidator.phone': '{field} deve ser preenchido com um número de telefone {param1} válido.', 'formvalidator.credit_card': '{field} não tem um cartão de crédito {param1} válido', 'formvalidator.date': '{field} deve conter uma data no formato {param1}', 'formvalidator.alpha': 'O campo {field} deve conter apenas caracteres alfabéticos', 'formvalidator.text': 'O campo {field} deve conter apenas caracteres alfabéticos', 'formvalidator.latin': 'O campo {field} deve conter apenas caracteres alfabéticos', 'formvalidator.alpha_numeric': '{field} deve conter apenas letras e números', 'formvalidator.alpha_dashes': '{field} deve conter apenas letras e traços', 'formvalidator.digit': '{field} destina-se a ser preenchido com apenas um dígito', 'formvalidator.integer': '{field} deve conter um número inteiro', 'formvalidator.decimal': '{field} deve conter um número válido', 'formvalidator.numeric': '{field} deve conter um número válido', 'formvalidator.range': '{field} deve conter um número entre {param1} e {param2}', 'formvalidator.color': '{field} deve conter uma cor válida', 'formvalidator.matches': '{field} deve corresponder ao campo {param1}', 'formvalidator.validation_function_not_found': '[A regra {rule} não foi definida]' }, }, 'en_US'); /** * Constructor of a FormElement. * This type of object has particular methods to parse rules and validate them in a specific DOM Element. * * @param {DOMElement} element DOM Element * @param {Object} options Object with configuration options * @return {FormElement} FormElement object */ var FormElement = function( element, options ){ this._element = Aux.elOrSelector( element, 'Invalid FormElement' ); this._errors = {}; this._rules = {}; this._value = null; this._options = Ink.extendObj( { label: this._getLabel() }, Element.data(this._element) ); this._options = Ink.extendObj( this._options, options || {} ); }; /** * FormElement's prototype */ FormElement.prototype = { /** * Function to get the label that identifies the field. * If it can't find one, it will use the name or the id * (depending on what is defined) * * @method _getLabel * @return {String} Label to be used in the error messages * @private */ _getLabel: function(){ var controlGroup = Element.findUpwardsByClass(this._element,'control-group'); var label = Ink.s('label',controlGroup); if( label ){ label = Element.textContent(label); } else { label = this._element.name || this._element.id || ''; } return label; }, /** * Function to parse a rules' string. * Ex: required|number|max_length[30] * * @method _parseRules * @param {String} rules String with the rules * @private */ _parseRules: function( rules ){ this._rules = {}; rules = rules.split("|"); var i, rulesLength = rules.length, rule, params, paramStartPos ; if( rulesLength > 0 ){ for( i = 0; i < rulesLength; i++ ){ rule = rules[i]; if( !rule ){ continue; } if( ( paramStartPos = rule.indexOf('[') ) !== -1 ){ params = rule.substr( paramStartPos+1 ); params = params.split(']'); params = params[0]; params = params.split(','); for (var p = 0, len = params.length; p < len; p++) { params[p] = params[p] === 'true' ? true : params[p] === 'false' ? false : params[p]; } params.splice(0,0,this.getValue()); rule = rule.substr(0,paramStartPos); this._rules[rule] = params; } else { this._rules[rule] = [this.getValue()]; } } } }, /** * Function to add an error to the FormElement's 'errors' object. * It basically receives the rule where the error occurred, the parameters passed to it (if any) * and the error message. * Then it replaces some tokens in the message for a more 'custom' reading * * @method _addError * @param {String|null} rule Rule that failed, or null if no rule was found. * @private * @static */ _addError: function(rule){ var params = this._rules[rule] || []; var paramObj = { field: this._options.label, value: this.getValue() }; for( var i = 1; i < params.length; i++ ){ paramObj['param' + i] = params[i]; } var i18nKey = 'formvalidator.' + rule; this._errors[rule] = validationMessages.text(i18nKey, paramObj); if (this._errors[rule] === i18nKey) { this._errors[rule] = 'Validation message not found'; } }, /** * Function to retrieve the element's value * * @method getValue * @return {mixed} The DOM Element's value * @public */ getValue: function(){ switch(this._element.nodeName.toLowerCase()){ case 'select': return Ink.s('option:selected',this._element).value; case 'textarea': return this._element.innerHTML; case 'input': if( "type" in this._element ){ if( (this._element.type === 'radio') && (this._element.type === 'checkbox') ){ if( this._element.checked ){ return this._element.value; } } else if( this._element.type !== 'file' ){ return this._element.value; } } else { return this._element.value; } return; default: return this._element.innerHTML; } }, /** * Function that returns the constructed errors object. * * @method getErrors * @return {Object} Errors' object * @public */ getErrors: function(){ return this._errors; }, /** * Function that returns the DOM element related to it. * * @method getElement * @return {Object} DOM Element * @public */ getElement: function(){ return this._element; }, /** * Get other elements in the same form. * * @method getFormElements * @return {Object} A mapping of keys to other elements in this form. * @public */ getFormElements: function () { return this._options.form._formElements; }, /** * Function used to validate the element based on the rules defined. * It parses the rules defined in the _options.rules property. * * @method validate * @return {Boolean} True if every rule was valid. False if one fails. * @public */ validate: function(){ this._errors = {}; if( "rules" in this._options || 1){ this._parseRules( this._options.rules ); } if( ("required" in this._rules) || (this.getValue() !== '') ){ for(var rule in this._rules) { if (this._rules.hasOwnProperty(rule)) { if( (typeof validationFunctions[rule] === 'function') ){ if( validationFunctions[rule].apply(this, this._rules[rule] ) === false ){ this._addError( rule ); return false; } } else { this._addError( null ); return false; } } } } return true; } }; /** * @class Ink.UI.FormValidator_2 * @version 2 * @constructor * @param {String|DOMElement} selector Either a CSS Selector string, or the form's DOMElement * @param {} [varname] [description] * @example * Ink.requireModules( ['Ink.UI.FormValidator_2'], function( FormValidator ){ * var myValidator = new FormValidator( 'form' ); * }); */ var FormValidator = function( selector, options ){ /** * DOMElement of the <form> being validated * * @property _rootElement * @type {DOMElement} */ this._rootElement = Aux.elOrSelector( selector ); /** * Object that will gather the form elements by name * * @property _formElements * @type {Object} */ this._formElements = {}; /** * Error message DOMElements * * @property _errorMessages */ this._errorMessages = []; /** * Array of elements marked with validation errors * * @property _markedErrorElements */ this._markedErrorElements = []; /** * Configuration options. Fetches the data attributes first, then the ones passed when executing the constructor. * By doing that, the latter will be the one with highest priority. * * @property _options * @type {Object} */ this._options = Ink.extendObj({ eventTrigger: 'submit', searchFor: 'input, select, textarea, .control-group', beforeValidation: undefined, onError: undefined, onSuccess: undefined },Element.data(this._rootElement)); this._options = Ink.extendObj( this._options, options || {} ); // Sets an event listener for a specific event in the form, if defined. // By default is the 'submit' event. if( typeof this._options.eventTrigger === 'string' ){ Event.observe( this._rootElement,this._options.eventTrigger, Ink.bindEvent(this.validate,this) ); } this._init(); }; /** * Method used to set validation functions (either custom or ovewrite the existent ones) * * @method setRule * @param {String} name Name of the function. E.g. 'required' * @param {String} errorMessage Error message to be displayed in case of returning false. E.g. 'Oops, you passed {param1} as parameter1, lorem ipsum dolor...' * @param {Function} cb Function to be executed when calling this rule * @public * @static */ FormValidator.setRule = function( name, errorMessage, cb ){ validationFunctions[ name ] = cb; if (validationMessages.getKey('formvalidator.' + name) !== errorMessage) { var langObj = {}; langObj['formvalidator.' + name] = errorMessage; var dictObj = {}; dictObj[validationMessages.lang()] = langObj; validationMessages.append(dictObj); } }; /** * Get the i18n object in charge of the error messages * * @method getI18n * @return {Ink.Util.I18n} The i18n object the FormValidator is using. */ FormValidator.getI18n = function () { return validationMessages; }; /** * Sets the I18n object for validation error messages * * @method setI18n * @param {Ink.Util.I18n} i18n The I18n object. */ FormValidator.setI18n = function (i18n) { validationMessages = i18n; }; /** * Add to the I18n dictionary. See `Ink.Util.I18n.append()` documentation. * * @method AppendI18n */ FormValidator.appendI18n = function () { validationMessages.append.apply(validationMessages, [].slice.call(arguments)); }; /** * Sets the language of the error messages. pt_PT and en_US are available, but you can add new languages by using append() * * See the `Ink.Util.I18n.lang()` setter * * @method setLanguage * @param language The language to set i18n to. */ FormValidator.setLanguage = function (language) { validationMessages.lang(language); }; /** * Method used to get the existing defined validation functions * * @method getRules * @return {Object} Object with the rules defined * @public * @static */ FormValidator.getRules = function(){ return validationFunctions; }; FormValidator.prototype = { _init: function(){ }, /** * Function that searches for the elements of the form, based in the * this._options.searchFor configuration. * * @method getElements * @return {Object} An object with the elements in the form, indexed by name/id * @public */ getElements: function(){ this._formElements = {}; var formElements = Selector.select( this._options.searchFor, this._rootElement ); if( formElements.length ){ var i, element; for( i=0; i<formElements.length; i+=1 ){ element = formElements[i]; var dataAttrs = Element.data( element ); if( !("rules" in dataAttrs) ){ continue; } var options = { form: this }; var key; if( ("name" in element) && element.name ){ key = element.name; } else if( ("id" in element) && element.id ){ key = element.id; } else { key = 'element_' + Math.floor(Math.random()*100); element.id = key; } if( !(key in this._formElements) ){ this._formElements[key] = [ new FormElement( element, options ) ]; } else { this._formElements[key].push( new FormElement( element, options ) ); } } } return this._formElements; }, /** * Runs the validate function of each FormElement in the this._formElements * object. * Also, based on the this._options.beforeValidation, this._options.onError * and this._options.onSuccess, this callbacks are executed when defined. * * @method validate * @param {Event} event window.event object * @return {Boolean} * @public */ validate: function( event ){ Event.stop(event); if( typeof this._options.beforeValidation === 'function' ){ this._options.beforeValidation(); } this.getElements(); var errorElements = []; for( var key in this._formElements ){ if( this._formElements.hasOwnProperty(key) ){ for( var counter = 0; counter < this._formElements[key].length; counter+=1 ){ if( !this._formElements[key][counter].validate() ) { errorElements.push(this._formElements[key][counter]); } } } } if( errorElements.length === 0 ){ if( typeof this._options.onSuccess === 'function' ){ this._options.onSuccess(); } return true; } else { if( typeof this._options.onError === 'function' ){ this._options.onError( errorElements ); } InkArray.each( this._markedErrorElements, Ink.bind(Css.removeClassName, Css, 'validation')); InkArray.each( this._markedErrorElements, Ink.bind(Css.removeClassName, Css, 'error')); InkArray.each( this._errorMessages, Element.remove); this._errorMessages = []; this._markedErrorElements = []; InkArray.each( errorElements, Ink.bind(function( formElement ){ var controlGroupElement; var controlElement; if( Css.hasClassName(formElement.getElement(),'control-group') ){ controlGroupElement = formElement.getElement(); controlElement = Ink.s('.control',formElement.getElement()); } else { controlGroupElement = Element.findUpwardsByClass(formElement.getElement(),'control-group'); controlElement = Element.findUpwardsByClass(formElement.getElement(),'control'); } if (!controlElement || !controlGroupElement) { controlElement = controlGroupElement = formElement.getElement(); } Css.addClassName( controlGroupElement, 'validation' ); Css.addClassName( controlGroupElement, 'error' ); this._markedErrorElements.push(controlGroupElement); var paragraph = document.createElement('p'); Css.addClassName(paragraph,'tip'); Element.insertAfter(paragraph, controlElement); var errors = formElement.getErrors(); var errorArr = []; for (var k in errors) { if (errors.hasOwnProperty(k)) { errorArr.push(errors[k]); } } paragraph.innerHTML = errorArr.join('<br/>'); this._errorMessages.push(paragraph); }, this)); return false; } } }; /** * Returns the FormValidator's Object */ return FormValidator; }); /** * @module Ink.UI.FormValidator_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.FormValidator', '1', ['Ink.Dom.Css_1','Ink.Util.Validator_1'], function( Css, InkValidator ) { 'use strict'; /** * @class Ink.UI.FormValidator * @version 1 */ var FormValidator = { /** * Specifies the version of the component * * @property version * @type {String} * @readOnly * @public */ version: '1', /** * Available flags to use in the validation process. * The keys are the 'rules', and their values are objects with the key 'msg', determining * what is the error message. * * @property _flagMap * @type {Object} * @readOnly * @private */ _flagMap: { //'ink-fv-required': {msg: 'Campo obrigat&oacute;rio'}, 'ink-fv-required': {msg: 'Required field'}, //'ink-fv-email': {msg: 'E-mail inv&aacute;lido'}, 'ink-fv-email': {msg: 'Invalid e-mail address'}, //'ink-fv-url': {msg: 'URL inv&aacute;lido'}, 'ink-fv-url': {msg: 'Invalid URL'}, //'ink-fv-number': {msg: 'N&uacute;mero inv&aacute;lido'}, 'ink-fv-number': {msg: 'Invalid number'}, //'ink-fv-phone_pt': {msg: 'N&uacute;mero de telefone inv&aacute;lido'}, 'ink-fv-phone_pt': {msg: 'Invalid phone number'}, //'ink-fv-phone_cv': {msg: 'N&uacute;mero de telefone inv&aacute;lido'}, 'ink-fv-phone_cv': {msg: 'Invalid phone number'}, //'ink-fv-phone_mz': {msg: 'N&uacute;mero de telefone inv&aacute;lido'}, 'ink-fv-phone_mz': {msg: 'Invalid phone number'}, //'ink-fv-phone_ao': {msg: 'N&uacute;mero de telefone inv&aacute;lido'}, 'ink-fv-phone_ao': {msg: 'Invalid phone number'}, //'ink-fv-date': {msg: 'Data inv&aacute;lida'}, 'ink-fv-date': {msg: 'Invalid date'}, //'ink-fv-confirm': {msg: 'Confirma&ccedil;&atilde;o inv&aacute;lida'}, 'ink-fv-confirm': {msg: 'Confirmation does not match'}, 'ink-fv-custom': {msg: ''} }, /** * This property holds all form elements for later validation * * @property elements * @type {Object} * @public */ elements: {}, /** * This property holds the objects needed to cross-check for the 'confirm' rule * * @property confirmElms * @type {Object} * @public */ confirmElms: {}, /** * This property holds the previous elements in the confirmElms property, but with a * true/false specifying if it has the class ink-fv-confirm. * * @property hasConfirm * @type {Object} */ hasConfirm: {}, /** * Defined class name to use in error messages label * * @property _errorClassName * @type {String} * @readOnly * @private */ _errorClassName: 'tip', /** * @property _errorValidationClassName * @type {String} * @readOnly * @private */ _errorValidationClassName: 'validaton', /** * @property _errorTypeWarningClassName * @type {String} * @readOnly * @private */ _errorTypeWarningClassName: 'warning', /** * @property _errorTypeErrorClassName * @type {String} * @readOnly * @private */ _errorTypeErrorClassName: 'error', /** * Check if a form is valid or not * * @method validate * @param {DOMElement|String} elm DOM form element or form id * @param {Object} options Options for * @param {Function} [options.onSuccess] function to run when form is valid * @param {Function} [options.onError] function to run when form is not valid * @param {Array} [options.customFlag] custom flags to use to validate form fields * @public * @return {Boolean} */ validate: function(elm, options) { this._free(); options = Ink.extendObj({ onSuccess: false, onError: false, customFlag: false, confirmGroup: [] }, options || {}); if(typeof(elm) === 'string') { elm = document.getElementById(elm); } if(elm === null){ return false; } this.element = elm; if(typeof(this.element.id) === 'undefined' || this.element.id === null || this.element.id === '') { // generate a random ID this.element.id = 'ink-fv_randomid_'+(Math.round(Math.random() * 99999)); } this.custom = options.customFlag; this.confirmGroup = options.confirmGroup; var fail = this._validateElements(); if(fail.length > 0) { if(options.onError) { options.onError(fail); } else { this._showError(elm, fail); } return false; } else { if(!options.onError) { this._clearError(elm); } this._clearCache(); if(options.onSuccess) { options.onSuccess(); } return true; } }, /** * Reset previously generated validation errors * * @method reset * @public */ reset: function() { this._clearError(); this._clearCache(); }, /** * Cleans the object * * @method _free * @private */ _free: function() { this.element = null; //this.elements = []; this.custom = false; this.confirmGroup = false; }, /** * Cleans the properties responsible for caching * * @method _clearCache * @private */ _clearCache: function() { this.element = null; this.elements = []; this.custom = false; this.confirmGroup = false; }, /** * Gets the form elements and stores them in the caching properties * * @method _getElements * @private */ _getElements: function() { //this.elements = []; // if(typeof(this.elements[this.element.id]) !== 'undefined') { // return; // } this.elements[this.element.id] = []; this.confirmElms[this.element.id] = []; //console.log(this.element); //console.log(this.element.elements); var formElms = this.element.elements; var curElm = false; for(var i=0, totalElm = formElms.length; i < totalElm; i++) { curElm = formElms[i]; if(curElm.getAttribute('type') !== null && curElm.getAttribute('type').toLowerCase() === 'radio') { if(this.elements[this.element.id].length === 0 || ( curElm.getAttribute('type') !== this.elements[this.element.id][(this.elements[this.element.id].length - 1)].getAttribute('type') && curElm.getAttribute('name') !== this.elements[this.element.id][(this.elements[this.element.id].length - 1)].getAttribute('name') )) { for(var flag in this._flagMap) { if(Css.hasClassName(curElm, flag)) { this.elements[this.element.id].push(curElm); break; } } } } else { for(var flag2 in this._flagMap) { if(Css.hasClassName(curElm, flag2) && flag2 !== 'ink-fv-confirm') { /*if(flag2 == 'ink-fv-confirm') { this.confirmElms[this.element.id].push(curElm); this.hasConfirm[this.element.id] = true; }*/ this.elements[this.element.id].push(curElm); break; } } if(Css.hasClassName(curElm, 'ink-fv-confirm')) { this.confirmElms[this.element.id].push(curElm); this.hasConfirm[this.element.id] = true; } } } //debugger; }, /** * Runs the validation for each element * * @method _validateElements * @private */ _validateElements: function() { var oGroups; this._getElements(); //console.log('HAS CONFIRM', this.hasConfirm); if(typeof(this.hasConfirm[this.element.id]) !== 'undefined' && this.hasConfirm[this.element.id] === true) { oGroups = this._makeConfirmGroups(); } var errors = []; var curElm = false; var customErrors = false; var inArray; for(var i=0, totalElm = this.elements[this.element.id].length; i < totalElm; i++) { inArray = false; curElm = this.elements[this.element.id][i]; if(!curElm.disabled) { for(var flag in this._flagMap) { if(Css.hasClassName(curElm, flag)) { if(flag !== 'ink-fv-custom' && flag !== 'ink-fv-confirm') { if(!this._isValid(curElm, flag)) { if(!inArray) { errors.push({elm: curElm, errors:[flag]}); inArray = true; } else { errors[(errors.length - 1)].errors.push(flag); } } } else if(flag !== 'ink-fv-confirm'){ customErrors = this._isCustomValid(curElm); if(customErrors.length > 0) { errors.push({elm: curElm, errors:[flag], custom: customErrors}); } } else if(flag === 'ink-fv-confirm'){ } } } } } errors = this._validateConfirmGroups(oGroups, errors); //console.log(InkDumper.returnDump(errors)); return errors; }, /** * Runs the 'confirm' validation for each group of elements * * @method _validateConfirmGroups * @param {Array} oGroups Array/Object that contains the group of confirm objects * @param {Array} errors Array that will store the errors * @private * @return {Array} Array of errors that was passed as 2nd parameter (either changed, or not, depending if errors were found). */ _validateConfirmGroups: function(oGroups, errors) { //console.log(oGroups); var curGroup = false; for(var i in oGroups) { if (oGroups.hasOwnProperty(i)) { curGroup = oGroups[i]; if(curGroup.length === 2) { if(curGroup[0].value !== curGroup[1].value) { errors.push({elm:curGroup[1], errors:['ink-fv-confirm']}); } } } } return errors; }, /** * Creates the groups of 'confirm' objects * * @method _makeConfirmGroups * @private * @return {Array|Boolean} Returns the array of confirm elements or false on error. */ _makeConfirmGroups: function() { var oGroups; if(this.confirmGroup && this.confirmGroup.length > 0) { oGroups = {}; var curElm = false; var curGroup = false; //this.confirmElms[this.element.id]; for(var i=0, total=this.confirmElms[this.element.id].length; i < total; i++) { curElm = this.confirmElms[this.element.id][i]; for(var j=0, totalG=this.confirmGroup.length; j < totalG; j++) { curGroup = this.confirmGroup[j]; if(Css.hasClassName(curElm, curGroup)) { if(typeof(oGroups[curGroup]) === 'undefined') { oGroups[curGroup] = [curElm]; } else { oGroups[curGroup].push(curElm); } } } } return oGroups; } else { if(this.confirmElms[this.element.id].length === 2) { oGroups = { "ink-fv-confirm": [ this.confirmElms[this.element.id][0], this.confirmElms[this.element.id][1] ] }; } return oGroups; } return false; }, /** * Validates an element with a custom validation * * @method _isCustomValid * @param {DOMElemenmt} elm Element to be validated * @private * @return {Array} Array of errors. If no errors are found, results in an empty array. */ _isCustomValid: function(elm) { var customErrors = []; var curFlag = false; for(var i=0, tCustom = this.custom.length; i < tCustom; i++) { curFlag = this.custom[i]; if(Css.hasClassName(elm, curFlag.flag)) { if(!curFlag.callback(elm, curFlag.msg)) { customErrors.push({flag: curFlag.flag, msg: curFlag.msg}); } } } return customErrors; }, /** * Runs the normal validation functions for a specific element * * @method _isValid * @param {DOMElement} elm DOMElement that will be validated * @param {String} fieldType Rule to be validated. This must be one of the keys present in the _flagMap property. * @private * @return {Boolean} The result of the validation. */ _isValid: function(elm, fieldType) { switch(fieldType) { case 'ink-fv-required': if(elm.nodeName.toLowerCase() === 'select') { if(elm.selectedIndex > 0) { return true; } else { return false; } } if(elm.getAttribute('type') !== 'checkbox' && elm.getAttribute('type') !== 'radio') { if(this._trim(elm.value) !== '') { return true; } } else if(elm.getAttribute('type') === 'checkbox') { if(elm.checked === true) { return true; } } else if(elm.getAttribute('type') === 'radio') { // get top radio var aFormRadios = elm.form[elm.name]; if(typeof(aFormRadios.length) === 'undefined') { aFormRadios = [aFormRadios]; } var isChecked = false; for(var i=0, totalRadio = aFormRadios.length; i < totalRadio; i++) { if(aFormRadios[i].checked === true) { isChecked = true; } } return isChecked; } break; case 'ink-fv-email': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { if(InkValidator.mail(elm.value)) { return true; } } break; case 'ink-fv-url': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { if(InkValidator.url(elm.value)) { return true; } } break; case 'ink-fv-number': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { if(!isNaN(Number(elm.value))) { return true; } } break; case 'ink-fv-phone_pt': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { if(InkValidator.isPTPhone(elm.value)) { return true; } } break; case 'ink-fv-phone_cv': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { if(InkValidator.isCVPhone(elm.value)) { return true; } } break; case 'ink-fv-phone_ao': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { if(InkValidator.isAOPhone(elm.value)) { return true; } } break; case 'ink-fv-phone_mz': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { if(InkValidator.isMZPhone(elm.value)) { return true; } } break; case 'ink-fv-date': if(this._trim(elm.value) === '') { if(Css.hasClassName(elm, 'ink-fv-required')) { return false; } else { return true; } } else { var Element = Ink.getModule('Ink.Dom.Element',1); var dataset = Element.data( elm ); var validFormat = 'yyyy-mm-dd'; if( Css.hasClassName(elm, 'ink-datepicker') && ("format" in dataset) ){ validFormat = dataset.format; } else if( ("validFormat" in dataset) ){ validFormat = dataset.validFormat; } if( !(validFormat in InkValidator._dateParsers ) ){ var validValues = []; for( var val in InkValidator._dateParsers ){ if (InkValidator._dateParsers.hasOwnProperty(val)) { validValues.push(val); } } throw "The attribute data-valid-format must be one of the following values: " + validValues.join(','); } return InkValidator.isDate( validFormat, elm.value ); } break; case 'ink-fv-custom': break; } return false; }, /** * Makes the necessary changes to the markup to show the errors of a given element * * @method _showError * @param {DOMElement} formElm The form element to be changed to show the errors * @param {Array} aFail An array with the errors found. * @private */ _showError: function(formElm, aFail) { this._clearError(formElm); //ink-warning-field //console.log(aFail); var curElm = false; for(var i=0, tFail = aFail.length; i < tFail; i++) { curElm = aFail[i].elm; if(curElm.getAttribute('type') !== 'radio') { var newLabel = document.createElement('p'); //newLabel.setAttribute('for',curElm.id); //newLabel.className = this._errorClassName; //newLabel.className += ' ' + this._errorTypeErrorClassName; Css.addClassName(newLabel, this._errorClassName); Css.addClassName(newLabel, this._errorTypeErrorClassName); if(aFail[i].errors[0] !== 'ink-fv-custom') { newLabel.innerHTML = this._flagMap[aFail[i].errors[0]].msg; } else { newLabel.innerHTML = aFail[i].custom[0].msg; } if(curElm.getAttribute('type') !== 'checkbox') { curElm.nextSibling.parentNode.insertBefore(newLabel, curElm.nextSibling); if(Css.hasClassName(curElm.parentNode, 'control')) { Css.addClassName(curElm.parentNode.parentNode, 'validation'); if(aFail[i].errors[0] === 'ink-fv-required') { Css.addClassName(curElm.parentNode.parentNode, 'error'); } else { Css.addClassName(curElm.parentNode.parentNode, 'warning'); } } } else { /* // TODO checkbox... does not work with this CSS curElm.parentNode.appendChild(newLabel); if(Css.hasClassName(curElm.parentNode.parentNode, 'control-group')) { Css.addClassName(curElm.parentNode.parentNode, 'control'); Css.addClassName(curElm.parentNode.parentNode, 'validation'); Css.addClassName(curElm.parentNode.parentNode, 'error'); }*/ } } else { if(Css.hasClassName(curElm.parentNode.parentNode, 'control-group')) { Css.addClassName(curElm.parentNode.parentNode, 'validation'); Css.addClassName(curElm.parentNode.parentNode, 'error'); } } } }, /** * Clears the error of a given element. Normally executed before any validation, for all elements, as a reset. * * @method _clearErrors * @param {DOMElement} formElm Form element to be cleared. * @private */ _clearError: function(formElm) { //return; var aErrorLabel = formElm.getElementsByTagName('p'); var curElm = false; for(var i = (aErrorLabel.length - 1); i >= 0; i--) { curElm = aErrorLabel[i]; if(Css.hasClassName(curElm, this._errorClassName)) { if(Css.hasClassName(curElm.parentNode, 'control')) { Css.removeClassName(curElm.parentNode.parentNode, 'validation'); Css.removeClassName(curElm.parentNode.parentNode, 'error'); Css.removeClassName(curElm.parentNode.parentNode, 'warning'); } if(Css.hasClassName(curElm,'tip') && Css.hasClassName(curElm,'error')){ curElm.parentNode.removeChild(curElm); } } } var aErrorLabel2 = formElm.getElementsByTagName('ul'); for(i = (aErrorLabel2.length - 1); i >= 0; i--) { curElm = aErrorLabel2[i]; if(Css.hasClassName(curElm, 'control-group')) { Css.removeClassName(curElm, 'validation'); Css.removeClassName(curElm, 'error'); } } }, /** * Removes unnecessary spaces to the left or right of a string * * @method _trim * @param {String} stri String to be trimmed * @private * @return {String|undefined} String trimmed. */ _trim: function(str) { if(typeof(str) === 'string') { return str.replace(/^\s+|\s+$|\n+$/g, ''); } } }; return FormValidator; }); /** * @module Ink.UI.Droppable_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule("Ink.UI.Droppable","1",["Ink.Dom.Element_1", "Ink.Dom.Event_1", "Ink.Dom.Css_1", "Ink.UI.Aux_1", "Ink.Util.Array_1", "Ink.Dom.Selector_1"], function( InkElement, InkEvent, Css, Aux, InkArray, Selector) { // Higher order functions var hAddClassName = function (element) { return function (className) {return Css.addClassName(element, className);}; }; var hRemoveClassName = function (element) { return function (className) {return Css.removeClassName(element, className);}; }; /** * @class Ink.UI.Droppable * @version 1 * @static */ var Droppable = { /** * Flag that determines if it's in debug mode or not * * @property debug * @type {Boolean} * @private */ debug: false, /** * Array with the data of each element (`{element: ..., data: ..., options: ...}`) * * @property _droppables * @type {Array} * @private */ _droppables: [], /** * Array of data for each draggable. (`{element: ..., data: ...}`) * * @property _draggables * @type {Array} * @private */ _draggables: [], /** * Makes an element droppable and adds it to the stack of droppable elements. * Can consider it a constructor of droppable elements, but where no Droppable object is returned. * * In the following arguments, any events/callbacks you may pass, can be either functions or strings. If the 'move' or 'copy' strings are passed, the draggable gets moved into this droppable. If 'revert' is passed, an acceptable droppable is moved back to the element it came from. * * @method add * @param {String|DOMElement} element Target element * @param {Object} [options] options object * @param {String} [options.hoverClass] Classname(s) applied when an acceptable draggable element is hovering the element * @param {String} [options.accept] Selector for choosing draggables which can be dropped in this droppable. * @param {Function} [options.onHover] callback called when an acceptable draggable element is hovering the droppable. Gets the draggable and the droppable element as parameters. * @param {Function|String} [options.onDrop] callback called when an acceptable draggable element is dropped. Gets the draggable, the droppable and the event as parameters. * @param {Function|String} [options.onDropOut] callback called when a droppable is dropped outside this droppable. Gets the draggable, the droppable and the event as parameters. (see above for string options). * @public * * @example * * <style type="text/css"> * .hover { * border: 1px solid red; * } * .left, .right { * float: left; width: 50%; * outline: 1px solid gray; * min-height: 2em; * } * </style> * <ul class="left"> * <li>Draggable 1</li> * <li>Draggable 2</li> * <li>Draggable 3</li> * </ul> * <ul class="right"> * </ul> * <script type="text/javascript"> * Ink.requireModules(['Ink.UI.Draggable_1', 'Ink.UI.Droppable_1'], function (Draggable, Droppable) { * new Draggable('.left li:eq(0)', {}); * new Draggable('.left li:eq(1)', {}); * new Draggable('.left li:eq(2)', {}); * Droppable.add('.left', {onDrop: 'move', onDropOut: 'revert'}); * Droppable.add('.right', {onDrop: 'move', onDropOut: 'revert'}); * }) * </script> * */ add: function(element, options) { element = Aux.elOrSelector(element, 'Droppable.add target element'); var opt = Ink.extendObj( { hoverClass: options.hoverclass /* old name */ || false, accept: false, onHover: false, onDrop: false, onDropOut: false }, options || {}, InkElement.data(element)); if (typeof opt.hoverClass === 'string') { opt.hoverClass = opt.hoverClass.split(/\s+/); } function cleanStyle(draggable) { draggable.style.position = 'inherit'; } var that = this; var namedEventHandlers = { move: function (draggable, droppable, event) { cleanStyle(draggable); droppable.appendChild(draggable); }, copy: function (draggable, droppable, event) { cleanStyle(draggable); droppable.appendChild(draggable.cloneNode); }, revert: function (draggable, droppable, event) { that._findDraggable(draggable).originalParent.appendChild(draggable); cleanStyle(draggable); } }; var name; if (typeof opt.onHover === 'string') { name = opt.onHover; opt.onHover = namedEventHandlers[name]; if (opt.onHover === undefined) { throw new Error('Unknown hover event handler: ' + name); } } if (typeof opt.onDrop === 'string') { name = opt.onDrop; opt.onDrop = namedEventHandlers[name]; if (opt.onDrop === undefined) { throw new Error('Unknown drop event handler: ' + name); } } if (typeof opt.onDropOut === 'string') { name = opt.onDropOut; opt.onDropOut = namedEventHandlers[name]; if (opt.onDropOut === undefined) { throw new Error('Unknown dropOut event handler: ' + name); } } var elementData = { element: element, data: {}, options: opt }; this._droppables.push(elementData); this._update(elementData); }, /** * find droppable data about `element`. this data is added in `.add` * * @method _findData * @param {DOMElement} element Needle * @return {object} Droppable data of the element * @private */ _findData: function (element) { var elms = this._droppables; for (var i = 0, len = elms.length; i < len; i++) { if (elms[i].element === element) { return elms[i]; } } }, /** * Find draggable data about `element` * * @method _findDraggable * @param {DOMElement} element Needle * @return {Object} Draggable data queried * @private */ _findDraggable: function (element) { var elms = this._draggables; for (var i = 0, len = elms.length; i < len; i++) { if (elms[i].element === element) { return elms[i]; } } }, /** * Invoke every time a drag starts * * @method updateAll * @private */ updateAll: function() { InkArray.each(this._droppables, Droppable._update); }, /** * Updates location and size of droppable element * * @method update * @param {String|DOMElement} element - target element * @private */ update: function(element) { this._update(this._findData(element)); }, _update: function(elementData) { var data = elementData.data; var element = elementData.element; data.left = InkElement.offsetLeft(element); data.top = InkElement.offsetTop( element); data.right = data.left + InkElement.elementWidth( element); data.bottom = data.top + InkElement.elementHeight(element); }, /** * Removes an element from the droppable stack and removes the droppable behavior * * @method remove * @param {String|DOMElement} elOrSelector Droppable element to disable. * @return {Boolean} Whether the object was found and deleted * @public */ remove: function(el) { el = Aux.elOrSelector(el); var len = this._droppables.length; for (var i = 0; i < len; i++) { if (this._droppables[i].element === el) { this._droppables.splice(i, 1); break; } } return len !== this._droppables.length; }, /** * Method called by a draggable to execute an action on a droppable * * @method action * @param {Object} coords coordinates where the action happened * @param {String} type type of action. drag or drop. * @param {Object} ev Event object * @param {Object} draggable draggable element * @private */ action: function(coords, type, ev, draggable) { // check all droppable elements InkArray.each(this._droppables, Ink.bind(function(elementData) { var data = elementData.data; var opt = elementData.options; var element = elementData.element; if (opt.accept && !Selector.matches(opt.accept, [draggable]).length) { return; } if (type === 'drag' && !this._findDraggable(draggable)) { this._draggables.push({ element: draggable, originalParent: draggable.parentNode }); } // check if our draggable is over our droppable if (coords.x >= data.left && coords.x <= data.right && coords.y >= data.top && coords.y <= data.bottom) { // INSIDE if (type === 'drag') { if (opt.hoverClass) { InkArray.each(opt.hoverClass, hAddClassName(element)); } if (opt.onHover) { opt.onHover(draggable, element); } } else if (type === 'drop') { if (opt.hoverClass) { InkArray.each(opt.hoverClass, hRemoveClassName(element)); } if (opt.onDrop) { opt.onDrop(draggable, element, ev); } } } else { // OUTSIDE if (type === 'drag' && opt.hoverClass) { InkArray.each(opt.hoverClass, hRemoveClassName(element)); } else if (type === 'drop') { if(opt.onDropOut){ opt.onDropOut(draggable, element, ev); } } } }, this)); } }; return Droppable; }); /* * @module Ink.UI.Draggable_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule("Ink.UI.Draggable","1",["Ink.Dom.Element_1", "Ink.Dom.Event_1", "Ink.Dom.Css_1", "Ink.Dom.Browser_1", "Ink.Dom.Selector_1", "Ink.UI.Aux_1"],function( InkElement, InkEvent, Css, Browser, Selector, Aux) { var x = 0, y = 1; // For accessing coords in [x, y] arrays // Get a value between two boundaries function between (val, min, max) { val = Math.min(val, max); val = Math.max(val, min); return val; } /** * @class Ink.UI.Draggable * @version 1 * @constructor * @param {String|DOMElement} target Target element. * @param {Object} [options] Optional object for configuring the component * @param {String} [options.constraint] Movement constraint. None by default. Can be `vertical`, `horizontal`, or `both`. * @param {String|DomElement} [options.constraintElm] Constrain dragging to be within this element. None by default. * @param {Number} [options.top,left,right,bottom] Limits for constraining draggable movement. * @param {String|DOMElement} [options.handle] if specified, this element will be used as a handle for dragging. * @param {Boolean} [options.revert] if true, reverts the draggable to the original position when dragging stops * @param {String} [options.cursor] cursor type (CSS `cursor` value) used when the mouse is over the draggable object * @param {Number} [options.zIndex] zindex applied to the draggable element while dragged * @param {Number} [options.fps] if defined, on drag will run every n frames per second only * @param {DomElement} [options.droppableProxy] if set, a shallow copy of the droppableProxy will be put on document.body with transparent bg * @param {String} [options.mouseAnchor] defaults to mouse cursor. can be 'left|center|right top|center|bottom' * @param {String} [options.dragClass='drag'] class to add when the draggable is being dragged. * @param {Function} [options.onStart] callback called when dragging starts * @param {Function} [options.onEnd] callback called when dragging stops * @param {Function} [options.onDrag] callback called while dragging, prior to position updates * @param {Function} [options.onChange] callback called while dragging, after position updates * @example * Ink.requireModules( ['Ink.UI.Draggable_1'], function( Draggable ){ * new Draggable( '#myElementId' ); * }); */ var Draggable = function(element, options) { this.init(element, options); }; Draggable.prototype = { /** * Init function called by the constructor * * @method _init * @param {String|DOMElement} element ID of the element or DOM Element. * @param {Object} [options] Options object for configuration of the module. * @private */ init: function(element, options) { var o = Ink.extendObj( { constraint: false, constraintElm: false, top: false, right: false, bottom: false, left: false, handle: options.handler /* old option name */ || false, revert: false, cursor: 'move', zindex: options.zindex /* old option name */ || 9999, dragClass: 'drag', onStart: false, onEnd: false, onDrag: false, onChange: false, droppableProxy: false, mouseAnchor: undefined, skipChildren: true, fps: 100, debug: false }, options || {}, InkElement.data(element)); this.options = o; this.element = Aux.elOrSelector(element); this.constraintElm = o.constraintElm && Aux.elOrSelector(o.constraintElm); this.handle = false; this.elmStartPosition = false; this.active = false; this.dragged = false; this.prevCoords = false; this.placeholder = false; this.position = false; this.zindex = false; this.firstDrag = true; if (o.fps) { this.deltaMs = 1000 / o.fps; this.lastRunAt = 0; } this.handlers = {}; this.handlers.start = Ink.bindEvent(this._onStart,this); this.handlers.dragFacade = Ink.bindEvent(this._onDragFacade,this); this.handlers.drag = Ink.bindEvent(this._onDrag,this); this.handlers.end = Ink.bindEvent(this._onEnd,this); this.handlers.selectStart = function(event) { InkEvent.stop(event); return false; }; // set handle this.handle = (this.options.handle) ? Aux.elOrSelector(this.options.handle) : this.element; this.handle.style.cursor = o.cursor; InkEvent.observe(this.handle, 'touchstart', this.handlers.start); InkEvent.observe(this.handle, 'mousedown', this.handlers.start); if (Browser.IE) { InkEvent.observe(this.element, 'selectstart', this.handlers.selectStart); } }, /** * Removes the ability of the element of being dragged * * @method destroy * @public */ destroy: function() { InkEvent.stopObserving(this.handle, 'touchstart', this.handlers.start); InkEvent.stopObserving(this.handle, 'mousedown', this.handlers.start); if (Browser.IE) { InkEvent.stopObserving(this.element, 'selectstart', this.handlers.selectStart); } }, /** * Gets coordinates for a given event (with added page scroll) * * @method _getCoords * @param {Object} e window.event object. * @return {Array} Array where the first position is the x coordinate, the second is the y coordinate * @private */ _getCoords: function(e) { var ps = [InkElement.scrollWidth(), InkElement.scrollHeight()]; return { x: (e.touches ? e.touches[0].clientX : e.clientX) + ps[x], y: (e.touches ? e.touches[0].clientY : e.clientY) + ps[y] }; }, /** * Clones src element's relevant properties to dst * * @method _cloneStyle * @param {DOMElement} src Element from where we're getting the styles * @param {DOMElement} dst Element where we're placing the styles. * @private */ _cloneStyle: function(src, dst) { dst.className = src.className; dst.style.borderWidth = '0'; dst.style.padding = '0'; dst.style.position = 'absolute'; dst.style.width = InkElement.elementWidth(src) + 'px'; dst.style.height = InkElement.elementHeight(src) + 'px'; dst.style.left = InkElement.elementLeft(src) + 'px'; dst.style.top = InkElement.elementTop(src) + 'px'; dst.style.cssFloat = Css.getStyle(src, 'float'); dst.style.display = Css.getStyle(src, 'display'); }, /** * onStart event handler * * @method _onStart * @param {Object} e window.event object * @return {Boolean|void} In some cases return false. Otherwise is void * @private */ _onStart: function(e) { if (!this.active && InkEvent.isLeftClick(e) || typeof e.button === 'undefined') { var tgtEl = InkEvent.element(e); if (this.options.skipChildren && tgtEl !== this.handle) { return; } InkEvent.stop(e); Css.addClassName(this.element, this.options.dragClass); this.elmStartPosition = [ InkElement.elementLeft(this.element), InkElement.elementTop( this.element) ]; var pos = [ parseInt(Css.getStyle(this.element, 'left'), 10), parseInt(Css.getStyle(this.element, 'top'), 10) ]; var dims = InkElement.elementDimensions(this.element); this.originalPosition = [ pos[x] ? pos[x]: null, pos[y] ? pos[y] : null ]; this.delta = this._getCoords(e); // mouse coords at beginning of drag this.active = true; this.position = Css.getStyle(this.element, 'position'); this.zindex = Css.getStyle(this.element, 'zIndex'); var div = document.createElement('div'); div.style.position = this.position; div.style.width = dims[x] + 'px'; div.style.height = dims[y] + 'px'; div.style.marginTop = Css.getStyle(this.element, 'margin-top'); div.style.marginBottom = Css.getStyle(this.element, 'margin-bottom'); div.style.marginLeft = Css.getStyle(this.element, 'margin-left'); div.style.marginRight = Css.getStyle(this.element, 'margin-right'); div.style.borderWidth = '0'; div.style.padding = '0'; div.style.cssFloat = Css.getStyle(this.element, 'float'); div.style.display = Css.getStyle(this.element, 'display'); div.style.visibility = 'hidden'; this.delta2 = [ this.delta.x - this.elmStartPosition[x], this.delta.y - this.elmStartPosition[y] ]; // diff between top-left corner of obj and mouse if (this.options.mouseAnchor) { var parts = this.options.mouseAnchor.split(' '); var ad = [dims[x], dims[y]]; // starts with 'right bottom' if (parts[0] === 'left') { ad[x] = 0; } else if(parts[0] === 'center') { ad[x] = parseInt(ad[x]/2, 10); } if (parts[1] === 'top') { ad[y] = 0; } else if(parts[1] === 'center') { ad[y] = parseInt(ad[y]/2, 10); } this.applyDelta = [this.delta2[x] - ad[x], this.delta2[y] - ad[y]]; } var dragHandlerName = this.options.fps ? 'dragFacade' : 'drag'; this.placeholder = div; if (this.options.onStart) { this.options.onStart(this.element, e); } if (this.options.droppableProxy) { // create new transparent div to optimize DOM traversal during drag this.proxy = document.createElement('div'); dims = [ window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight ]; var fs = this.proxy.style; fs.width = dims[x] + 'px'; fs.height = dims[y] + 'px'; fs.position = 'fixed'; fs.left = '0'; fs.top = '0'; fs.zIndex = this.options.zindex + 1; fs.backgroundColor = '#FF0000'; Css.setOpacity(this.proxy, 0); var firstEl = document.body.firstChild; while (firstEl && firstEl.nodeType !== 1) { firstEl = firstEl.nextSibling; } document.body.insertBefore(this.proxy, firstEl); InkEvent.observe(this.proxy, 'mousemove', this.handlers[dragHandlerName]); InkEvent.observe(this.proxy, 'touchmove', this.handlers[dragHandlerName]); } else { InkEvent.observe(document, 'mousemove', this.handlers[dragHandlerName]); } this.element.style.position = 'absolute'; this.element.style.zIndex = this.options.zindex; this.element.parentNode.insertBefore(this.placeholder, this.element); this._onDrag(e); InkEvent.observe(document, 'mouseup', this.handlers.end); InkEvent.observe(document, 'touchend', this.handlers.end); return false; } }, /** * Function that gets the timestamp of the current run from time to time. (FPS) * * @method _onDragFacade * @param {Object} window.event object. * @private */ _onDragFacade: function(e) { var now = +new Date(); if (!this.lastRunAt || now > this.lastRunAt + this.deltaMs) { this.lastRunAt = now; this._onDrag(e); } }, /** * Function that handles the dragging movement * * @method _onDrag * @param {Object} window.event object. * @private */ _onDrag: function(e) { if (this.active) { InkEvent.stop(e); this.dragged = true; var mouseCoords = this._getCoords(e), mPosX = mouseCoords.x, mPosY = mouseCoords.y, o = this.options, newX = false, newY = false; if (this.prevCoords && mPosX !== this.prevCoords.x || mPosY !== this.prevCoords.y) { if (o.onDrag) { o.onDrag(this.element, e); } this.prevCoords = mouseCoords; newX = this.elmStartPosition[x] + mPosX - this.delta.x; newY = this.elmStartPosition[y] + mPosY - this.delta.y; var draggableSize = InkElement.elementDimensions(this.element); if (this.constraintElm) { var offset = InkElement.offset(this.constraintElm); var size = InkElement.elementDimensions(this.constraintElm); var constTop = offset[y] + (o.top || 0), constBottom = offset[y] + size[y] - (o.bottom || 0), constLeft = offset[x] + (o.left || 0), constRight = offset[x] + size[x] - (o.right || 0); newY = between(newY, constTop, constBottom - draggableSize[y]); newX = between(newX, constLeft, constRight - draggableSize[x]); } else if (o.constraint) { var right = o.right === false ? InkElement.pageWidth() - draggableSize[x] : o.right, left = o.left === false ? 0 : o.left, top = o.top === false ? 0 : o.top, bottom = o.bottom === false ? InkElement.pageHeight() - draggableSize[y] : o.bottom; if (o.constraint === 'horizontal' || o.constraint === 'both') { newX = between(newX, left, right); } if (o.constraint === 'vertical' || o.constraint === 'both') { newY = between(newY, top, bottom); } } var Droppable = Ink.getModule('Ink.UI.Droppable_1'); if (this.firstDrag) { if (Droppable) { Droppable.updateAll(); } /*this.element.style.position = 'absolute'; this.element.style.zIndex = this.options.zindex; this.element.parentNode.insertBefore(this.placeholder, this.element);*/ this.firstDrag = false; } if (newX) { this.element.style.left = newX + 'px'; } if (newY) { this.element.style.top = newY + 'px'; } if (Droppable) { // apply applyDelta defined on drag init var mouseCoords2 = this.options.mouseAnchor ? {x: mPosX - this.applyDelta[x], y: mPosY - this.applyDelta[y]} : mouseCoords; Droppable.action(mouseCoords2, 'drag', e, this.element); } if (o.onChange) { o.onChange(this); } } } }, /** * Function that handles the end of the dragging process * * @method _onEnd * @param {Object} window.event object. * @private */ _onEnd: function(e) { InkEvent.stopObserving(document, 'mousemove', this.handlers.drag); InkEvent.stopObserving(document, 'touchmove', this.handlers.drag); if (this.options.fps) { this._onDrag(e); } Css.removeClassName(this.element, this.options.dragClass); if (this.active && this.dragged) { if (this.options.droppableProxy) { // remove transparent div... document.body.removeChild(this.proxy); } if (this.pt) { // remove debugging element... InkElement.remove(this.pt); this.pt = undefined; } /*if (this.options.revert) { this.placeholder.parentNode.removeChild(this.placeholder); }*/ if(this.placeholder) { InkElement.remove(this.placeholder); } if (this.options.revert) { this.element.style.position = this.position; if (this.zindex !== null) { this.element.style.zIndex = this.zindex; } else { this.element.style.zIndex = 'auto'; } // restore default zindex of it had none this.element.style.left = (this.originalPosition[x]) ? this.originalPosition[x] + 'px' : ''; this.element.style.top = (this.originalPosition[y]) ? this.originalPosition[y] + 'px' : ''; } if (this.options.onEnd) { this.options.onEnd(this.element, e); } var Droppable = Ink.getModule('Ink.UI.Droppable_1'); if (Droppable) { Droppable.action(this._getCoords(e), 'drop', e, this.element); } this.position = false; this.zindex = false; this.firstDrag = true; } this.active = false; this.dragged = false; } }; return Draggable; }); /** * @module Ink.UI.DatePicker_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.DatePicker', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1','Ink.Util.Date_1', 'Ink.Dom.Browser_1'], function(Aux, Event, Css, Element, Selector, InkArray, InkDate ) { 'use strict'; /** * @class Ink.UI.DatePicker * @constructor * @version 1 * * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {String} [options.instance] unique id for the datepicker * @param {String} [options.format] Date format string * @param {String} [options.cssClass] CSS class to be applied to the datepicker * @param {String} [options.position] position the datepicker. Accept right or bottom, default is right * @param {Boolean} [options.onFocus] if the datepicker should open when the target element is focused * @param {Function} [options.onYearSelected] callback function to execute when the year is selected * @param {Function} [options.onMonthSelected] callback function to execute when the month is selected * @param {Function} [options.validDayFn] callback function to execute when 'rendering' the day (in the month view) * @param {String} [options.startDate] Date to define init month. Must be in yyyy-mm-dd format * @param {Function} [options.onSetDate] callback to execute when set date * @param {Boolean} [options.displayInSelect] whether to display the component in a select. defaults to false. * @param {Boolean} [options.showClose] whether to display the close button or not. defaults to true. * @param {Boolean} [options.showClean] whether to display the clean button or not. defaults to true. * @param {String} [options.yearRange] enforce limits to year for the Date, ex: '1990:2020' (deprecated) * @param {String} [options.dateRange] enforce limits to year, month and day for the Date, ex: '1990-08-25:2020-11' * @param {Number} [options.startWeekDay] day to use as first column on the calendar view. Defaults to Monday (1) * @param {String} [options.closeText] text to display on close button. defaults to 'Fechar' * @param {String} [options.cleanText] text to display on clean button. defaults to 'Limpar' * @param {String} [options.prevLinkText] text to display on the previous button. defaults to '«' * @param {String} [options.nextLinkText] text to display on the previous button. defaults to '«' * @param {String} [options.ofText] text to display between month and year. defaults to ' de ' * @param {Object} [options.month] Hash of month names. Defaults to portuguese month names. January is 1. * @param {Object} [options.wDay] Hash of weekdays. Defaults to portuguese month names. Sunday is 0. * * @example * <input type="text" id="dPicker" /> * <script> * Ink.requireModules(['Ink.Dom.Selector_1','Ink.UI.DatePicker_1'],function( Selector, DatePicker ){ * var datePickerElement = Ink.s('#dPicker'); * var datePickerObj = new DatePicker( datePickerElement ); * }); * </script> */ var DatePicker = function(selector, options) { if (selector) { this._dataField = Aux.elOrSelector(selector, '1st argument'); } this._options = Ink.extendObj({ instance: 'scdp_' + Math.round(99999*Math.random()), format: 'yyyy-mm-dd', cssClass: 'sapo_component_datepicker', position: 'right', onFocus: true, onYearSelected: undefined, onMonthSelected: undefined, validDayFn: undefined, startDate: false, // format yyyy-mm-dd onSetDate: false, displayInSelect: false, showClose: true, showClean: true, yearRange: false, dateRange: false, startWeekDay: 1, closeText: 'Close', cleanText: 'Clear', prevLinkText: '«', nextLinkText: '»', ofText: '&nbsp;de&nbsp;', month: { 1:'January', 2:'February', 3:'March', 4:'April', 5:'May', 6:'June', 7:'July', 8:'August', 9:'September', 10:'October', 11:'November', 12:'December' }, wDay: { 0:'Sunday', 1:'Monday', 2:'Tuesday', 3:'Wednesday', 4:'Thursday', 5:'Friday', 6:'Saturday' } }, Element.data(this._dataField) || {}); this._options = Ink.extendObj(this._options, options || {}); this._options.format = this._dateParsers[ this._options.format ] || this._options.format; this._hoverPicker = false; this._picker = null; if (this._options.pickerField) { this._picker = Aux.elOrSelector(this._options.pickerField, 'pickerField'); } this._today = new Date(); this._day = this._today.getDate( ); this._month = this._today.getMonth( ); this._year = this._today.getFullYear( ); this._setMinMax( this._options.dateRange || this._options.yearRange ); this._data = new Date( Date.UTC.apply( this , this._checkDateRange( this._year , this._month , this._day ) ) ); if(this._options.startDate && typeof this._options.startDate === 'string' && /\d\d\d\d\-\d\d\-\d\d/.test(this._options.startDate)) { this.setDate( this._options.startDate ); } this._init(); this._render(); if ( !this._options.startDate ){ if( this._dataField && typeof this._dataField.value === 'string' && this._dataField.value){ this.setDate( this._dataField.value ); } } Aux.registerInstance(this, this._containerObject, 'datePicker'); }; DatePicker.prototype = { version: '0.1', /** * Initialization function. Called by the constructor and * receives the same parameters. * * @method _init * @private */ _init: function(){ Ink.extendObj(this._options,this._lang || {}); }, /** * Renders the DatePicker's markup * * @method _render * @private */ _render: function() { /*jshint maxstatements:100, maxcomplexity:30 */ this._containerObject = document.createElement('div'); this._containerObject.id = this._options.instance; this._containerObject.className = 'sapo_component_datepicker'; var dom = document.getElementsByTagName('body')[0]; if(this._options.showClose || this._options.showClean){ this._superTopBar = document.createElement("div"); this._superTopBar.className = 'sapo_cal_top_options'; if(this._options.showClean){ var clean = document.createElement('a'); clean.className = 'clean'; clean.innerHTML = this._options.cleanText; this._superTopBar.appendChild(clean); } if(this._options.showClose){ var close = document.createElement('a'); close.className = 'close'; close.innerHTML = this._options.closeText; this._superTopBar.appendChild(close); } this._containerObject.appendChild(this._superTopBar); } var calendarTop = document.createElement("div"); calendarTop.className = 'sapo_cal_top'; this._monthDescContainer = document.createElement("div"); this._monthDescContainer.className = 'sapo_cal_month_desc'; this._monthPrev = document.createElement('div'); this._monthPrev.className = 'sapo_cal_prev'; this._monthPrev.innerHTML ='<a href="#prev" class="change_month_prev">' + this._options.prevLinkText + '</a>'; this._monthNext = document.createElement('div'); this._monthNext.className = 'sapo_cal_next'; this._monthNext.innerHTML ='<a href="#next" class="change_month_next">' + this._options.nextLinkText + '</a>'; calendarTop.appendChild(this._monthPrev); calendarTop.appendChild(this._monthDescContainer); calendarTop.appendChild(this._monthNext); this._monthContainer = document.createElement("div"); this._monthContainer.className = 'sapo_cal_month'; this._containerObject.appendChild(calendarTop); this._containerObject.appendChild(this._monthContainer); this._monthSelector = document.createElement('ul'); this._monthSelector.className = 'sapo_cal_month_selector'; var ulSelector; var liMonth; for(var i=1; i<=12; i++){ if ((i-1) % 4 === 0) { ulSelector = document.createElement('ul'); } liMonth = document.createElement('li'); liMonth.innerHTML = '<a href="#" class="sapo_calmonth_' + ( (String(i).length === 2) ? i : "0" + i) + '">' + this._options.month[i].substring(0,3) + '</a>'; ulSelector.appendChild(liMonth); if (i % 4 === 0) { this._monthSelector.appendChild(ulSelector); } } this._containerObject.appendChild(this._monthSelector); this._yearSelector = document.createElement('ul'); this._yearSelector.className = 'sapo_cal_year_selector'; this._containerObject.appendChild(this._yearSelector); if(!this._options.onFocus || this._options.displayInSelect){ if(!this._options.pickerField){ this._picker = document.createElement('a'); this._picker.href = '#open_cal'; this._picker.innerHTML = 'open'; this._picker.style.position = 'absolute'; this._picker.style.top = Element.elementTop(this._dataField); this._picker.style.left = Element.elementLeft(this._dataField) + (Element.elementWidth(this._dataField) || 0) + 5 + 'px'; this._dataField.parentNode.appendChild(this._picker); this._picker.className = 'sapo_cal_date_picker'; } else { this._picker = Aux.elOrSelector(this._options.pickerField, 'pickerField'); } } if(this._options.displayInSelect){ if (this._options.dayField && this._options.monthField && this._options.yearField || this._options.pickerField) { this._options.dayField = Aux.elOrSelector(this._options.dayField, 'dayField'); this._options.monthField = Aux.elOrSelector(this._options.monthField, 'monthField'); this._options.yearField = Aux.elOrSelector(this._options.yearField, 'yearField'); } else { throw "To use display in select you *MUST* to set dayField, monthField, yearField and pickerField!"; } } dom.insertBefore(this._containerObject, dom.childNodes[0]); // this._dataField.parentNode.appendChild(this._containerObject, dom.childNodes[0]); if (!this._picker) { Event.observe(this._dataField,'focus',Ink.bindEvent(function(){ this._containerObject = Element.clonePosition(this._containerObject, this._dataField); if ( this._options.position === 'bottom' ) { this._containerObject.style.top = Element.elementHeight(this._dataField) + Element.offsetTop(this._dataField) + 'px'; this._containerObject.style.left = Element.offset(this._dataField)[0] +'px'; } else { this._containerObject.style.top = Element.offset(this._dataField)[1] +'px'; this._containerObject.style.left = Element.elementWidth(this._dataField) + Element.offset(this._dataField)[0] +'px'; } //dom.appendChild(this._containerObject); this._updateDate(); this._showMonth(); this._containerObject.style.display = 'block'; },this)); } else { Event.observe(this._picker,'click',Ink.bindEvent(function(e){ Event.stop(e); this._containerObject = Element.clonePosition(this._containerObject,this._picker); this._updateDate(); this._showMonth(); this._containerObject.style.display = 'block'; },this)); } if(!this._options.displayInSelect){ Event.observe(this._dataField,'change', Ink.bindEvent(function() { this._updateDate( ); this._showDefaultView( ); this.setDate( ); if ( !this._hoverPicker ) { this._containerObject.style.display = 'none'; } },this)); Event.observe(this._dataField,'blur', Ink.bindEvent(function() { if ( !this._hoverPicker ) { this._containerObject.style.display = 'none'; } },this)); } else { Event.observe(this._options.dayField,'change', Ink.bindEvent(function(){ var yearSelected = this._options.yearField[this._options.yearField.selectedIndex].value; if(yearSelected !== '' && yearSelected !== 0) { this._updateDate(); this._showDefaultView(); } },this)); Event.observe(this._options.monthField,'change', Ink.bindEvent(function(){ var yearSelected = this._options.yearField[this._options.yearField.selectedIndex].value; if(yearSelected !== '' && yearSelected !== 0){ this._updateDate(); this._showDefaultView(); } },this)); Event.observe(this._options.yearField,'change', Ink.bindEvent(function(){ this._updateDate(); this._showDefaultView(); },this)); } Event.observe(document,'click',Ink.bindEvent(function(e){ if (e.target === undefined) { e.target = e.srcElement; } if (!Element.descendantOf(this._containerObject, e.target) && e.target !== this._dataField) { if (!this._picker) { this._containerObject.style.display = 'none'; } else if (e.target !== this._picker && (!this._options.displayInSelect || (e.target !== this._options.dayField && e.target !== this._options.monthField && e.target !== this._options.yearField) ) ) { if (!this._options.dayField || (!Element.descendantOf(this._options.dayField, e.target) && !Element.descendantOf(this._options.monthField, e.target) && !Element.descendantOf(this._options.yearField, e.target) ) ) { this._containerObject.style.display = 'none'; } } } },this)); this._showMonth(); this._monthChanger = document.createElement('a'); this._monthChanger.href = '#monthchanger'; this._monthChanger.className = 'sapo_cal_link_month'; this._monthChanger.innerHTML = this._options.month[this._month + 1]; this._deText = document.createElement('span'); this._deText.innerHTML = this._options._deText; this._yearChanger = document.createElement('a'); this._yearChanger.href = '#yearchanger'; this._yearChanger.className = 'sapo_cal_link_year'; this._yearChanger.innerHTML = this._year; this._monthDescContainer.innerHTML = ''; this._monthDescContainer.appendChild(this._monthChanger); this._monthDescContainer.appendChild(this._deText); this._monthDescContainer.appendChild(this._yearChanger); Event.observe(this._containerObject,'mouseover',Ink.bindEvent(function(e) { Event.stop( e ); this._hoverPicker = true; },this)); Event.observe(this._containerObject,'mouseout',Ink.bindEvent(function(e) { Event.stop( e ); this._hoverPicker = false; },this)); Event.observe(this._containerObject,'click',Ink.bindEvent(function(e){ if(typeof(e.target) === 'undefined'){ e.target = e.srcElement; } var className = e.target.className; var isInactive = className.indexOf( 'sapo_cal_off' ) !== -1; Event.stop(e); if( className.indexOf('sapo_cal_') === 0 && !isInactive ){ var day = className.substr( 9 , 2 ); if( Number( day ) ) { this.setDate( this._year + '-' + ( this._month + 1 ) + '-' + day ); this._containerObject.style.display = 'none'; } else if(className === 'sapo_cal_link_month'){ this._monthContainer.style.display = 'none'; this._yearSelector.style.display = 'none'; this._monthPrev.childNodes[0].className = 'action_inactive'; this._monthNext.childNodes[0].className = 'action_inactive'; this._setActiveMonth(); this._monthSelector.style.display = 'block'; } else if(className === 'sapo_cal_link_year'){ this._monthPrev.childNodes[0].className = 'action_inactive'; this._monthNext.childNodes[0].className = 'action_inactive'; this._monthSelector.style.display = 'none'; this._monthContainer.style.display = 'none'; this._showYearSelector(); this._yearSelector.style.display = 'block'; } } else if( className.indexOf("sapo_calmonth_") === 0 && !isInactive ){ var month=className.substr(14,2); if(Number(month)){ this._month = month - 1; // if( typeof this._options.onMonthSelected === 'function' ){ // this._options.onMonthSelected(this, { // 'year': this._year, // 'month' : this._month // }); // } this._monthSelector.style.display = 'none'; this._monthPrev.childNodes[0].className = 'change_month_prev'; this._monthNext.childNodes[0].className = 'change_month_next'; if ( this._year < this._yearMin || this._year === this._yearMin && this._month <= this._monthMin ){ this._monthPrev.childNodes[0].className = 'action_inactive'; } else if( this._year > this._yearMax || this._year === this._yearMax && this._month >= this._monthMax ){ this._monthNext.childNodes[0].className = 'action_inactive'; } this._updateCal(); this._monthContainer.style.display = 'block'; } } else if( className.indexOf("sapo_calyear_") === 0 && !isInactive ){ var year=className.substr(13,4); if(Number(year)){ this._year = year; if( typeof this._options.onYearSelected === 'function' ){ this._options.onYearSelected(this, { 'year': this._year }); } this._monthPrev.childNodes[0].className = 'action_inactive'; this._monthNext.childNodes[0].className = 'action_inactive'; this._yearSelector.style.display='none'; this._setActiveMonth(); this._monthSelector.style.display='block'; } } else if( className.indexOf('change_month_') === 0 && !isInactive ){ if(className === 'change_month_next'){ this._updateCal(1); } else if(className === 'change_month_prev'){ this._updateCal(-1); } } else if( className.indexOf('change_year_') === 0 && !isInactive ){ if(className === 'change_year_next'){ this._showYearSelector(1); } else if(className === 'change_year_prev'){ this._showYearSelector(-1); } } else if(className === 'clean'){ if(this._options.displayInSelect){ this._options.yearField.selectedIndex = 0; this._options.monthField.selectedIndex = 0; this._options.dayField.selectedIndex = 0; } else { this._dataField.value = ''; } } else if(className === 'close'){ this._containerObject.style.display = 'none'; } this._updateDescription(); },this)); }, /** * Sets the range of dates allowed to be selected in the Date Picker * * @method _setMinMax * @param {String} dateRange Two dates separated by a ':'. Example: 2013-01-01:2013-12-12 * @private */ _setMinMax : function( dateRange ) { var auxDate; if( dateRange ) { var dates = dateRange.split( ':' ); var pattern = /^(\d{4})((\-)(\d{1,2})((\-)(\d{1,2}))?)?$/; if ( dates[ 0 ] ) { if ( dates[ 0 ] === 'NOW' ) { this._yearMin = this._today.getFullYear( ); this._monthMin = this._today.getMonth( ) + 1; this._dayMin = this._today.getDate( ); } else if ( pattern.test( dates[ 0 ] ) ) { auxDate = dates[ 0 ].split( '-' ); this._yearMin = Math.floor( auxDate[ 0 ] ); this._monthMin = Math.floor( auxDate[ 1 ] ) || 1; this._dayMin = Math.floor( auxDate[ 2 ] ) || 1; if ( 1 < this._monthMin && this._monthMin > 12 ) { this._monthMin = 1; this._dayMin = 1; } if ( 1 < this._dayMin && this._dayMin > this._daysInMonth( this._yearMin , this._monthMin ) ) { this._dayMin = 1; } } else { this._yearMin = Number.MIN_VALUE; this._monthMin = 1; this._dayMin = 1; } } if ( dates[ 1 ] ) { if ( dates[ 1 ] === 'NOW' ) { this._yearMax = this._today.getFullYear( ); this._monthMax = this._today.getMonth( ) + 1; this._dayMax = this._today.getDate( ); } else if ( pattern.test( dates[ 1 ] ) ) { auxDate = dates[ 1 ].split( '-' ); this._yearMax = Math.floor( auxDate[ 0 ] ); this._monthMax = Math.floor( auxDate[ 1 ] ) || 12; this._dayMax = Math.floor( auxDate[ 2 ] ) || this._daysInMonth( this._yearMax , this._monthMax ); if ( 1 < this._monthMax && this._monthMax > 12 ) { this._monthMax = 12; this._dayMax = 31; } var MDay = this._daysInMonth( this._yearMax , this._monthMax ); if ( 1 < this._dayMax && this._dayMax > MDay ) { this._dayMax = MDay; } } else { this._yearMax = Number.MAX_VALUE; this._monthMax = 12; this._dayMax = 31; } } if ( !( this._yearMax >= this._yearMin && (this._monthMax > this._monthMin || ( (this._monthMax === this._monthMin) && (this._dayMax >= this._dayMin) ) ) ) ) { this._yearMin = Number.MIN_VALUE; this._monthMin = 1; this._dayMin = 1; this._yearMax = Number.MAX_VALUE; this._monthMax = 12; this._dayMaXx = 31; } } else { this._yearMin = Number.MIN_VALUE; this._monthMin = 1; this._dayMin = 1; this._yearMax = Number.MAX_VALUE; this._monthMax = 12; this._dayMax = 31; } }, /** * Checks if a date is between the valid range. * Starts by checking if the date passed is valid. If not, will fallback to the 'today' date. * Then checks if the all params are inside of the date range specified. If not, it will fallback to the nearest valid date (either Min or Max). * * @method _checkDateRange * @param {Number} year Year with 4 digits (yyyy) * @param {Number} month Month * @param {Number} day Day * @return {Array} Array with the final processed date. * @private */ _checkDateRange : function( year , month , day ) { if ( !this._isValidDate( year , month + 1 , day ) ) { year = this._today.getFullYear( ); month = this._today.getMonth( ); day = this._today.getDate( ); } if ( year > this._yearMax ) { year = this._yearMax; month = this._monthMax - 1; day = this._dayMax; } else if ( year < this._yearMin ) { year = this._yearMin; month = this._monthMin - 1; day = this._dayMin; } if ( year === this._yearMax && month + 1 > this._monthMax ) { month = this._monthMax - 1; day = this._dayMax; } else if ( year === this._yearMin && month + 1 < this._monthMin ) { month = this._monthMin - 1; day = this._dayMin; } if ( year === this._yearMax && month + 1 === this._monthMax && day > this._dayMax ){ day = this._dayMax; } else if ( year === this._yearMin && month + 1 === this._monthMin && day < this._dayMin ){ day = this._dayMin; } else if ( day > this._daysInMonth( year , month + 1 ) ){ day = this._daysInMonth( year , month + 1 ); } return [ year , month , day ]; }, /** * Sets the markup in the default view mode (showing the days). * Also disables the previous and next buttons in case they don't meet the range requirements. * * @method _showDefaultView * @private */ _showDefaultView: function(){ this._yearSelector.style.display = 'none'; this._monthSelector.style.display = 'none'; this._monthPrev.childNodes[0].className = 'change_month_prev'; this._monthNext.childNodes[0].className = 'change_month_next'; if ( this._year < this._yearMin || this._year === this._yearMin && this._month + 1 <= this._monthMin ){ this._monthPrev.childNodes[0].className = 'action_inactive'; } else if( this._year > this._yearMax || this._year === this._yearMax && this._month + 1 >= this._monthMax ){ this._monthNext.childNodes[0].className = 'action_inactive'; } this._monthContainer.style.display = 'block'; }, /** * Updates the date shown on the datepicker * * @method _updateDate * @private */ _updateDate: function(){ var dataParsed; if(!this._options.displayInSelect){ if(this._dataField.value !== ''){ if(this._isDate(this._options.format,this._dataField.value)){ dataParsed = this._getDataArrayParsed(this._dataField.value); dataParsed = this._checkDateRange( dataParsed[ 0 ] , dataParsed[ 1 ] - 1 , dataParsed[ 2 ] ); this._year = dataParsed[ 0 ]; this._month = dataParsed[ 1 ]; this._day = dataParsed[ 2 ]; }else{ this._dataField.value = ''; this._year = this._data.getFullYear( ); this._month = this._data.getMonth( ); this._day = this._data.getDate( ); } this._data.setFullYear( this._year , this._month , this._day ); this._dataField.value = this._writeDateInFormat( ); } } else { dataParsed = []; if(this._isValidDate( dataParsed[0] = this._options.yearField[this._options.yearField.selectedIndex].value, dataParsed[1] = this._options.monthField[this._options.monthField.selectedIndex].value, dataParsed[2] = this._options.dayField[this._options.dayField.selectedIndex].value )){ dataParsed = this._checkDateRange( dataParsed[ 0 ] , dataParsed[ 1 ] - 1 , dataParsed[ 2 ] ); this._year = dataParsed[ 0 ]; this._month = dataParsed[ 1 ]; this._day = dataParsed[ 2 ]; } else { dataParsed = this._checkDateRange( dataParsed[ 0 ] , dataParsed[ 1 ] - 1 , 1 ); if(this._isValidDate( dataParsed[ 0 ], dataParsed[ 1 ] + 1 ,dataParsed[ 2 ] )){ this._year = dataParsed[ 0 ]; this._month = dataParsed[ 1 ]; this._day = this._daysInMonth(dataParsed[0],dataParsed[1]); this.setDate(); } } } this._updateDescription(); this._showMonth(); }, /** * Updates the date description shown at the top of the datepicker * * @method _updateDescription * @private */ _updateDescription: function(){ this._monthChanger.innerHTML = this._options.month[ this._month + 1 ]; this._deText.innerHTML = this._options.ofText; this._yearChanger.innerHTML = this._year; }, /** * Renders the year selector view of the datepicker * * @method _showYearSelector * @private */ _showYearSelector: function(){ if (arguments.length){ var year = + this._year + arguments[0]*10; year=year-year%10; if ( year>this._yearMax || year+9<this._yearMin ){ return; } this._year = + this._year + arguments[0]*10; } var str = "<li>"; var ano_base = this._year-(this._year%10); for (var i=0; i<=11; i++){ if (i % 4 === 0){ str+='<ul>'; } if (!i || i === 11){ if ( i && (ano_base+i-1)<=this._yearMax && (ano_base+i-1)>=this._yearMin ){ str+='<li><a href="#year_next" class="change_year_next">' + this._options.nextLinkText + '</a></li>'; } else if( (ano_base+i-1)<=this._yearMax && (ano_base+i-1)>=this._yearMin ){ str+='<li><a href="#year_prev" class="change_year_prev">' + this._options.prevLinkText + '</a></li>'; } else { str +='<li>&nbsp;</li>'; } } else { if ( (ano_base+i-1)<=this._yearMax && (ano_base+i-1)>=this._yearMin ){ str+='<li><a href="#" class="sapo_calyear_' + (ano_base+i-1) + (((ano_base+i-1) === this._data.getFullYear()) ? ' sapo_cal_on' : '') + '">' + (ano_base+i-1) +'</a></li>'; } else { str+='<li><a href="#" class="sapo_cal_off">' + (ano_base+i-1) +'</a></li>'; } } if ((i+1) % 4 === 0) { str+='</ul>'; } } str += "</li>"; this._yearSelector.innerHTML = str; }, /** * This function returns the given date in an array format * * @method _getDataArrayParsed * @param {String} dateStr A date on a string. * @private * @return {Array} The given date in an array format */ _getDataArrayParsed: function(dateStr){ var arrData = []; var data = InkDate.set( this._options.format , dateStr ); if (data) { arrData = [ data.getFullYear( ) , data.getMonth( ) + 1 , data.getDate( ) ]; } return arrData; }, /** * Checks if a date is valid * * @method _isValidDate * @param {Number} year * @param {Number} month * @param {Number} day * @private * @return {Boolean} True if the date is valid, false otherwise */ _isValidDate: function(year, month, day){ var yearRegExp = /^\d{4}$/; var validOneOrTwo = /^\d{1,2}$/; return ( yearRegExp.test(year) && validOneOrTwo.test(month) && validOneOrTwo.test(day) && month >= 1 && month <= 12 && day >= 1 && day <= this._daysInMonth(year,month) ); }, /** * Checks if a given date is an valid format. * * @method _isDate * @param {String} format A date format. * @param {String} dateStr A date on a string. * @private * @return {Boolean} True if the given date is valid according to the given format */ _isDate: function(format, dateStr){ try { if (typeof format === 'undefined'){ return false; } var data = InkDate.set( format , dateStr ); if( data && this._isValidDate( data.getFullYear( ) , data.getMonth( ) + 1 , data.getDate( ) ) ){ return true; } } catch (ex) {} return false; }, /** * This method returns the date written with the format specified on the options * * @method _writeDateInFormat * @private * @return {String} Returns the current date of the object in the specified format */ _writeDateInFormat:function(){ return InkDate.get( this._options.format , this._data ); }, /** * This method allows the user to set the DatePicker's date on run-time. * * @method setDate * @param {String} dateString A date string in yyyy-mm-dd format. * @public */ setDate : function( dateString ) { if ( typeof dateString === 'string' && /\d{4}-\d{1,2}-\d{1,2}/.test( dateString ) ) { var auxDate = dateString.split( '-' ); this._year = auxDate[ 0 ]; this._month = auxDate[ 1 ] - 1; this._day = auxDate[ 2 ]; } this._setDate( ); }, /** * Sets the chosen date on the target input field * * @method _setDate * @param {DOMElement} objClicked Clicked object inside the DatePicker's calendar. * @private */ _setDate : function( objClicked ){ if( typeof objClicked !== 'undefined' && objClicked.className && objClicked.className.indexOf('sapo_cal_') === 0 ) { this._day = objClicked.className.substr( 9 , 2 ); } this._data.setFullYear.apply( this._data , this._checkDateRange( this._year , this._month , this._day ) ); if(!this._options.displayInSelect){ this._dataField.value = this._writeDateInFormat(); } else { this._options.dayField.value = this._data.getDate(); this._options.monthField.value = this._data.getMonth()+1; this._options.yearField.value = this._data.getFullYear(); } if(this._options.onSetDate) { this._options.onSetDate( this , { date : this._data } ); } }, /** * Makes the necessary work to update the calendar * when choosing a different month * * @method _updateCal * @param {Number} inc Indicates previous or next month * @private */ _updateCal: function(inc){ if( typeof this._options.onMonthSelected === 'function' ){ this._options.onMonthSelected(this, { 'year': this._year, 'month' : this._month }); } this._updateMonth(inc); this._showMonth(); }, /** * Function that returns the number of days on a given month on a given year * * @method _daysInMonth * @param {Number} _y - year * @param {Number} _m - month * @private * @return {Number} The number of days on a given month on a given year */ _daysInMonth: function(_y,_m){ var nDays = 31; switch (_m) { case 2: nDays = ((_y % 400 === 0) || (_y % 4 === 0 && _y % 100 !== 0)) ? 29 : 28; break; case 4: case 6: case 9: case 11: nDays = 30; break; } return nDays; }, /** * Updates the calendar when a different month is chosen * * @method _updateMonth * @param {Number} incValue - indicates previous or next month * @private */ _updateMonth: function(incValue){ if(typeof incValue === 'undefined') { incValue = "0"; } var mes = this._month + 1; var ano = this._year; switch(incValue){ case -1: if (mes===1){ if(ano === this._yearMin){ return; } mes=12; ano--; } else { mes--; } this._year = ano; this._month = mes - 1; break; case 1: if(mes === 12){ if(ano === this._yearMax){ return; } mes=1; ano++; } else{ mes++; } this._year = ano; this._month = mes - 1; break; default: } }, /** * Key-value object that (for a given key) points to the correct parsing format for the DatePicker * @property _dateParsers * @type {Object} * @readOnly */ _dateParsers: { 'yyyy-mm-dd' : 'Y-m-d' , 'yyyy/mm/dd' : 'Y/m/d' , 'yy-mm-dd' : 'y-m-d' , 'yy/mm/dd' : 'y/m/d' , 'dd-mm-yyyy' : 'd-m-Y' , 'dd/mm/yyyy' : 'd/m/Y' , 'dd-mm-yy' : 'd-m-y' , 'dd/mm/yy' : 'd/m/y' , 'mm/dd/yyyy' : 'm/d/Y' , 'mm-dd-yyyy' : 'm-d-Y' }, /** * Renders the current month * * @method _showMonth * @private */ _showMonth: function(){ /*jshint maxstatements:100, maxcomplexity:20 */ var i, j; var mes = this._month + 1; var ano = this._year; var maxDay = this._daysInMonth(ano,mes); var wDayFirst = (new Date( ano , mes - 1 , 1 )).getDay(); var startWeekDay = this._options.startWeekDay || 0; this._monthPrev.childNodes[0].className = 'change_month_prev'; this._monthNext.childNodes[0].className = 'change_month_next'; if ( ano < this._yearMin || ano === this._yearMin && mes <= this._monthMin ){ this._monthPrev.childNodes[0].className = 'action_inactive'; } else if( ano > this._yearMax || ano === this._yearMax && mes >= this._monthMax ){ this._monthNext.childNodes[0].className = 'action_inactive'; } if(startWeekDay && Number(startWeekDay)){ if(startWeekDay > wDayFirst) { wDayFirst = 7 + startWeekDay - wDayFirst; } else { wDayFirst += startWeekDay; } } var html = ''; html += '<ul class="sapo_cal_header">'; for(i=0; i<7; i++){ html+='<li>' + this._options.wDay[i + (((startWeekDay+i)>6) ? startWeekDay-7 : startWeekDay )].substring(0,1) + '</li>'; } html+='</ul>'; var counter = 0; html+='<ul>'; if(wDayFirst){ for(j = startWeekDay; j < wDayFirst - startWeekDay; j++) { if (!counter){ html+='<ul>'; } html+='<li class="sapo_cal_empty">&nbsp;</li>'; counter++; } } for (i = 1; i <= maxDay; i++) { if (counter === 7){ counter=0; html+='<ul>'; } var idx = 'sapo_cal_' + ((String(i).length === 2) ? i : "0" + i); idx += ( ano === this._yearMin && mes === this._monthMin && i < this._dayMin || ano === this._yearMax && mes === this._monthMax && i > this._dayMax || ano === this._yearMin && mes < this._monthMin || ano === this._yearMax && mes > this._monthMax || ano < this._yearMin || ano > this._yearMax || ( this._options.validDayFn && !this._options.validDayFn.call( this, new Date( ano , mes - 1 , i) ) ) ) ? " sapo_cal_off" : (this._data.getFullYear( ) === ano && this._data.getMonth( ) === mes - 1 && i === this._day) ? " sapo_cal_on" : ""; html+='<li><a href="#" class="' + idx + '">' + i + '</a></li>'; counter++; if(counter === 7){ html+='</ul>'; } } if (counter !== 7){ for(i = counter; i < 7; i++){ html+='<li class="sapo_cal_empty">&nbsp;</li>'; } html+='</ul>'; } html+='</ul>'; this._monthContainer.innerHTML = html; }, /** * This method sets the active month * * @method _setActiveMonth * @param {DOMElement} parent DOMElement where all the months are. * @private */ _setActiveMonth: function(parent){ if (typeof parent === 'undefined') { parent = this._monthSelector; } var length = parent.childNodes.length; if (parent.className && parent.className.match(/sapo_calmonth_/)) { var year = this._year; var month = parent.className.substr( 14 , 2 ); if ( year === this._data.getFullYear( ) && month === this._data.getMonth( ) + 1 ) { Css.addClassName( parent , 'sapo_cal_on' ); Css.removeClassName( parent , 'sapo_cal_off' ); } else { Css.removeClassName( parent , 'sapo_cal_on' ); if ( year === this._yearMin && month < this._monthMin || year === this._yearMax && month > this._monthMax || year < this._yearMin || year > this._yearMax ) { Css.addClassName( parent , 'sapo_cal_off' ); } else { Css.removeClassName( parent , 'sapo_cal_off' ); } } } else if (length !== 0){ for (var i = 0; i < length; i++) { this._setActiveMonth(parent.childNodes[i]); } } }, /** * Prototype's method to allow the 'i18n files' to change all objects' language at once. * @param {Object} options Object with the texts' configuration. * @param {String} closeText Text of the close anchor * @param {String} cleanText Text of the clean text anchor * @param {String} prevLinkText "Previous" link's text * @param {String} nextLinkText "Next" link's text * @param {String} ofText The text "of", present in 'May of 2013' * @param {Object} month An object with keys from 1 to 12 that have the full months' names * @param {Object} wDay An object with keys from 0 to 6 that have the full weekdays' names * @public */ lang: function( options ){ this._lang = options; }, /** * This calls the rendering of the selected month. * * @method showMonth * @public */ showMonth: function(){ this._showMonth(); }, /** * Returns true if the calendar sceen is in 'select day' mode * * @return {Boolean} True if the calendar sceen is in 'select day' mode * @public */ isMonthRendered: function(){ var header = Selector.select('.sapo_cal_header',this._containerObject)[0]; return ( (Css.getStyle(header.parentNode,'display') !== 'none') && (Css.getStyle(header.parentNode.parentNode,'display') !== 'none') ); } }; return DatePicker; }); /** * @module Ink.UI.Close_1 * @author inkdev AT sapo.pt */ Ink.createModule('Ink.UI.Close', '1', ['Ink.Dom.Event_1','Ink.Dom.Element_1'], function(InkEvent, InkElement) { 'use strict'; /** * Subscribes clicks on the document.body. If and only if you clicked on an element * having class "ink-close" or "ink-dismiss", will go up the DOM hierarchy looking for an element with any * of the following classes: "ink-alert", "ink-alert-block". * If it is found, it is removed from the DOM. * * One should call close once per page (full page refresh). * * @class Ink.UI.Close * @constructor * @example * <script> * Ink.requireModules(['Ink.UI.Close_1'],function( Close ){ * new Close(); * }); * </script> */ var Close = function() { InkEvent.observe(document.body, 'click', function(ev) { var el = InkEvent.element(ev); el = InkElement.findUpwardsByClass(el, 'ink-close') || InkElement.findUpwardsByClass(el, 'ink-dismiss'); if (!el) { return; // ink-close or ink-dismiss class not found } var toRemove = el; toRemove = InkElement.findUpwardsByClass(el, 'ink-alert') || InkElement.findUpwardsByClass(el, 'ink-alert-block'); if (toRemove) { InkEvent.stop(ev); InkElement.remove(toRemove); } }); }; return Close; }); /** * @module Ink.UI.Carousel_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Carousel', '1', ['Ink.UI.Aux_1', 'Ink.Dom.Event_1', 'Ink.Dom.Css_1', 'Ink.Dom.Element_1', 'Ink.UI.Pagination_1', 'Ink.Dom.Browser_1', 'Ink.Dom.Selector_1'], function(Aux, InkEvent, Css, InkElement, Pagination, Browser/*, Selector*/) { 'use strict'; /* * TODO: * keyboardSupport * swipe */ /** * @class Ink.UI.Carousel_1 * @constructor * * @param {String|DOMElement} selector * @param {Object} [options] * @param {String} [options.axis='x'] Can be `'x'` or `'y'`, for a horizontal or vertical carousel * @param {Boolean} [options.center=false] Center the carousel. * @TODO @param {Boolean} [options.keyboardSupport=false] Enable keyboard support * @param {String|DOMElement|Ink.UI.Pagination_1} [options.pagination] Either an `<ul>` element to add pagination markup to, or an `Ink.UI.Pagination` instance to use. * @param {Function} [options.onChange] Callback for when the page is changed. */ var Carousel = function(selector, options) { this._handlers = { paginationChange: Ink.bind(this._onPaginationChange, this), windowResize: Ink.bind(this.refit, this) }; InkEvent.observe(window, 'resize', this._handlers.windowResize); this._element = Aux.elOrSelector(selector, '1st argument'); this._options = Ink.extendObj({ axis: 'x', hideLast: false, center: false, keyboardSupport:false, pagination: null, onChange: null }, options || {}, InkElement.data(this._element)); this._isY = (this._options.axis === 'y'); var rEl = this._element; var ulEl = Ink.s('ul.stage', rEl); this._ulEl = ulEl; InkElement.removeTextNodeChildren(ulEl); if (this._options.hideLast) { var hiderEl = document.createElement('div'); hiderEl.className = 'hider'; this._element.appendChild(hiderEl); hiderEl.style.position = 'absolute'; hiderEl.style[ this._isY ? 'left' : 'top' ] = '0'; // fix to top.. hiderEl.style[ this._isY ? 'right' : 'bottom' ] = '0'; // and bottom... hiderEl.style[ this._isY ? 'bottom' : 'right' ] = '0'; // and move to the end. this._hiderEl = hiderEl; } this.refit(); if (this._isY) { // Override white-space: no-wrap which is only necessary to make sure horizontal stuff stays horizontal, but breaks stuff intended to be vertical. this._ulEl.style.whiteSpace = 'normal'; } if (this._options.pagination) { if (Aux.isDOMElement(this._options.pagination) || typeof this._options.pagination === 'string') { // if dom element or css selector string... this._pagination = new Pagination(this._options.pagination, { size: this._numPages, onChange: this._handlers.paginationChange }); } else { // assumes instantiated pagination this._pagination = this._options.pagination; this._pagination._options.onChange = this._handlers.paginationChange; this._pagination.setSize(this._numPages); this._pagination.setCurrent(0); } } }; Carousel.prototype = { /** * Measure the carousel once again, adjusting the involved elements' * sizes. Called automatically when the window resizes, in order to * cater for changes from responsive media queries, for instance. * * @method refit */ refit: function() { this._liEls = Ink.ss('li.slide', this._ulEl); var numItems = this._liEls.length; this._ctnLength = this._size(this._element); this._elLength = this._size(this._liEls[0]); this._itemsPerPage = Math.floor( this._ctnLength / this._elLength ); this._numPages = Math.ceil( numItems / this._itemsPerPage ); this._deltaLength = this._itemsPerPage * this._elLength; if (this._isY) { this._element.style.width = this._liEls[0].offsetWidth + 'px'; this._ulEl.style.width = this._liEls[0].offsetWidth + 'px'; } else { this._ulEl.style.height = this._liEls[0].offsetHeight + 'px'; } this._center(); this._updateHider(); this._IE7(); if (this._pagination) { this._pagination.setSize(this._numPages); this._pagination.setCurrent(0); } }, _size: function (elm) { var dims = InkElement.outerDimensions(elm) return this._isY ? dims[1] : dims[0]; }, _center: function() { if (!this._options.center) { return; } var gap = Math.floor( (this._ctnLength - (this._elLength * this._itemsPerPage) ) / 2 ); var pad; if (this._isY) { pad = [gap, 'px 0']; } else { pad = ['0 ', gap, 'px']; } this._ulEl.style.padding = pad.join(''); }, _updateHider: function() { if (!this._hiderEl) { return; } var gap = Math.floor( this._ctnLength - (this._elLength * this._itemsPerPage) ); if (this._options.center) { gap /= 2; } this._hiderEl.style[ this._isY ? 'height' : 'width' ] = gap + 'px'; }, /** * Refit stuff for IE7 because it won't support inline-block. * * @method _IE7 * @private */ _IE7: function () { if (Browser.IE && '' + Browser.version.split('.')[0] === '7') { var numPages = this._numPages; var slides = Ink.ss('li.slide', this._ulEl); var stl = function (prop, val) {slides[i].style[prop] = val; }; for (var i = 0, len = slides.length; i < len; i++) { stl('position', 'absolute'); stl(this._isY ? 'top' : 'left', (i * this._elLength) + 'px'); } } }, _onPaginationChange: function(pgn) { var currPage = pgn.getCurrent(); this._ulEl.style[ this._options.axis === 'y' ? 'top' : 'left'] = ['-', currPage * this._deltaLength, 'px'].join(''); if (this._options.onChange) { this._options.onChange.call(this, currPage); } } }; return Carousel; }); /** * @module Ink.UI.Modal_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.Modal', '1', ['Ink.UI.Aux_1','Ink.Dom.Event_1','Ink.Dom.Css_1','Ink.Dom.Element_1','Ink.Dom.Selector_1','Ink.Util.Array_1'], function(Aux, Event, Css, Element, Selector, InkArray ) { 'use strict'; /** * @class Ink.UI.Modal * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {String} [options.width] Default/Initial width. Ex: '600px' * @param {String} [options.height] Default/Initial height. Ex: '400px' * @param {String} [options.shadeClass] Custom class to be added to the div.ink-shade * @param {String} [options.modalClass] Custom class to be added to the div.ink-modal * @param {String} [options.trigger] CSS Selector to target elements that will trigger the Modal. * @param {String} [options.triggerEvent] Trigger's event to be listened. 'click' is the default value. Ex: 'mouseover', 'touchstart'... * @param {Boolean} [options.autoDisplay=true] Display the Modal automatically when constructed. * @param {String} [options.markup] Markup to be placed in the Modal when created * @param {Function} [options.onShow] Callback function to run when the Modal is opened. * @param {Function} [options.onDismiss] Callback function to run when the Modal is closed. Return `false` to cancel dismissing the Modal. * @param {Boolean} [options.closeOnClick] Determines if the Modal should close when clicked outside of it. 'false' by default. * @param {Boolean} [options.responsive] Determines if the Modal should behave responsively (adapt to smaller viewports). * @param {Boolean} [options.disableScroll] Determines if the Modal should 'disable' the page's scroll (not the Modal's body). * * @example * <div class="ink-shade fade"> * <div id="test" class="ink-modal fade" data-trigger="#bModal" data-width="800px" data-height="400px"> * <div class="modal-header"> * <button class="modal-close ink-dismiss"></button> * <h5>Modal windows can have headers</h5> * </div> * <div class="modal-body" id="modalContent"> * <h3>Please confirm your previous choice</h3> * <p>"No," said Peleg, "and he hasn't been baptized right either, or it would have washed some of that devil's blue off his face."</p> * <p> * <img src="http://placehold.it/800x400" style="width: 100%;" alt=""> * </p> * <p>"Do tell, now," cried Bildad, "is this Philistine a regular member of Deacon Deuteronomy's meeting? I never saw him going there, and I pass it every Lord's day."</p> * <p>"I don't know anything about Deacon Deuteronomy or his meeting," said I; "all I know is, that Queequeg here is a born member of the First Congregational Church. He is a deacon himself, Queequeg is."</p> * </div> * <div class="modal-footer"> * <div class="push-right"> * <button class="ink-button info">Confirm</button> * <button class="ink-button caution ink-dismiss">Cancel</button> * </div> * </div> * </div> * </div> * <a href="#" id="bModal">Open modal</a> * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.Modal_1'], function( Selector, Modal ){ * var modalElement = Ink.s('#test'); * var modalObj = new Modal( modalElement ); * }); * </script> */ var Modal = function(selector, options) { if( (typeof selector !== 'string') && (typeof selector !== 'object') && (typeof options.markup === 'undefined') ){ throw 'Invalid Modal selector'; } else if(typeof selector === 'string'){ if( selector !== '' ){ this._element = Selector.select(selector); if( this._element.length === 0 ){ /** * From a developer's perspective this should be like it is... * ... from a user's perspective, if it doesn't find elements, should just ignore it, no? */ throw 'The Modal selector has not returned any elements'; } else { this._element = this._element[0]; } } } else if( !!selector ){ this._element = selector; } this._options = { /** * Width, height and markup really optional, as they can be obtained by the element */ width: undefined, height: undefined, /** * To add extra classes */ shadeClass: undefined, modalClass: undefined, /** * Optional trigger properties */ trigger: undefined, triggerEvent: 'click', autoDisplay: true, /** * Remaining options */ markup: undefined, onShow: undefined, onDismiss: undefined, closeOnClick: false, responsive: true, disableScroll: true }; this._handlers = { click: Ink.bindEvent(this._onClick, this), keyDown: Ink.bindEvent(this._onKeyDown, this), resize: Ink.bindEvent(this._onResize, this) }; this._wasDismissed = false; /** * Modal Markup */ if( this._element ){ this._markupMode = Css.hasClassName(this._element,'ink-modal'); // Check if the full modal comes from the markup } else { this._markupMode = false; } if( !this._markupMode ){ this._modalShadow = document.createElement('div'); this._modalShadowStyle = this._modalShadow.style; this._modalDiv = document.createElement('div'); this._modalDivStyle = this._modalDiv.style; if( !!this._element ){ this._options.markup = this._element.innerHTML; } /** * Not in full markup mode, let's set the classes and css configurations */ Css.addClassName( this._modalShadow,'ink-shade' ); Css.addClassName( this._modalDiv,'ink-modal' ); Css.addClassName( this._modalDiv,'ink-space' ); /** * Applying the main css styles */ // this._modalDivStyle.position = 'absolute'; this._modalShadow.appendChild( this._modalDiv); document.body.appendChild( this._modalShadow ); } else { this._modalDiv = this._element; this._modalDivStyle = this._modalDiv.style; this._modalShadow = this._modalDiv.parentNode; this._modalShadowStyle = this._modalShadow.style; this._contentContainer = Selector.select(".modal-body",this._modalDiv); if( !this._contentContainer.length ){ throw 'Missing div with class "modal-body"'; } this._contentContainer = this._contentContainer[0]; this._options.markup = this._contentContainer.innerHTML; /** * First, will handle the least important: The dataset */ this._options = Ink.extendObj(this._options,Element.data(this._element)); } /** * Now, the most important, the initialization options */ this._options = Ink.extendObj(this._options,options || {}); if( !this._markupMode ){ this.setContentMarkup(this._options.markup); } if( typeof this._options.shadeClass === 'string' ){ InkArray.each( this._options.shadeClass.split(' '), Ink.bind(function( item ){ Css.addClassName( this._modalShadow, item.trim() ); }, this)); } if( typeof this._options.modalClass === 'string' ){ InkArray.each( this._options.modalClass.split(' '), Ink.bind(function( item ){ Css.addClassName( this._modalDiv, item.trim() ); }, this)); } if( ("trigger" in this._options) && ( typeof this._options.trigger !== 'undefined' ) ){ var triggerElement,i; if( typeof this._options.trigger === 'string' ){ triggerElement = Selector.select( this._options.trigger ); if( triggerElement.length > 0 ){ for( i=0; i<triggerElement.length; i++ ){ Event.observe( triggerElement[i], this._options.triggerEvent, Ink.bindEvent(this.open, this) ); } } } } else if ( this._options.autoDisplay ) { this.open(); } }; Modal.prototype = { /** * Responsible for repositioning the modal * * @method _reposition * @private */ _reposition: function(){ this._modalDivStyle.top = this._modalDivStyle.left = '50%'; this._modalDivStyle.marginTop = '-' + ( ~~( Element.elementHeight(this._modalDiv)/2) ) + 'px'; this._modalDivStyle.marginLeft = '-' + ( ~~( Element.elementWidth(this._modalDiv)/2) ) + 'px'; }, /** * Responsible for resizing the modal * * @method _onResize * @param {Boolean|Event} runNow Its executed in the begining to resize/reposition accordingly to the viewport. But usually it's an event object. * @private */ _onResize: function( runNow ){ if( typeof runNow === 'boolean' ){ this._timeoutResizeFunction.call(this); } else if( !this._resizeTimeout && (typeof runNow === 'object') ){ this._resizeTimeout = setTimeout(Ink.bind(this._timeoutResizeFunction, this),250); } }, /** * Timeout Resize Function * * @method _timeoutResizeFunction * @private */ _timeoutResizeFunction: function(){ /** * Getting the current viewport size */ var elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body, currentViewportHeight = parseInt(elem.clientHeight,10), currentViewportWidth = parseInt(elem.clientWidth,10) ; if( ( currentViewportWidth > this.originalStatus.width ) /* && ( parseInt(this._modalDivStyle.maxWidth,10) >= Element.elementWidth(this._modalDiv) )*/ ){ /** * The viewport width has expanded */ this._modalDivStyle.width = this._modalDivStyle.maxWidth; } else { /** * The viewport width has not changed or reduced */ //this._modalDivStyle.width = (( currentViewportWidth * this.originalStatus.width ) / this.originalStatus.viewportWidth ) + 'px'; this._modalDivStyle.width = (~~( currentViewportWidth * 0.9)) + 'px'; } if( (currentViewportHeight > this.originalStatus.height) && (parseInt(this._modalDivStyle.maxHeight,10) >= Element.elementHeight(this._modalDiv) ) ){ /** * The viewport height has expanded */ //this._modalDivStyle.maxHeight = this._modalDivStyle.height = this._modalDivStyle.maxHeight; } else { /** * The viewport height has not changed, or reduced */ this._modalDivStyle.height = (~~( currentViewportHeight * 0.9)) + 'px'; } this._resizeContainer(); this._reposition(); this._resizeTimeout = undefined; }, /** * Navigation click handler * * @method _onClick * @param {Event} ev * @private */ _onClick: function(ev) { var tgtEl = Event.element(ev); if (Css.hasClassName(tgtEl, 'ink-close') || Css.hasClassName(tgtEl, 'ink-dismiss') || Element.findUpwardsByClass(tgtEl, 'ink-close') || Element.findUpwardsByClass(tgtEl, 'ink-dismiss') || ( this._options.closeOnClick && (!Element.descendantOf(this._shadeElement, tgtEl) || (tgtEl === this._shadeElement)) ) ) { var alertsInTheModal = Selector.select('.ink-alert',this._shadeElement), alertsLength = alertsInTheModal.length ; for( var i = 0; i < alertsLength; i++ ){ if( Element.descendantOf(alertsInTheModal[i], tgtEl) ){ return; } } Event.stop(ev); this.dismiss(); } }, /** * Responsible for handling the escape key pressing. * * @method _onKeyDown * @param {Event} ev * @private */ _onKeyDown: function(ev) { if (ev.keyCode !== 27 || this._wasDismissed) { return; } this.dismiss(); }, /** * Responsible for setting the size of the modal (and position) based on the viewport. * * @method _resizeContainer * @private */ _resizeContainer: function() { this._contentElement.style.overflow = this._contentElement.style.overflowX = this._contentElement.style.overflowY = 'hidden'; var containerHeight = Element.elementHeight(this._modalDiv); this._modalHeader = Selector.select('.modal-header',this._modalDiv); if( this._modalHeader.length>0 ){ this._modalHeader = this._modalHeader[0]; containerHeight -= Element.elementHeight(this._modalHeader); } this._modalFooter = Selector.select('.modal-footer',this._modalDiv); if( this._modalFooter.length>0 ){ this._modalFooter = this._modalFooter[0]; containerHeight -= Element.elementHeight(this._modalFooter); } this._contentContainer.style.height = containerHeight + 'px'; if( containerHeight !== Element.elementHeight(this._contentContainer) ){ this._contentContainer.style.height = ~~(containerHeight - (Element.elementHeight(this._contentContainer) - containerHeight)) + 'px'; } if( this._markupMode ){ return; } this._contentContainer.style.overflow = this._contentContainer.style.overflowX = 'hidden'; this._contentContainer.style.overflowY = 'auto'; this._contentElement.style.overflow = this._contentElement.style.overflowX = this._contentElement.style.overflowY = 'visible'; }, /** * Responsible for 'disabling' the page scroll * * @method _disableScroll * @private */ _disableScroll: function() { this._oldScrollPos = Element.scroll(); this._onScrollBinded = Ink.bindEvent(function(event) { var tgtEl = Event.element(event); if( !Element.descendantOf(this._modalShadow, tgtEl) ){ Event.stop(event); window.scrollTo(this._oldScrollPos[0], this._oldScrollPos[1]); } },this); Event.observe(window, 'scroll', this._onScrollBinded); Event.observe(document, 'touchmove', this._onScrollBinded); }, /************** * PUBLIC API * **************/ /** * Display this Modal. Useful if you have initialized the modal * @method open * @param {Event} [event] (internal) In case its fired by the internal trigger. */ open: function(event) { if( event ){ Event.stop(event); } var elem = (document.compatMode === "CSS1Compat") ? document.documentElement : document.body; this._resizeTimeout = null; Css.addClassName( this._modalShadow,'ink-shade' ); this._modalShadowStyle.display = this._modalDivStyle.display = 'block'; setTimeout(Ink.bind(function(){ Css.addClassName( this._modalShadow,'visible' ); Css.addClassName( this._modalDiv,'visible' ); }, this),100); /** * Fallback to the old one */ this._contentElement = this._modalDiv; this._shadeElement = this._modalShadow; if( !this._markupMode ){ /** * Setting the content of the modal */ this.setContentMarkup( this._options.markup ); } /** * If any size has been user-defined, let's set them as max-width and max-height */ if( typeof this._options.width !== 'undefined' ){ this._modalDivStyle.width = this._options.width; if( this._options.width.indexOf('%') === -1 ){ this._modalDivStyle.maxWidth = Element.elementWidth(this._modalDiv) + 'px'; } } else { this._modalDivStyle.maxWidth = this._modalDivStyle.width = Element.elementWidth(this._modalDiv)+'px'; } if( parseInt(elem.clientWidth,10) <= parseInt(this._modalDivStyle.width,10) ){ this._modalDivStyle.width = (~~(parseInt(elem.clientWidth,10)*0.9))+'px'; } if( typeof this._options.height !== 'undefined' ){ this._modalDivStyle.height = this._options.height; if( this._options.height.indexOf('%') === -1 ){ this._modalDivStyle.maxHeight = Element.elementHeight(this._modalDiv) + 'px'; } } else { this._modalDivStyle.maxHeight = this._modalDivStyle.height = Element.elementHeight(this._modalDiv) + 'px'; } if( parseInt(elem.clientHeight,10) <= parseInt(this._modalDivStyle.height,10) ){ this._modalDivStyle.height = (~~(parseInt(elem.clientHeight,10)*0.9))+'px'; } this.originalStatus = { viewportHeight: parseInt(elem.clientHeight,10), viewportWidth: parseInt(elem.clientWidth,10), width: parseInt(this._modalDivStyle.maxWidth,10), height: parseInt(this._modalDivStyle.maxHeight,10) }; /** * Let's 'resize' it: */ if(this._options.responsive) { this._onResize(true); Event.observe( window,'resize',this._handlers.resize ); } else { this._resizeContainer(); this._reposition(); } if (this._options.onShow) { this._options.onShow(this); } if(this._options.disableScroll) { this._disableScroll(); } // subscribe events Event.observe(this._shadeElement, 'click', this._handlers.click); Event.observe(document, 'keydown', this._handlers.keyDown); Aux.registerInstance(this, this._shadeElement, 'modal'); this._wasDismissed = false; }, /** * Dismisses the modal * * @method dismiss * @public */ dismiss: function() { if (this._options.onDismiss) { var ret = this._options.onDismiss(this); if (ret === false) { return; } } this._wasDismissed = true; if(this._options.disableScroll) { Event.stopObserving(window, 'scroll', this._onScrollBinded); Event.stopObserving(document, 'touchmove', this._onScrollBinded); } if( this._options.responsive ){ Event.stopObserving(window, 'resize', this._handlers.resize); } // this._modalShadow.parentNode.removeChild(this._modalShadow); if( !this._markupMode ){ this._modalShadow.parentNode.removeChild(this._modalShadow); this.destroy(); } else { Css.removeClassName( this._modalDiv, 'visible' ); Css.removeClassName( this._modalShadow, 'visible' ); var dismissInterval, transitionEndFn = Ink.bindEvent(function(){ if( !dismissInterval ){ return; } this._modalShadowStyle.display = 'none'; Event.stopObserving(document,'transitionend',transitionEndFn); Event.stopObserving(document,'oTransitionEnd',transitionEndFn); Event.stopObserving(document,'webkitTransitionEnd',transitionEndFn); clearInterval(dismissInterval); dismissInterval = undefined; }, this) ; Event.observe(document,'transitionend',transitionEndFn); Event.observe(document,'oTransitionEnd',transitionEndFn); Event.observe(document,'webkitTransitionEnd',transitionEndFn); if( !dismissInterval ){ dismissInterval = setInterval(Ink.bind(function(){ if( this._modalShadowStyle.opacity > 0 ){ return; } else { this._modalShadowStyle.display = 'none'; clearInterval(dismissInterval); dismissInterval = undefined; } }, this),500); } } }, /** * Removes the modal from the DOM * * @method destroy * @public */ destroy: function() { Aux.unregisterInstance(this._instanceId); }, /** * Returns the content DOM element * * @method getContentElement * @return {DOMElement} Modal main cointainer. * @public */ getContentElement: function() { return this._contentContainer; }, /** * Replaces the content markup * * @method setContentMarkup * @param {String} contentMarkup * @public */ setContentMarkup: function(contentMarkup) { if( !this._markupMode ){ this._modalDiv.innerHTML = [contentMarkup].join(''); this._contentContainer = Selector.select(".modal-body",this._modalDiv); if( !this._contentContainer.length ){ // throw 'Missing div with class "modal-body"'; var tempHeader = Selector.select(".modal-header",this._modalDiv); var tempFooter = Selector.select(".modal-footer",this._modalDiv); InkArray.each(tempHeader,Ink.bind(function( element ){ element.parentNode.removeChild(element); },this)); InkArray.each(tempFooter,Ink.bind(function( element ){ element.parentNode.removeChild(element); },this)); var body = document.createElement('div'); Css.addClassName(body,'modal-body'); body.innerHTML = this._modalDiv.innerHTML; this._modalDiv.innerHTML = ''; InkArray.each(tempHeader,Ink.bind(function( element ){ this._modalDiv.appendChild(element); },this)); this._modalDiv.appendChild(body); InkArray.each(tempFooter,Ink.bind(function( element ){ this._modalDiv.appendChild(element); },this)); this._contentContainer = Selector.select(".modal-body",this._modalDiv); } this._contentContainer = this._contentContainer[0]; } else { this._contentContainer.innerHTML = [contentMarkup].join(''); } this._contentElement = this._modalDiv; this._resizeContainer(); } }; return Modal; }); /** * @module Ink.UI.ProgressBar_1 * @author inkdev AT sapo.pt * @version 1 */ Ink.createModule('Ink.UI.ProgressBar', '1', ['Ink.Dom.Selector_1','Ink.Dom.Element_1'], function( Selector, Element ) { 'use strict'; /** * Associated to a .ink-progress-bar element, it provides the necessary * method - setValue() - for the user to change the element's value. * * @class Ink.UI.ProgressBar * @constructor * @version 1 * @param {String|DOMElement} selector * @param {Object} [options] Options * @param {Number} [options.startValue] Percentage of the bar that is filled. Range between 0 and 100. Default: 0 * @param {Function} [options.onStart] Callback that is called when a change of value is started * @param {Function} [options.onEnd] Callback that is called when a change of value ends * * @example * <div class="ink-progress-bar grey" data-start-value="70%"> * <span class="caption">I am a grey progress bar</span> * <div class="bar grey"></div> * </div> * <script> * Ink.requireModules( ['Ink.Dom.Selector_1','Ink.UI.ProgressBar_1'], function( Selector, ProgressBar ){ * var progressBarElement = Ink.s('.ink-progress-bar'); * var progressBarObj = new ProgressBar( progressBarElement ); * }); * </script> */ var ProgressBar = function( selector, options ){ if( typeof selector !== 'object' ){ if( typeof selector !== 'string' ){ throw '[Ink.UI.ProgressBar] :: Invalid selector'; } else { this._element = Selector.select(selector); if( this._element.length < 1 ){ throw "[Ink.UI.ProgressBar] :: Selector didn't find any elements"; } this._element = this._element[0]; } } else { this._element = selector; } this._options = Ink.extendObj({ 'startValue': 0, 'onStart': function(){}, 'onEnd': function(){} },Element.data(this._element)); this._options = Ink.extendObj( this._options, options || {}); this._value = this._options.startValue; this._init(); }; ProgressBar.prototype = { /** * Init function called by the constructor * * @method _init * @private */ _init: function(){ this._elementBar = Selector.select('.bar',this._element); if( this._elementBar.length < 1 ){ throw '[Ink.UI.ProgressBar] :: Bar element not found'; } this._elementBar = this._elementBar[0]; this._options.onStart = Ink.bind(this._options.onStart,this); this._options.onEnd = Ink.bind(this._options.onEnd,this); this.setValue( this._options.startValue ); }, /** * Sets the value of the Progressbar * * @method setValue * @param {Number} newValue Numeric value, between 0 and 100, that represents the percentage of the bar. * @public */ setValue: function( newValue ){ this._options.onStart( this._value); newValue = parseInt(newValue,10); if( isNaN(newValue) || (newValue < 0) ){ newValue = 0; } else if( newValue>100 ){ newValue = 100; } this._value = newValue; this._elementBar.style.width = this._value + '%'; this._options.onEnd( this._value ); } }; return ProgressBar; });
libs/component/index.js
zangxd/ui-react
import React from 'react'; import classnames from 'classnames'; export default class Component extends React.Component { classNames(...args) { return classnames(args); } className(...args) { return this.classNames.apply(this, args.concat([this.props.className])); } style(args) { return Object.assign({}, args, this.props.style) } } Component.propTypes = { className: React.PropTypes.string, style: React.PropTypes.object }; Component.defaultProps = { style: {} };
jestSupport/preprocessor.js
kfiroo/react-native
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction'); const path = require('path'); const transformer = require('../packager/transformer.js'); module.exports = { process(src, file) { // Don't transform node_modules, except react-tools which includes the // untransformed copy of React if ( file.match(/node_modules\/(?!react-tools\/)/) || // (TODO: balpert, cpojer): Remove this once react is updated to 0.14 file.endsWith('performanceNow.js') ) { return src; } return transformer.transform(src, file).code; }, getCacheKey: createCacheKeyFunction([ __filename, path.join(__dirname, '../packager/transformer.js'), path.join(__dirname, '../node_modules/babel-core/package.json'), ]), };
public/js/components/app.js
gonzochic/inox
import React from 'react'; import Overview from 'public/js/components/overview'; import Feed from 'public/js/components/feed'; import Navbar from 'public/js/components/navbar'; import Profile from 'public/js/components/profile'; import profileData from 'public/js/helper/profiledata' import { Router, Route, Link } from 'react-router'; import { history } from 'react-router/lib/HashHistory'; export default class App extends React.Component { constructor(props) { super(props); this.state = { profileName: '', profileId: '' }; } componentWillMount() { profileData.fetchData(() => { this.setState({ profileName: profileData.profile.username, profileId: profileData.profile._id }) }); } render() { return ( <div id={'wrapper'}> <Navbar profileName={this.state.profileName} profileId = {this.state.profileId} /> {this.props.children} <h6>Footer</h6> </div> ); } } React.render(( <Router history={history}> <Route path="/" component={App}> <Route path="overview" component={Overview}/> <Route path="entries/:id" component={Feed}/> <Route path="profiles/:id" component={Profile} /> </Route> </Router> ), document.getElementById('react-content'));
react-flux-mui/js/material-ui/src/svg-icons/av/fiber-pin.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFiberPin = (props) => ( <SvgIcon {...props}> <path d="M5.5 10.5h2v1h-2zM20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zM9 11.5c0 .85-.65 1.5-1.5 1.5h-2v2H4V9h3.5c.85 0 1.5.65 1.5 1.5v1zm3.5 3.5H11V9h1.5v6zm7.5 0h-1.2l-2.55-3.5V15H15V9h1.25l2.5 3.5V9H20v6z"/> </SvgIcon> ); AvFiberPin = pure(AvFiberPin); AvFiberPin.displayName = 'AvFiberPin'; AvFiberPin.muiName = 'SvgIcon'; export default AvFiberPin;
vendor/assets/javascripts/jquery-1.9.1.js
allantokuda/LDT
/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var i, l, thisCache, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, notxml, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== core_strundefined ) { ret = elem.getAttribute( name ); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; while ( (elem = this[i++]) ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self, len = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < len; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.hover = function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 ) { isSuccess = true; statusText = "nocontent"; // if not modified } else if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var value, name, index, easing, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
admin/client/App/screens/List/components/ItemsTable/ItemsTableRow.js
Pop-Code/keystone
import React from 'react'; import classnames from 'classnames'; import ListControl from '../ListControl'; import { Columns } from 'FieldTypes'; import { DropTarget, DragSource } from 'react-dnd'; import { setDragBase, resetItems, reorderItems, setRowAlert, moveItem, } from '../../actions'; const ItemsRow = React.createClass({ propTypes: { columns: React.PropTypes.array, id: React.PropTypes.any, index: React.PropTypes.number, items: React.PropTypes.object, list: React.PropTypes.object, // Injected by React DnD: isDragging: React.PropTypes.bool, // eslint-disable-line react/sort-prop-types connectDragSource: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDropTarget: React.PropTypes.func, // eslint-disable-line react/sort-prop-types connectDragPreview: React.PropTypes.func, // eslint-disable-line react/sort-prop-types }, renderRow (item) { const itemId = item.id; const rowClassname = classnames({ 'ItemList__row--dragging': this.props.isDragging, 'ItemList__row--selected': this.props.checkedItems[itemId], 'ItemList__row--manage': this.props.manageMode, 'ItemList__row--success': this.props.rowAlert.success === itemId, 'ItemList__row--failure': this.props.rowAlert.fail === itemId, }); // item fields var cells = this.props.columns.map((col, i) => { var ColumnType = Columns[col.type] || Columns.__unrecognised__; var linkTo = !i ? `${Keystone.adminPath}/${this.props.list.path}/${itemId}` : undefined; return <ColumnType key={col.path} list={this.props.list} col={col} data={item} linkTo={linkTo} />; }); // add sortable icon when applicable if (this.props.list.sortable) { cells.unshift(<ListControl key="_sort" type="sortable" dragSource={this.props.connectDragSource} />); } // add delete/check icon when applicable if (!this.props.list.nodelete) { cells.unshift(this.props.manageMode ? ( <ListControl key="_check" type="check" active={this.props.checkedItems[itemId]} /> ) : ( <ListControl key="_delete" onClick={(e) => this.props.deleteTableItem(item, e)} type="delete" /> )); } var addRow = (<tr key={'i' + item.id} onClick={this.props.manageMode ? (e) => this.props.checkTableItem(item, e) : null} className={rowClassname}>{cells}</tr>); if (this.props.list.sortable) { return ( // we could add a preview container/image // this.props.connectDragPreview(this.props.connectDropTarget(addRow)) this.props.connectDropTarget(addRow) ); } else { return (addRow); } }, render () { return this.renderRow(this.props.item); }, }); module.exports = exports = ItemsRow; // Expose Sortable /** * Implements drag source. */ const dragItem = { beginDrag (props) { const send = { ...props }; props.dispatch(setDragBase(props.item, props.index)); return { ...send }; }, endDrag (props, monitor, component) { if (!monitor.didDrop()) { props.dispatch(resetItems(props.id)); return; } const page = props.currentPage; const pageSize = props.pageSize; // If we were dropped onto a page change target, then droppedOn.prevSortOrder etc will be // set by that target, and we should use those values. If we were just dropped onto a new row // then we need to calculate these values ourselves. const droppedOn = monitor.getDropResult(); const prevSortOrder = droppedOn.prevSortOrder || props.sortOrder; // To explain the following line, suppose we are on page 3 and there are 10 items per page. // Previous to this page, there are (3 - 1)*10 = 20 items before us. If we have index 6 // on this page, then we're the 7th item to display (index starts from 0), and so we // want to update the display order to 20 + 7 = 27. const newSortOrder = droppedOn.newSortOrder || (page - 1) * pageSize + droppedOn.index + 1; // If we were dropped on a page change target, then droppedOn.gotToPage will be set, and we should // pass this to reorderItems, which will then change the page for the user. props.dispatch(reorderItems(props.item, prevSortOrder, newSortOrder, Number(droppedOn.goToPage))); }, }; /** * Implements drag target. */ const dropItem = { drop (props, monitor, component) { return { ...props }; }, hover (props, monitor, component) { // reset row alerts if (props.rowAlert.success || props.rowAlert.fail) { props.dispatch(setRowAlert({ reset: true, })); } const dragged = monitor.getItem().index; const over = props.index; // self if (dragged === over) { return; } props.dispatch(moveItem(dragged, over, props)); monitor.getItem().index = over; }, }; /** * Specifies the props to inject into your component. */ function dragProps (connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview(), }; } function dropProps (connect) { return { connectDropTarget: connect.dropTarget(), }; }; exports.Sortable = DragSource('item', dragItem, dragProps)(DropTarget('item', dropItem, dropProps)(ItemsRow));
example/src/Video/Video.js
lokiuz/redraft
/* eslint-disable jsx-a11y/media-has-caption */ import React from 'react'; import PropTypes from 'prop-types'; import withHover from '../withHover'; import './Video.css'; const imgStyles = { medium: { height: 300, }, small: { height: 200, }, }; const figStyles = { small: { float: 'left', margin: 20, }, }; const Video = ({ src, caption, display, onMouseEnter, onMouseLeave, isHovered, }) => ( <figure className={!isHovered ? 'Video-wrap' : 'Video-wrap hovered'} style={figStyles[display]} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} > {isHovered && caption && <span className="Video-caption">{caption}</span>} <video className="Video" src={src} controls style={imgStyles[display]} /> </figure> ); Video.propTypes = { src: PropTypes.string.isRequired, caption: PropTypes.string, display: PropTypes.string.isRequired, onMouseEnter: PropTypes.func.isRequired, onMouseLeave: PropTypes.func.isRequired, isHovered: PropTypes.bool, }; Video.defaultProps = { caption: '', isHovered: false, }; export default withHover(Video);
5eShapedCompanion/4.4.5/5eShapedCompanion.js
NathaTerrien/Natha-roll20-api-scripts
var ShapedScripts = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const Roll20 = __webpack_require__(1); const roll20 = new Roll20(); const parseModule = __webpack_require__(3); const mmFormat = __webpack_require__(4); const myState = roll20.getState('ShapedScripts'); const Logger = __webpack_require__(5); const logger = new Logger('5eShapedCompanion', roll20); const EntityLookup = __webpack_require__(6); const JSONValidator = __webpack_require__(8); const el = new EntityLookup(); const Reporter = __webpack_require__(9); const reporter = new Reporter(roll20, 'Shaped Scripts'); const ShapedScripts = __webpack_require__(10); const srdConverter = __webpack_require__(22); const sanitise = __webpack_require__(23); const mpp = __webpack_require__(24); const shaped = new ShapedScripts(logger, myState, roll20, parseModule.getParser(mmFormat, logger), el, reporter, srdConverter, sanitise, mpp); const _ = __webpack_require__(2); roll20.logWrap = 'roll20'; logger.wrapModule(el); logger.wrapModule(roll20); logger.wrapModule(srdConverter); const jsonValidator = new JSONValidator(__webpack_require__(4)); el.configureEntity('monsters', [ EntityLookup.jsonValidatorAsEntityProcessor(jsonValidator), el.getSpellHydrator(), ], EntityLookup.jsonValidatorAsVersionChecker(jsonValidator)); el.configureEntity('spells', [el.getMonsterSpellUpdater()], EntityLookup.getVersionChecker('0.2.1')); roll20.on('ready', () => { shaped.checkInstall(); shaped.registerEventHandlers(); }); module.exports = { addEntities(entities) { try { if (typeof entities === 'string') { entities = JSON.parse(entities); } // Suppress excessive logging when adding big lists of entities const prevLogLevel = myState.config.logLevel; myState.config.logLevel = Logger.INFO; const result = el.addEntities(entities); myState.config.logLevel = prevLogLevel; const summary = _.mapObject(result, (resultObject, type) => { if (type === 'errors') { return resultObject.length; } return _.mapObject(resultObject, operationResultArray => operationResultArray.length); }); logger.info('Summary of adding entities to the lookup: $$$', summary); logger.info('Details: $$$', result); if (!_.isEmpty(result.errors)) { const message = _.chain(result.errors) .groupBy('entity') .mapObject(entityErrors => _.chain(entityErrors) .pluck('errors') .flatten() .value() ) .map((errors, entityName) => `<li>${entityName}:<ul><li>${errors.join('</li><li>')}</li></ul></li>`) .value(); reporter.reportError(`JSON import error:<ul>${message}</ul>`); } } catch (e) { reporter.reportError('JSON parse error, please see log for more information'); logger.error(e.toString()); logger.error(e.stack); } }, }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { /* globals state, createObj, findObjs, getObj, getAttrByName, sendChat, on, log, Campaign, playerIsGM, spawnFx, spawnFxBetweenPoints, filterObjs, randomInteger */ 'use strict'; const _ = __webpack_require__(2); // noinspection JSUnusedLocalSymbols module.exports = class Roll20Wrapper { getState(module) { if (!state[module]) { state[module] = {}; } return state[module]; } createObj(type, attributes) { return createObj(type, attributes); } findObjs(attributes) { return findObjs(attributes); } filterObjs(attributes) { return filterObjs(attributes); } getObj(type, id) { return getObj(type, id); } getOrCreateObj(type, attributes) { const newAttributes = _.extend(_.clone(attributes), { type }); const existing = this.findObjs(newAttributes); switch (existing.length) { case 0: return this.createObj(type, newAttributes); case 1: return existing[0]; default: throw new Error(`Asked for a single ${type} but more than 1 was found matching attributes: ` + `${JSON.stringify(attributes)}`); } } getAttrByName(character, attrName, valueType) { return getAttrByName(character, attrName, valueType); } checkCharacterFlag(character, flag) { const value = this.getAttrByName(character, flag); switch (typeof value) { case 'boolean': return value; case 'number': return !!value; default: return value === '1' || value === 'on'; } } getAttrObjectByName(character, attrName) { const attr = this.findObjs({ type: 'attribute', characterid: character, name: attrName }); return attr && attr.length > 0 ? attr[0] : null; } getOrCreateAttr(characterId, attrName) { return this.getOrCreateObj('attribute', { characterid: characterId, name: attrName }); } setAttrByName(characterId, attrName, value) { this.getOrCreateAttr(characterId, attrName).set('current', value); } processAttrValue(characterId, attrName, cb) { const attribute = this.getOrCreateAttr(characterId, attrName); attribute.set('current', cb(attribute.get('current'))); } getRepeatingSectionAttrs(characterId, sectionName) { const prefix = `repeating_${sectionName}`; return _.filter(this.findObjs({ type: 'attribute', characterid: characterId }), attr => attr.get('name').indexOf(prefix) === 0); } getRepeatingSectionItemIdsByName(characterId, sectionName) { const re = new RegExp(`repeating_${sectionName}_([^_]+)_name$`); return _.reduce(this.getRepeatingSectionAttrs(characterId, sectionName), (lookup, attr) => { const match = attr.get('name').match(re); if (match) { lookup[attr.get('current').toLowerCase()] = match[1]; } return lookup; }, {}); } getCurrentPage(playerId) { let pageId; if (this.playerIsGM(playerId)) { pageId = this.getObj('player', playerId).get('lastpage'); } else { pageId = this.getCampaign().get('playerspecificpages')[playerId] || this.getCampaign().get('playerpageid'); } return pageId ? this.getObj('page', pageId) : null; } spawnFx(pointsArray, fxType, pageId) { switch (pointsArray.length) { case 1: spawnFx(pointsArray[0].x, pointsArray[0].y, fxType, pageId); break; case 2: spawnFxBetweenPoints(pointsArray[0], pointsArray[1], fxType, pageId); break; default: throw new Error('Wrong number of points supplied to spawnFx: $$$', pointsArray); } } playerIsGM(playerId) { return playerIsGM(playerId); } getCampaign() { return Campaign(); // eslint-disable-line } sendChat(sendAs, message, callback, options) { return sendChat(sendAs, message, callback, options); } on(event, callback) { return on(event, callback); } randomInteger(max) { return randomInteger(max); } log(msg) { return log(msg); } }; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = _; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); /** * A specification of a field that can appear * in the format that this parser processes * @typedef {Object} FieldSpec * @property {FieldSpec[]} [contentModel] - list of child fieldSpecs for complex content * @property {boolean} [bare] - if true this field appears as a bare value with no parseToken in front of it * @property {string} [parseToken] - the token that defines the beginning of this field (usually case insensitive). Not * used for bare tokens. * @property {string} [pattern] - a pattern that defines the value of this field. For bare properties this will * determine if the field matches at all, whereas for normal ones this will just be used to validate them * @property {number} [forNextMatchGroup] - the 1-based index of the match group from the supplied pattern that will * contain text that should be handed to the next parser rather than used as part of this field. * @property {number} [forPreviousMatchGroup] - the 1-based index of the match group from the supplied pattern that * will contain text that should be handed to the previous parser to complete its value rather than used as part of * this field. Only applicable to bare properties, since ones with a token have a clearly defined start based on the * parseToken * @property {number} [matchGroup=0] - the index of the capturing group in the supplied pattern to use as the value for * this field. If left at the default of 0, the whole match will be used. * @property {boolean} [caseSensitive=false] - If true, the pattern used for the value of this field will be made case * sensitive. Note that parseToken matching is always case insensitive. * @property {string} type - the type of this field. Currently valid values are [orderedContent, unorderedContent, * string, enumType, integer, abililty] * @property {string[]} enumValues - an array of valid values for this field if the type is enumType * @property {number} [minOccurs=1] - the minimum number of times this field should occur in the parent content model. * @property {number} [maxOccurs=1] - the maximum number of times this field should occur in the parent content model. */ /** * * @param {FieldSpec} formatSpec - Root format specification for this parser * @param logger - Logger object to use for reporting errors etc. * @returns {{parse: ((*))}} - A parser that will process text in the format specified by the supplied formatSpec into * JSON objects */ function getParser(formatSpec, logger) { // noinspection JSUnusedGlobalSymbols const parserModule = { makeContentModelParser(fieldSpec, ordered) { const module = this; return { parse(stateManager, textLines, resume) { const parseState = stateManager.enterChildParser(this, resume); let someMatch = false; let canContinue; let stopParser = null; parseState.subParsers = parseState.subParsers || module.makeParserList(fieldSpec.contentModel); if (parseState.resumeParser) { if (!parseState.resumeParser.resumeParse(stateManager, textLines)) { stateManager.leaveChildParser(this); return false; } someMatch = true; } function parseRunner(parser, index, parsers) { if (!parser.parse(stateManager, textLines)) { if (parser.required === 0 || !ordered) { // No match but it's ok to keep looking // through the rest of the content model for one return false; } // No match but one was required here by the content model } else { parser.justMatched = true; if (parser.required > 0) { parser.required--; } parser.allowed--; if (ordered) { // Set all the previous parsers to be exhausted since we've matched // this one and we're in a strictly ordered content model. _.each(parsers.slice(0, index), _.partial(_.extend, _, { allowed: 0 })); } } return true; } do { stopParser = _.find(parseState.subParsers, parseRunner); logger.debug('Stopped at parser $$$', stopParser); canContinue = stopParser && stopParser.justMatched; if (stopParser) { someMatch = someMatch || stopParser.justMatched; stopParser.justMatched = false; } // Lose any parsers that have used up all their cardinality already parseState.subParsers = _.reject(parseState.subParsers, { allowed: 0 }); } while (!_.isEmpty(parseState.subParsers) && !_.isEmpty(textLines) && canContinue); stateManager.leaveChildParser(this, someMatch ? parseState : undefined); return someMatch; }, resumeParse(stateManager, textLines) { return this.parse(stateManager, textLines, true); }, complete(parseState/* , finalText*/) { const missingContent = _.filter(parseState.subParsers, 'required'); if (!_.isEmpty(missingContent)) { throw new MissingContentError(missingContent); } }, }; }, matchParseToken(myParseState, textLines) { if (_.isEmpty(textLines) || this.bare) { return !_.isEmpty(textLines); } const re = new RegExp(`^(.*?)(${this.parseToken})(?:[\\s.]+|$)`, 'i'); const match = textLines[0].match(re); if (match) { logger.debug('Found match $$$', match[0]); myParseState.forPrevious = match[1]; myParseState.text = ''; textLines[0] = textLines[0].slice(match[0].length).trim(); if (!textLines[0]) { textLines.shift(); } } return !!match; }, matchValue(myParseState, textLines) { if (this.pattern && this.bare) { // If this is not a bare value then we can take all the text up to next // token and just validate it at the end. If it is, then the pattern itself // defines whether this field matches and we must run it immediately. if (_.isEmpty(textLines)) { return false; } textLines[0] = textLines[0].trim(); const matchGroup = this.matchGroup || 0; const re = new RegExp(this.pattern, this.caseSensitive ? '' : 'i'); logger.debug('$$$ attempting to match value [$$$] against regexp $$$', this.name, textLines[0], re.toString()); const match = textLines[0].match(re); if (match) { logger.debug('Successful match! $$$', match); myParseState.text = match[matchGroup]; if (!myParseState.forPrevious && this.forPreviousMatchGroup) { logger.debug('Setting forPrevious to $$$', match[this.forPreviousMatchGroup]); myParseState.forPrevious = match[this.forPreviousMatchGroup]; } textLines[0] = textLines[0].slice(match.index + match[0].length); if (this.forNextMatchGroup && match[this.forNextMatchGroup]) { textLines[0] = match[this.forNextMatchGroup] + textLines[0]; } if (!textLines[0]) { myParseState.text += '\n'; textLines.shift(); } return true; } logger.debug('Match failed'); return false; } logger.debug('$$$ standard string match, not using pattern', this.name); myParseState.text = ''; return true; }, orderedContent(fieldSpec) { return this.makeContentModelParser(fieldSpec, true); }, unorderedContent(fieldSpec) { return this.makeContentModelParser(fieldSpec, false); }, string(/* fieldSpec */) { return this.makeSimpleValueParser(); }, enumType(fieldSpec) { const parser = this.makeSimpleValueParser(); if (fieldSpec.bare) { parser.matchValue = function matchValue(myParseState, textLines) { const firstMatch = _.chain(fieldSpec.enumValues) .map(enumValue => { logger.debug('Attempting to parse as enum property $$$', enumValue); const pattern = `^(.*?)(${enumValue})(?:[\\s.]+|$)`; const re = new RegExp(pattern, this.caseSensitive ? '' : 'i'); return textLines[0].match(re); }) .compact() .sortBy(match => match[1].length) .first() .value(); if (firstMatch) { logger.debug('Finished trying to parse as enum property, match: $$$', firstMatch); myParseState.text = firstMatch[2]; myParseState.forPrevious = firstMatch[1]; textLines[0] = textLines[0].slice(firstMatch.index + firstMatch[0].length); if (!textLines[0]) { textLines.shift(); } return true; } return false; }; } return parser; }, number(fieldSpec) { const parser = this.makeSimpleValueParser(); parser.typeConvert = function typeConvert(textValue) { const parts = textValue.split('/'); let intVal; if (parts.length > 1) { intVal = parts[0] / parts[1]; } else { intVal = parseInt(textValue, 10); } if (_.isNaN(intVal)) { throw new BadValueError(fieldSpec.name, textValue, '[Integer]'); } return intVal; }; return parser; }, ability(/* fieldSpec */) { const parser = this.number(); parser.matchValue = function matchValue(parseState, textLines) { if (_.isEmpty(textLines)) { return false; } textLines[0] = textLines[0].trim(); const re = new RegExp('^([\\sa-z\\(\\)]*)(\\d+(?:\\s?\\([\\-+\\d]+\\))?)', 'i'); logger.debug('Attempting to match value [$$$] against regexp $$$', textLines[0].trim(), re.toString()); let match = textLines[0].match(re); if (match) { logger.debug('Successful match $$$', match); parseState.text = match[2]; textLines[0] = match[1] + textLines[0].slice(match.index + match[0].length); if (!textLines[0]) { textLines.shift(); } return true; } else if (textLines[1]) { // Try and match against the next line in case we have a two line format textLines[1] = textLines[1].trim(); match = textLines[1].match(/^(\d+)(?:\s?\([\-+\d]+\))?/); if (match) { logger.debug('Successful ability match $$$ on next line - looks like two line format', match); parseState.text = match[1]; textLines[1] = textLines[1].slice(match[0].length); if (!textLines[0]) { textLines.shift(); } if (!textLines[0]) { textLines.shift(); } return true; } } return false; }; return parser; }, heading(fieldSpec) { fieldSpec.bare = true; const parser = this.makeSimpleValueParser(); parser.skipOutput = true; return parser; }, makeSimpleValueParser() { const module = this; return { parse(stateManager, textLines) { const parseState = stateManager.enterChildParser(this); const match = this.matchParseToken(parseState, textLines) && this.matchValue(parseState, textLines); if (match) { stateManager.completeCurrentStack(parseState.forPrevious); delete parseState.forPrevious; stateManager.leaveChildParser(this, parseState); } else { stateManager.leaveChildParser(this); } return match; }, complete(parseState, finalText) { parseState.text += finalText || ''; if (parseState.text) { parseState.value = this.extractValue(parseState.text); parseState.value = this.typeConvert(parseState.value); parseState.setOutputValue(); } }, extractValue(text) { text = text.trim(); if (this.pattern && !this.bare) { const regExp = new RegExp(this.pattern, this.caseSensitive ? '' : 'i'); const match = text.match(regExp); if (match) { const matchGroup = this.matchGroup || 0; return match[matchGroup]; } throw new BadValueError(this.name, text, regExp); } else { return text; } }, typeConvert(textValue) { return textValue; }, resumeParse(stateManager, textLines) { if (_.isEmpty(textLines)) { return false; } const parseState = stateManager.enterChildParser(this, true); parseState.text += `${textLines.shift()}\n`; stateManager.leaveChildParser(this, parseState); return true; }, matchParseToken: module.matchParseToken, matchValue: module.matchValue, }; }, makeBaseParseState(skipOutput, propertyPath, outputObject, completedObjects) { return { text: '', getObjectValue() { let value = outputObject; const segments = _.clone(propertyPath); while (segments.length) { const prop = segments.shift(); if (prop.flatten) { continue; } value = value[prop.name]; if (_.isArray(value)) { value = _.last(value); } } return value; }, setOutputValue() { if (skipOutput) { return; } let outputTo = outputObject; const segments = _.clone(propertyPath); while (segments.length > 0) { const prop = segments.shift(); if (prop.flatten) { continue; } let currentValue = outputTo[prop.name]; let newValue = segments.length === 0 ? this.value : {}; if (_.isUndefined(currentValue) && prop.allowed > 1) { currentValue = []; outputTo[prop.name] = currentValue; } if (_.isArray(currentValue)) { let arrayItem = _.find(currentValue, _.partial(_.negate(_.contains), completedObjects)); if (!arrayItem) { currentValue.push(newValue); arrayItem = _.last(currentValue); } newValue = arrayItem; } else if (_.isUndefined(currentValue)) { outputTo[prop.name] = newValue; } else if (segments.length === 0) { throw new Error('Simple value property somehow already had value when we came to set it'); } else { newValue = currentValue; } outputTo = newValue; } }, logWrap: `parseState[${_.pluck(propertyPath, 'name').join('/')}]`, toJSON() { return _.extend(_.clone(this), { propertyPath }); }, }; }, makeParseStateManager() { const incompleteParserStack = []; const currentPropertyPath = []; const completedObjects = []; const module = this; return { outputObject: {}, leaveChildParser(parser, state) { currentPropertyPath.pop(); if (state) { state.resumeParser = _.isEmpty(incompleteParserStack) ? null : _.last(incompleteParserStack).parser; incompleteParserStack.push({ parser, state }); } }, completeCurrentStack(finalText) { while (!_.isEmpty(incompleteParserStack)) { const incomplete = incompleteParserStack.shift(); incomplete.parser.complete(incomplete.state, finalText); const value = incomplete.state.getObjectValue(); if (_.isObject(value) && !incomplete.parser.flatten) { // Crude but this list is unlikely to get that big completedObjects.push(value); } } }, enterChildParser(parser, resume) { currentPropertyPath.push({ name: parser.name, allowed: parser.allowed, flatten: parser.flatten, }); if (!resume || _.isEmpty(incompleteParserStack) || parser !== _.last(incompleteParserStack).parser) { return module.makeBaseParseState(parser.skipOutput, _.clone(currentPropertyPath), this.outputObject, completedObjects); } return incompleteParserStack.pop().state; }, logWrap: 'parserState', toJSON() { return _.extend(_.clone(this), { incompleteParsers: incompleteParserStack, propertyPath: currentPropertyPath, }); }, }; }, parserId: 0, parserAttributes: [ 'forPreviousMatchGroup', 'forNextMatchGroup', 'parseToken', 'flatten', 'pattern', 'matchGroup', 'bare', 'caseSensitive', 'name', 'skipOutput', ], getParserFor(fieldSpec) { logger.debug('Making parser for field $$$', fieldSpec); const parserBuilder = this[fieldSpec.type]; if (!parserBuilder) { throw new Error(`Can\'t make parser for type ${fieldSpec.type}`); } const parser = parserBuilder.call(this, fieldSpec); parser.required = _.isUndefined(fieldSpec.minOccurs) ? 1 : fieldSpec.minOccurs; parser.allowed = _.isUndefined(fieldSpec.maxOccurs) ? 1 : fieldSpec.maxOccurs; _.extend(parser, _.pick(fieldSpec, this.parserAttributes)); _.defaults(parser, { parseToken: parser.name, }); parser.id = this.parserId++; parser.logWrap = `parser[${parser.name}]`; return parser; }, makeParserList(contentModelArray) { const module = this; return _.chain(contentModelArray) .reject('noParse') .reduce((parsers, fieldSpec) => { parsers.push(module.getParserFor(fieldSpec)); return parsers; }, []) .value(); }, logWrap: 'parseModule', }; logger.wrapModule(parserModule); const parser = parserModule.getParserFor(formatSpec); return { parse(text) { logger.debug('Text: $$$', text); const textLines = _.chain(text.split('\n')) .invoke('trim') .compact() .value(); logger.debug(parser); const stateManager = parserModule.makeParseStateManager(); const success = parser.parse(stateManager, textLines); while (success && !_.isEmpty(textLines)) { parser.resumeParse(stateManager, textLines); } stateManager.completeCurrentStack(textLines.join('\n')); if (success && textLines.length === 0) { stateManager.outputObject.version = formatSpec.formatVersion; logger.info(stateManager.outputObject); return stateManager.outputObject; } return null; }, }; } /** * @constructor */ function ParserError(message) { // noinspection JSUnusedGlobalSymbols this.message = message; } ParserError.prototype = new Error(); /** * @constructor */ function MissingContentError(missingFieldParsers) { this.missingFieldParsers = missingFieldParsers; this.message = '<ul>'; this.message += _.reduce(this.missingFieldParsers, (memo, parser) => `${memo}<li>Field ${parser.parseToken} should have appeared ${parser.required} more times</li>` , ''); this.message += '</ul>'; } MissingContentError.prototype = new ParserError(); /** * @constructor */ function BadValueError(name, value, pattern) { 'use strict'; this.name = name; this.value = value; this.pattern = pattern; // noinspection JSUnusedGlobalSymbols this.message = `Bad value [${this.value}] for field [${this.name}]. Should have matched pattern: ${this.pattern}`; } BadValueError.prototype = new ParserError(); module.exports = { getParser, MissingContentError, BadValueError, ParserError, }; /***/ }, /* 4 */ /***/ function(module, exports) { module.exports = { "formatVersion": "0.2", "name": "monsters", "maxOccurs": "Infinity", "type": "orderedContent", "bare": true, "contentModel": [ { "name": "coreInfo", "type": "orderedContent", "flatten": true, "contentModel": [ { "name": "name", "type": "string", "bare": "true" }, { "name": "size", "enumValues": [ "Tiny", "Small", "Medium", "Large", "Huge", "Gargantuan" ], "type": "enumType", "bare": "true" }, { "name": "type", "type": "string", "bare": "true", "pattern": "^([\\w\\s\\(\\),-]+),", "matchGroup": 1 }, { "name": "alignment", "type": "enumType", "enumValues": [ "lawful good", "lawful neutral", "lawful evil", "neutral good", "neutral evil", "neutral", "chaotic good", "chaotic neutral", "chaotic evil", "unaligned", "any alignment", "any good alignment", "any non-good alignment", "any evil alignment", "any non-evil alignment", "any lawful alignment", "any non-lawful alignment", "any chaotic alignment", "any non-chaotic alignment", "construct", "(?:lawful|neutral|chaotic) (?:good|neutral|evil) \\(\\d+%\\) or (?:lawful|neutral|chaotic) (?:good|neutral|evil) \\(\\d+%\\)" ], "bare": true } ] }, { "name": "attributes", "type": "unorderedContent", "flatten": true, "contentModel": [ { "name": "AC", "parseToken": "armor class", "pattern": "\\d+\\s*(?:\\([^)]*\\))?", "type": "string" }, { "name": "HP", "parseToken": "hit points", "type": "string", "pattern": "\\d+(?:\\s?\\(\\s?\\d+d\\d+(?:\\s?[-+]\\s?\\d+)?\\s?\\))?" }, { "name": "speed", "minOccurs": 0, "type": "string", "pattern": "^\\d+\\s?ft[\\.]?(,\\s?(fly|swim|burrow|climb)\\s\\d+\\s?ft[\\.]?)*(\\s?\\([^\\)]+\\))?$" }, { "name": "strength", "parseToken": "str", "type": "ability" }, { "name": "dexterity", "parseToken": "dex", "type": "ability" }, { "name": "constitution", "parseToken": "con", "type": "ability" }, { "name": "intelligence", "parseToken": "int", "type": "ability" }, { "name": "wisdom", "parseToken": "wis", "type": "ability" }, { "name": "charisma", "parseToken": "cha", "type": "ability" }, { "name": "savingThrows", "minOccurs": 0, "parseToken": "saving throws", "type": "string", "pattern": "(?:(?:^|,\\s*)(?:Str|Dex|Con|Int|Wis|Cha)\\s+[\\-\\+]\\d+)+" }, { "name": "skills", "minOccurs": 0, "type": "string", "pattern": "(?:(?:^|,\\s*)(?:Acrobatics|Animal Handling|Arcana|Athletics|Deception|History|Insight|Intimidation|Investigation|Medicine|Nature|Perception|Performance|Persuasion|Religion|Sleight of Hand|Stealth|Survival|Influence|Society)\\s+[\\-\\+]\\d+)+" }, { "minOccurs": 0, "type": "string", "name": "damageVulnerabilities", "parseToken": "damage vulnerabilities" }, { "minOccurs": 0, "type": "string", "name": "damageResistances", "parseToken": "damage resistances" }, { "minOccurs": 0, "type": "string", "name": "damageImmunities", "parseToken": "damage immunities" }, { "minOccurs": 0, "type": "string", "name": "conditionImmunities", "parseToken": "condition immunities" }, { "name": "senses", "type": "string", "minOccurs": 0, "pattern": "(?:(?:^|,\\s*)(?:blindsight|darkvision|tremorsense|truesight)\\s+\\d+\\s*ft\\.?(?: or \\d+ ft\\. while deafened)?(?:\\s?\\([^\\)]+\\))?)+" }, { "name": "passivePerception", "parseToken": ",?\\s*passive Perception", "minOccurs": 0, "type": "number", "skipOutput": true }, { "name": "spells", "minOccurs": 0, "type": "string" }, { "name": "languages", "minOccurs": 0, "type": "string" } ] }, { "name": "challenge", "type": "string", "pattern": "^\\s*(\\d+(?:\\s*\\/\\s*\\d)?)\\s*(?:\\(\\s*[\\d,]+\\s*XP\\s*\\)\\s*)?$", "matchGroup": 1 }, { "name": "traitSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "traits", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "pattern": "(^|.*?[a-z]\\.\\s?)((?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|to|in|the|with|and|or|a)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "bare": true, "caseSensitive": true }, { "name": "recharge", "type": "string", "pattern": "^\\(([^\\)]+)\\)", "bare": true, "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "actionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Actions$" }, { "name": "actions", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "pattern": "(^|.*?[a-z]\\.\\s?)((?:\\d+\\.\\s?)?(?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|in|to|with|the|and|or|a|\\+\\d+)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "bare": true, "caseSensitive": true }, { "name": "recharge", "type": "string", "bare": true, "pattern": "^\\(([^\\)]+)\\)", "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "reactionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "reactionHeader", "type": "heading", "bare": true, "pattern": "^Reactions$" }, { "name": "reactions", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "pattern": "(^|.*?[a-z]\\.\\s?)((?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|in|to|with|the|and|or|a)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "bare": true, "caseSensitive": true }, { "name": "recharge", "type": "string", "bare": true, "pattern": "^\\(([^\\)]+)\\)", "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "legendaryActionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Legendary Actions$" }, { "name": "legendaryPoints", "type": "number", "bare": true, "pattern": "^The[ \\w]+can take (\\d+) legendary actions.*?start of its turn[.]?", "matchGroup": 1 }, { "name": "legendaryActions", "type": "orderedContent", "minOccurs": 1, "maxOccurs": "Infinity", "contentModel": [ { "name": "name", "type": "string", "bare": true, "pattern": "(^|.*?[a-z]\\.\\s?)((?:[A-Z][\\w\\-']+[,:!]?|A)(?:\\s(?:[A-Z][\\w\\-']+[,:!]?|of|with|to|the|and|or|a)+)*)(\\s?\\([^\\)]+\\))?\\.(?!$)", "matchGroup": 2, "forPreviousMatchGroup": 1, "forNextMatchGroup": 3, "caseSensitive": true }, { "name": "cost", "type": "number", "bare": true, "pattern": "^\\s*\\(\\s*costs (\\d+) actions\\s*\\)", "matchGroup": 1, "minOccurs": 0 }, { "name": "text", "bare": true, "type": "string" } ] } ] }, { "name": "lairActionSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Lair Actions$" }, { "name": "lairActions", "type": "string", "bare": true, "minOccurs": 1, "maxOccurs": "Infinity" } ] }, { "name": "regionalEffectsSection", "type": "orderedContent", "minOccurs": 0, "maxOccurs": 1, "flatten": true, "contentModel": [ { "name": "actionHeader", "type": "heading", "bare": true, "pattern": "^Regional Effects$" }, { "name": "regionalEffects", "type": "string", "minOccurs": 1, "maxOccurs": "Infinity", "bare": true }, { "name": "regionalEffectsFade", "type": "string", "bare": true } ] } ] }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); function stringify(object) { if (object === undefined) { return object; } return typeof object === 'string' ? object : JSON.stringify(object, (key, value) => (key !== 'logWrap' && key !== 'isLogWrapped' ? value : undefined) ); } function wrapFunctions(object, moduleName, makeWrapper) { const funcs = getAllFuncs(object); return _.each(funcs, funcName => (object[funcName] = makeWrapper(funcName, object[funcName], moduleName))); } function getAllFuncs(obj) { let props = []; let current = obj; do { props = props.concat(Object.getOwnPropertyNames(current)); } while ((current = Object.getPrototypeOf(current)) && current !== Object.prototype); return props.sort().filter((e, i, arr) => (e !== arr[i + 1] && typeof obj[e] === 'function')); } module.exports = class Logger { constructor(loggerName, roll20) { this.prefixString = ''; const state = roll20.getState('roll20-logger'); state[loggerName] = state[loggerName] || Logger.levels.INFO; roll20.on('chat:message', (msg) => { if (msg.type === 'api' && msg.content.startsWith('!logLevel')) { const parts = msg.content.split(/\s/); if (parts.length > 2) { if (!state[parts[1]]) { roll20.sendChat('Logger', `Unrecognised logger name ${parts[1]}`); return; } state[parts[1]] = Logger.levels[parts[2].toUpperCase()] || Logger.levels.INFO; } } }); function shouldLog(level) { return level <= state[loggerName]; } function outputLog(level, message) { if (!shouldLog(level)) { return; } const args = arguments.length > 2 ? _.toArray(arguments).slice(2) : []; let processedMessage = stringify(message); if (processedMessage) { processedMessage = processedMessage.replace(/\$\$\$/g, () => stringify(args.shift())); } // noinspection NodeModulesDependencies roll20.log(`${loggerName} ${Date.now()} ` + `${Logger.getLabel(level)} : ${shouldLog(Logger.levels.TRACE) ? this.prefixString : ''}` + `${processedMessage}`); } _.each(Logger.levels, (level, levelName) => { this[levelName.toLowerCase()] = _.partial(outputLog, level); }); this.wrapModule = function wrapModule(modToWrap) { if (shouldLog(Logger.levels.TRACE)) { wrapFunctions(modToWrap, modToWrap.logWrap, this.wrapFunction.bind(this)); modToWrap.isLogWrapped = true; } return modToWrap; }; this.getLogTap = function getLogTap(level, messageString) { return _.partial(outputLog, level, messageString); }; this.wrapFunction = function wrapFunction(name, func, moduleName) { if (shouldLog(Logger.levels.TRACE)) { if (name === 'toJSON' || moduleName === 'roll20' && name === 'log') { return func; } const logger = this; return function functionWrapper() { logger.trace('$$$.$$$ starting with this value: $$$ and args $$$', moduleName, name, this, arguments); logger.prefixString = `${logger.prefixString} `; const retVal = func.apply(this, arguments); logger.prefixString = logger.prefixString.slice(0, -2); logger.trace('$$$.$$$ ending with return value $$$', moduleName, name, retVal); if (retVal && retVal.logWrap && !retVal.isLogWrapped) { logger.wrapModule(retVal); } return retVal; }; } return func; }; } static getLabel(logLevel) { const logPair = _.chain(Logger.levels).pairs().find(pair => pair[1] === logLevel).value(); return logPair ? logPair[0] : 'UNKNOWN'; } static get levels() { return { OFF: 0, ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4, TRACE: 5, }; } }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); module.exports = class EntityLookup { constructor() { this.entities = {}; this.noWhiteSpaceEntities = {}; this.entityProcessors = {}; this.versionCheckers = {}; } configureEntity(entityName, processors, versionChecker) { this.entities[entityName] = {}; this.noWhiteSpaceEntities[entityName] = {}; this.entityProcessors[entityName] = processors || []; this.versionCheckers[entityName] = versionChecker || _.constant(true); } addEntities(entitiesObject) { const results = { errors: [], }; _.chain(entitiesObject) .omit('version', 'patch') .each((entityArray, type) => { results[type] = { withErrors: [], skipped: [], deleted: [], patched: [], added: [], }; if (!this.entities[type]) { results.errors.push({ entity: 'general', errors: [`Unrecognised entity type ${type}`] }); return; } if (!this.versionCheckers[type](entitiesObject.version, results.errors)) { return; } _.each(entityArray, (entity) => { let key = entity.name.toLowerCase(); let operation = !!this.entities[type][key] ? (entitiesObject.patch ? 'patched' : 'skipped') : 'added'; if (operation === 'patched') { entity = patchEntity(this.entities[type][key], entity); if (!entity) { operation = 'deleted'; delete this.entities[type][key]; delete this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; } } if (_.contains(['patched', 'added'], operation)) { const processed = _.reduce(this.entityProcessors[type], utils.executor, { entity, type, version: entitiesObject.version, errors: [], }); if (!_.isEmpty(processed.errors)) { processed.entity = processed.entity.name; results.errors.push(processed); operation = 'withErrors'; } else { if (processed.entity.name.toLowerCase() !== key) { results[type].deleted.push(key); delete this.entities[type][key]; delete this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; key = processed.entity.name.toLowerCase(); } this.entities[type][key] = processed.entity; this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')] = processed.entity; } } results[type][operation].push(key); }); }); return results; } findEntity(type, name, tryWithoutWhitespace) { const key = name.toLowerCase(); if (!this.entities[type]) { throw new Error(`Unrecognised entity type ${type}`); } let found = this.entities[type][key]; if (!found && tryWithoutWhitespace) { found = this.noWhiteSpaceEntities[type][key.replace(/\s+/g, '')]; } return found && utils.deepClone(found); } searchEntities(type, criteria) { function containsSomeIgnoreCase(array, testValues) { testValues = (_.isArray(testValues) ? testValues : [testValues]).map(s => s.toLowerCase()); return !!_.chain(array) .map(s => s.toLowerCase()) .intersection(testValues) .value().length; } return _.reduce(criteria, (results, criterionValue, criterionField) => { const re = new RegExp(criterionValue, 'i'); const matcher = (entity) => { const value = entity[criterionField]; switch (typeof value) { case 'string': return value.match(re); case 'boolean': case 'number': return value === criterionValue; case 'object': return _.isArray(value) && containsSomeIgnoreCase(value, criterionValue); default: return false; } }; return results.filter(matcher); }, this.getAll(type)); } getAll(type) { if (!this.entities[type]) { throw new Error(`Unrecognised entity type: ${type}`); } return utils.deepClone(_.values(this.entities[type])); } /** * Gets all of the keys for the specified entity type * @param {string} type - The entity type to retrieve keys for (either 'monster' or 'spell') * @param {boolean} sort - True if the returned array should be sorted alphabetically; false otherwise * @function * @public * @name EntityLookup#getKeys * @return {Array} An array containing all keys for the specified entity type */ getKeys(type, sort) { if (!this.entities[type]) { throw new Error(`Unrecognised entity type: ${type}`); } const keys = _.keys(this.entities[type]); if (sort) { keys.sort(); } return keys; } /** * Gets spell hydrator * @function * @public * @name EntityLookup#getSpellHydrator * @return {function} */ getSpellHydrator() { const self = this; return function spellHydrator(monsterInfo) { const monster = monsterInfo.entity; if (monster.spells) { const spellArray = monster.spells.split(', '); monster.spells = _.map(spellArray, spellName => self.findEntity('spells', spellName) || spellName); } return monsterInfo; }; } getMonsterSpellUpdater() { const self = this; return function spellUpdater(spellInfo) { const spell = spellInfo.entity; _.chain(self.entities.monsters) .pluck('spells') .compact() .each(spellArray => { const spellIndex = _.findIndex(spellArray, monsterSpell => { if (typeof monsterSpell === 'string') { return monsterSpell.toLowerCase() === spell.name.toLowerCase(); } return monsterSpell !== spell && monsterSpell.name.toLowerCase() === spell.name.toLowerCase(); }); if (spellIndex !== -1) { spellArray[spellIndex] = spell; } }); return spellInfo; }; } toJSON() { return { monsterCount: _.size(this.entities.monsters), spellCount: _.size(this.entities.spells) }; } get logWrap() { return 'entityLookup'; } static jsonValidatorAsEntityProcessor(jsonValidator) { return function jsonValidatorEntityProcessor(entityInfo) { const wrapper = { version: entityInfo.version, }; wrapper[entityInfo.type] = [entityInfo.entity]; const errors = jsonValidator.validate(wrapper); const flattenedErrors = _.chain(errors).values().flatten().value(); entityInfo.errors = entityInfo.errors.concat(flattenedErrors); return entityInfo; }; } static jsonValidatorAsVersionChecker(jsonValidator) { return EntityLookup.getVersionChecker(jsonValidator.getVersionNumber()); } static getVersionChecker(requiredVersion) { function pruneToMinor(versionString) { return versionString.split('.', 2).join('.'); } return function versionChecker(version, errorsArray) { const prunedVersion = pruneToMinor(version); const prunedRequiredVersion = pruneToMinor(requiredVersion); const valid = prunedVersion === prunedRequiredVersion; if (!valid) { errorsArray.push({ entity: 'general', errors: [`Incorrect entity objects version: [${version}]. Required is: ${requiredVersion}`], }); } return valid; }; } }; function patchEntity(original, patch) { if (patch.remove) { return undefined; } return _.mapObject(original, (propVal, propName) => { if (propName === 'name' && patch.newName) { return patch.newName; } return patch[propName] || propVal; }); } /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); // noinspection JSUnusedGlobalSymbols module.exports = { deepExtend(original, newValues) { if (!original) { original = _.isArray(newValues) ? [] : {}; } _.each(newValues, (value, key) => { if (_.isArray(original[key])) { if (!_.isArray(value)) { original[key].push(value); } else { original[key] = _.map(value, (item, index) => { if (_.isObject(item)) { return this.deepExtend(original[key][index], item); } return item !== undefined ? item : original[key][index]; }); } } else if (_.isObject(original[key])) { original[key] = this.deepExtend(original[key], value); } else { original[key] = value; } }); return original; }, createObjectFromPath(pathString, value) { const newObject = {}; _.reduce(pathString.split(/\./), (object, pathPart, index, pathParts) => { const match = pathPart.match(/([^.\[]*)(?:\[(\d+)\])?/); const newVal = index === pathParts.length - 1 ? value : {}; if (match[2]) { object[match[1]] = []; object[match[1]][match[2]] = newVal; } else { object[match[1]] = newVal; } return newVal; }, newObject); return newObject; }, getObjectFromPath(obj, path) { path = path.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties path = path.replace(/^\./, ''); // strip a leading dot path.split('.').every(segment => (obj = obj[segment])); return obj; }, deepClone(object) { return JSON.parse(JSON.stringify(object)); }, executor() { switch (arguments.length) { case 0: return undefined; case 1: return arguments[0](); default: // Fall through } const args = Array.apply(null, arguments).slice(2); args.unshift(arguments[0]); return arguments[1].apply(null, args); }, /** * Gets a string as 'Title Case' capitalizing the first letter of each word (i.e. 'the grapes of wrath' -> 'The * Grapes Of Wrath') * @param {string} s - The string to be converted * @return {string} the supplied string in title case */ toTitleCase(s) { return s.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()); }, toOptionsString(options) { let res = options.join(' --'); if (res.length > 0) { res = `--${res}`; } return res; }, /** * Calculates a contrasting color using YIQ luma value * @param {string} hexcolor - the color to calculate a contrasting color for * @return {string} either 'white' or 'black' as determined to be the best contrasting text color for the input color */ getContrastYIQ(hexcolor) { hexcolor = hexcolor.replace('#', ''); if (hexcolor.length === 3) { hexcolor += hexcolor; } const r = parseInt(hexcolor.substr(0, 2), 16); const g = parseInt(hexcolor.substr(2, 2), 16); const b = parseInt(hexcolor.substr(4, 2), 16); const yiq = (r * 299 + g * 587 + b * 114) / 1000; return yiq >= 128 ? 'black' : 'white'; }, /** * Builds an html element as a string using the specified options * @param {string} tag - the html tag type * @param innerHtml - can be a string to be used as the element inner html, or a {tag, innerHtml, attrs} object * in order to build a child html element string * @param attrs - a collection of attributes and their values to be applied to the html element * @return {string} the full html element as a string */ buildHTML(tag, innerHtml, attrs) { if (typeof innerHtml === 'object') { innerHtml = _.map(innerHtml, html => html && this.buildHTML(html.tag, html.innerHtml, html.attrs)).join(''); } let h = `<${tag}`; h += _.chain(attrs) .map((attrVal, attrName) => attrVal !== false && ` ${attrName}="${attrVal}"`) .compact() .value() .join(''); if (innerHtml) { h += `>${innerHtml}</${tag}>`; } else { h += '/>'; } return h; }, missingParam(name) { throw new Error(`Parameter ${name} is required`); }, flattenObject(object) { return _.reduce(object, (explodedProps, propVal, propKey) => { if (_.isObject(propVal)) { return _.extend(explodedProps, this.flattenObject(propVal)); } explodedProps[propKey] = propVal; return explodedProps; }, {}); }, }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); // noinspection JSUnusedGlobalSymbols const validatorFactories = { orderedContent(spec) { return makeContentModelValidator(spec); }, unorderedContent(spec) { return makeContentModelValidator(spec); }, string(spec) { if (spec.pattern) { if (spec.matchGroup) { return regExValidator(spec.name, extractRegexPart(spec.pattern, spec.matchGroup), spec.caseSensitive); } return regExValidator(spec.name, spec.pattern, spec.caseSensitive); } return function noop() { }; }, enumType(spec) { return function enumValidator(value, errors) { if (!_.some(spec.enumValues, enumVal => new RegExp(`^${enumVal}$`, 'i').test(value))) { errors.add(`Value "${value}" should have been one of [${spec.enumValues.join(',')}]`); } }; }, ability(spec) { return regExValidator(spec.name, '\\d+'); }, heading() { // Do not replace with _.noop, these functions get annotated return function noop() { }; }, number() { return function numberValidator(value, errors) { if (typeof value !== 'number') { errors.add(`Value "${value}" should have been a number`); } }; }, }; function extractRegexPart(regexp, matchIndex) { let braceCount = 0; let startIndex = _.findIndex(regexp, (character, index) => { if (character === '(' && (index < 2 || regexp[index - 1] !== '\\') && regexp[index + 1] !== '?') { return ++braceCount === matchIndex; } return false; }); if (startIndex === -1) { throw new Error(`Can\'t find matchgroup ${matchIndex} in regular expression ${regexp}`); } // Lose the bracket startIndex++; let openCount = 1; const endIndex = _.findIndex(regexp.slice(startIndex), (character, index, regexpPart) => { if (character === '(' && regexpPart[index - 1] !== '\\') { openCount++; } if (character === ')' && regexpPart[index - 1] !== '\\') { return --openCount === 0; } return false; }); if (endIndex === -1) { throw new Error(`matchgroup ${matchIndex} seems not to have closing brace in regular expression ${regexp}`); } return regexp.slice(startIndex, startIndex + endIndex); } function regExValidator(fieldName, regexp, caseSensitive) { const re = new RegExp(`^${regexp}$`, caseSensitive ? undefined : 'i'); return function regexpValidate(value, errors) { if (!re.test(value)) { errors.add(`Value "${value}" doesn\'t match pattern /${regexp}/`); } }; } function makeValidator(spec) { const validator = validatorFactories[spec.type](spec); validator.max = _.isUndefined(spec.maxOccurs) ? 1 : spec.maxOccurs; validator.min = _.isUndefined(spec.minOccurs) ? 1 : spec.minOccurs; validator.fieldName = spec.name; return validator; } function makeContentModelValidator(spec) { const parts = _.chain(spec.contentModel) .reject({ type: 'heading' }) .partition({ flatten: true }) .value(); const flattened = _.map(parts[0], makeValidator); const subValidators = _.reduce(parts[1], (subVals, field) => { subVals[field.name] = makeValidator(field); return subVals; }, {}); return function contentModelValidator(object, errors, isFlatten) { let completed = _.reduce(object, (completedMemo, fieldValue, fieldName) => { const validator = subValidators[fieldName]; if (validator) { completedMemo.push(fieldName); errors.pushPath(fieldName); if (_.isArray(fieldValue)) { if (fieldValue.length > validator.max) { errors.add(`Number of entries [${fieldValue.length}] exceeds maximum allowed: ${validator.max}`); } else if (fieldValue.length < validator.min) { errors.add(`Number of entries [${fieldValue.length}] is less than minimum allowed: ${validator.min}`); } else { _.each(fieldValue, (arrayItem, index) => { errors.pushIndex(arrayItem.name ? arrayItem.name : index); validator(arrayItem, errors); errors.popIndex(); }); } } else { validator(fieldValue, errors); } errors.popPath(); } return completedMemo; }, []); let toValidate = _.omit(object, completed); _.chain(flattened) .map(validator => { const subCompleted = validator(toValidate, errors, true); if (subCompleted.length === 0) { return validator; } completed = completed.concat(subCompleted); toValidate = _.omit(toValidate, completed); return null; }) .compact() .each(validator => { if (validator.min > 0) { errors.pushPath(validator.fieldName); errors.add('Section is missing'); errors.popPath(); } }); // If we're a flattened validator (our content is injected directly into the parent content model) // Then we should only report missing fields if there was some match in our content model - otherwise // the parent content model will check the cardinality of this model as a whole if (!isFlatten || !_.isEmpty(completed)) { _.chain(subValidators) .omit(completed) .each(validator => { if (validator.min > 0) { errors.pushPath(validator.fieldName); errors.add('Field is missing'); errors.popPath(); } }); } // Flattened content models shouldn't check for unrecognised fields since they're only parsing // part of the current content model. if (!isFlatten) { _.chain(object) .omit(completed) .each((value, key) => { errors.pushPath(key); errors.add('Unrecognised field'); errors.popPath(); }); } return completed; }; } class Errors { constructor() { this.errors = []; this.currentPath = []; } pushPath(path) { this.currentPath.push(path); } popPath() { return this.currentPath.pop(); } pushIndex(index) { this.currentPath[this.currentPath.length - 1] = `${this.currentPath[this.currentPath.length - 1]}[${index}]`; } popIndex() { this.currentPath[this.currentPath.length - 1] = this.currentPath[this.currentPath.length - 1].replace(/\[[^\]]+\]/, ''); } add(msg) { this.errors.push({ msg, path: _.clone(this.currentPath) }); } getErrors() { return _.chain(this.errors) .groupBy(error => error.path[0]) .mapObject(errorList => _.map(errorList, error => `${error.path.slice(1).join('.')}: ${error.msg}`) ) .value(); } } module.exports = class JSONValidator { constructor(spec) { this.versionProp = { type: 'string', name: 'version', }; this.spec = spec; this.contentValidator = makeValidator({ type: 'unorderedContent', contentModel: [spec, this.versionProp] }); } validate(object) { const errors = new Errors(); this.contentValidator(object, errors); return errors.getErrors(); } getVersionNumber() { return this.spec.formatVersion; } }; /***/ }, /* 9 */ /***/ function(module, exports) { 'use strict'; function makeNormalMessage(scriptName, heading, text) { return '<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">' + '<div style="font-weight: bold; border-bottom: 1px solid black;font-size: 130%;">' + `${scriptName} ${heading}</div>${text}</div>`; } function makeErrorMessage(scriptName, text) { return '<div style="border: 1px solid black; background-color: white; padding: 3px 3px;">' + '<div style="font-weight: bold; border-bottom: 1px solid black;font-size: 130%;color:red;">' + `${scriptName}</div>${text}</div>`; } class Reporter { constructor(roll20, scriptName) { this.roll20 = roll20; this.scriptName = scriptName; } setPlayer(playerId) { this.playerId = playerId; } reportPublic(heading, text) { // Horrible bug with this at the moment - seems to generate spurious chat // messages when noarchive:true is set // sendChat('ShapedScripts', '' + msg, null, {noarchive:true}); this.roll20.sendChat('', `${makeNormalMessage(this.scriptName, heading, text)}`); } reportPlayer(heading, text) { this.roll20.sendChat('', `/w ${this.getPlayerName()} ${makeNormalMessage(this.scriptName, heading, text)}`); } reportError(text) { this.roll20.sendChat('', `/w ${this.getPlayerName()} ${makeErrorMessage(this.scriptName, text)}`); } getPlayerName() { return this.playerId ? this.roll20.getObj('player', this.playerId).get('displayname').split(/ /)[0] : 'gm'; } } module.exports = Reporter; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* globals unescape */ 'use strict'; const _ = __webpack_require__(2); const parseModule = __webpack_require__(3); const makeCommandProc = __webpack_require__(11); const utils = __webpack_require__(7); const UserError = __webpack_require__(12); const Migrator = __webpack_require__(14); const ShapedConfig = __webpack_require__(15); // Modules const AbilityMaker = __webpack_require__(16); const ConfigUI = __webpack_require__(17); const AdvantageTracker = __webpack_require__(18); const RestManager = __webpack_require__(19); const TraitManager = __webpack_require__(20); const AmmoManager = __webpack_require__(21); /** * @typedef {Object} ChatMessage * @property {string} content * @property {string} type * @property {SelectedItem[]} selected * @property {string} rolltemplate */ /** * * @typedef {Object} SelectedItem * @property {string} _id * @property (string _type */ module.exports = ShapedScripts; function ShapedScripts(logger, myState, roll20, parser, entityLookup, reporter, srdConverter, sanitise, mpp) { let addedTokenIds = []; const reportPublic = reporter.reportPublic.bind(reporter); const reportPlayer = reporter.reportPlayer.bind(reporter); const reportError = reporter.reportError.bind(reporter); const commandProc = makeCommandProc('shaped', roll20); const chatWatchers = []; const advantageTracker = new AdvantageTracker(); const traitManager = new TraitManager(); const ammoManager = new AmmoManager(); const abilityMaker = new AbilityMaker(); const modules = [ abilityMaker, new ConfigUI(), advantageTracker, traitManager, new RestManager(), ammoManager, ]; modules.forEach(module => module.configure(roll20, reporter, logger, myState, commandProc)); /** * * @param {ChatMessage} msg */ this.handleInput = function handleInput(msg) { logger.debug(msg); reporter.setPlayer(msg.playerid); if (msg.type !== 'api') { this.triggerChatWatchers(msg); return; } this.oldStyleModulesConfigure(commandProc).processCommand(msg); }; ///////////////////////////////////////// // Command handlers ///////////////////////////////////////// this.applyTokenDefaults = function applyTokenDefaults(options) { _.each(options.selected.graphic, token => { const represents = token.get('represents'); const character = roll20.getObj('character', represents); if (character) { this.applyCharacterDefaults(character); this.getTokenConfigurer(token)(character); } }); }; this.importStatblock = function importStatblock(options) { logger.info('Importing statblocks for tokens $$$', options.selected.graphic); _.each(options.selected.graphic, token => { const error = `Could not find GM notes on either selected token ${token.get('name')} or the character ` + 'it represents. Have you pasted it in correctly?'; const text = token.get('gmnotes'); if (!text) { const char = roll20.getObj('character', token.get('represents')); if (char) { char.get('gmnotes', notes => { if (notes) { return this.processGMNotes(options, token, notes); } return reportError(error); }); } else { return reportError(error); } } return this.processGMNotes(options, token, text); }); }; this.processGMNotes = function processGMNotes(options, token, text) { text = sanitise(unescape(text), logger); const monsters = parser.parse(text).monsters; mpp(monsters, entityLookup); this.importMonsters(monsters, options, token, [ function gmNotesSetter(character) { character.set('gmnotes', text.replace(/\n/g, '<br>')); }, ]); }; this.importMonstersFromJson = function importMonstersFromJson(options) { if (options.all) { options.monsters = entityLookup.getAll('monsters'); delete options.all; } if (_.isEmpty(options.monsters)) { this.showEntityPicker('monster', 'monsters'); } else { this.importMonsters(options.monsters.slice(0, 20), options, options.selected.graphic, []); options.monsters = options.monsters.slice(20); if (!_.isEmpty(options.monsters)) { setTimeout(() => this.importMonstersFromJson(options), 200); } } }; this.importMonsters = function importMonsters(monsters, options, token, characterProcessors) { const characterRetrievalStrategies = []; if (token) { characterProcessors.push(this.getAvatarCopier(token).bind(this)); if (_.size(monsters) === 1) { characterProcessors.push(this.getTokenConfigurer(token).bind(this)); characterProcessors.push(this.getTokenVisionConfigurer(token, monsters[0].senses)); if (options.replace || options.overwrite) { characterRetrievalStrategies.push(this.getTokenRetrievalStrategy(token).bind(this)); } } } if (options.replace) { characterRetrievalStrategies.push(this.nameRetrievalStrategy); } characterRetrievalStrategies.push(this.creationRetrievalStrategy.bind(this)); characterProcessors.push(this.monsterDataPopulator.bind(this)); const errors = []; const importedList = _.chain(monsters) .map(monsterData => { const character = _.reduce(characterRetrievalStrategies, (result, strategy) => result || strategy(monsterData.name, errors), null); if (!character) { logger.error('Failed to find or create character for monster $$$', monsterData.name); return null; } const oldAttrs = roll20.findObjs({ type: 'attribute', characterid: character.id }); _.invoke(oldAttrs, 'remove'); character.set('name', monsterData.name); _.each(characterProcessors, proc => proc(character, monsterData)); return character && character.get('name'); }) .compact() .value(); if (!_.isEmpty(importedList)) { const monsterList = importedList.join('</li><li>'); reportPlayer('Import Success', `Added the following monsters: <ul><li>${monsterList}</li></ul>`); } if (!_.isEmpty(errors)) { const errorList = errors.join('</li><li>'); reportError(`The following errors occurred on import: <ul><li>${errorList}</li></ul>`); } }; this.importSpellsFromJson = function importSpellsFromJson(options) { if (_.isEmpty(options.spells)) { this.showEntityPicker('spell', 'spells'); } else { this.addSpellsToCharacter(options.selected.character, options.spells); } }; this.importSpellListFromJson = function importSpellListFromJson(options) { const spells = entityLookup.searchEntities('spells', _.pick(options, _.keys(ShapedConfig.spellSearchOptions))); const newOpts = _.omit(options, _.keys(ShapedConfig.spellSearchOptions)); newOpts.spells = spells; this.importSpellsFromJson(newOpts); }; this.getEntityCriteriaAdaptor = function getEntityCriteriaAdaptor(entityType) { return function entityCriteriaAdaptor(criterionOption, options) { const result = entityLookup.searchEntities(entityType, criterionOption, options[entityType]); if (result) { // If we get a result, wipe the existing list so that the new one replaces it options[entityType] = []; } return result; }; }; this.showEntityPicker = function showEntityPicker(entityName, entityNamePlural) { const list = entityLookup.getKeys(entityNamePlural, true); if (!_.isEmpty(list)) { // title case the names for better display list.forEach((part, index) => (list[index] = utils.toTitleCase(part))); // create a clickable button with a roll query to select an entity from the loaded json reportPlayer(`${utils.toTitleCase(entityName)} Importer`, `<a href="!shaped-import-${entityName} --?{Pick a ${entityName}|${list.join('|')}}">Click to select a ` + `${entityName}</a>`); } else { reportError(`Could not find any ${entityNamePlural}.<br/>Please ensure you have a properly formatted ` + `${entityNamePlural} json file.`); } }; this.addSpellsToCharacter = function addSpellsToCharacter(character, spells, noreport) { const gender = roll20.getAttrByName(character.id, 'gender'); const defaultIndex = Math.min(myState.config.defaultGenderIndex, myState.config.genderPronouns.length); const defaultPronounInfo = myState.config.genderPronouns[defaultIndex]; const pronounInfo = _.clone(_.find(myState.config.genderPronouns, pronounDetails => new RegExp(pronounDetails.matchPattern, 'i').test(gender)) || defaultPronounInfo); _.defaults(pronounInfo, defaultPronounInfo); const importData = { spells: srdConverter.convertSpells(spells, pronounInfo), }; this.getImportDataWrapper(character).mergeImportData(importData); if (!noreport) { reportPlayer('Import Success', 'Added the following spells: <ul><li>' + `${_.map(importData.spells, spell => spell.name).join('</li><li>')}</li></ul>`); } }; this.monsterDataPopulator = function monsterDataPopulator(character, monsterData) { this.applyCharacterDefaults(character); const converted = srdConverter.convertMonster(monsterData); logger.debug('Converted monster data: $$$', converted); const expandedSpells = converted.spells; delete converted.spells; this.getImportDataWrapper(character).setNewImportData({ npc: converted }); if (expandedSpells) { this.addSpellsToCharacter(character, expandedSpells, true); } return character; }; this.getTokenRetrievalStrategy = function getTokenRetrievalStrategy(token) { return function tokenRetrievalStrategy(name, errors) { if (token) { const character = roll20.getObj('character', token.get('represents')); if (character && roll20.getAttrByName(character.id, 'locked')) { errors.push(`Character with name ${character.get('name')} and id ${character.id}` + ' was locked and cannot be overwritten'); return null; } return character; } return null; }; }; this.nameRetrievalStrategy = function nameRetrievalStrategy(name, errors) { const chars = roll20.findObjs({ type: 'character', name }); if (chars.length > 1) { errors.push(`More than one existing character found with name "${name}". Can\'t replace`); return null; } if (chars[0] && roll20.getAttrByName(chars[0].id, 'locked')) { errors.push(`Character with name ${chars[0].get('name')} and id ${chars[0].id}` + ' was locked and cannot be overwritten'); return null; } return chars[0]; }; this.creationRetrievalStrategy = function creationRetrievalStrategy(name, errors) { if (!_.isEmpty(roll20.findObjs({ type: 'character', name }))) { errors.push(`Can\'t create new character with name "${name}` + '" because one already exists with that name. Perhaps you want --replace?'); return null; } return roll20.createObj('character', { name }); }; this.getAvatarCopier = function getAvatarCopier(token) { return function avatarCopier(character) { character.set('avatar', token.get('imgsrc')); }; }; this.applyCharacterDefaults = function applyCharacterDefaults(character) { _.each(utils.flattenObject(_.omit(myState.config.newCharSettings, 'tokenActions')), (value, key) => { const attrName = ShapedConfig.configToAttributeLookup[key]; if (attrName) { const attribute = roll20.getOrCreateAttr(character.id, attrName); if (value === '***default***' || (_.isBoolean(value) && !value)) { attribute.remove(); } else { attribute.set('current', _.isBoolean(value) ? 'on' : value); } } }); const abilityNames = _.chain(myState.config.newCharSettings.tokenActions) .map((action, actionName) => (action === true ? actionName : action)) .compact() .values() .value(); abilityMaker.addAbilitiesByName(abilityNames, character); }; this.getTokenConfigurer = function getTokenConfigurer(token) { return function tokenConfigurer(character) { token.set('represents', character.id); token.set('name', character.get('name')); const settings = myState.config.tokenSettings; if (settings.number && token.get('name').indexOf('%%NUMBERED%%') === -1) { token.set('name', `${token.get('name')} %%NUMBERED%%`); } _.chain(settings) .pick(['bar1', 'bar2', 'bar3']) .each((bar, barName) => { if (!_.isEmpty(bar.attribute)) { const attribute = roll20.getOrCreateAttr(character.id, bar.attribute); if (attribute) { token.set(`${barName}_value`, attribute.get('current')); if (bar.max) { token.set(`${barName}_max`, attribute.get('max')); } token.set(`showplayers_${barName}`, bar.showPlayers); if (bar.link) { token.set(`${barName}_link`, attribute.id); } } } }); // auras _.chain(settings) .pick(['aura1', 'aura2']) .each((aura, auraName) => { token.set(`${auraName}_radius`, aura.radius); token.set(`${auraName}_color`, aura.color); token.set(`${auraName}_square`, aura.square); }); logger.debug('Settings for tokens: $$$', settings); token.set('showname', settings.showName); token.set('showplayers_name', settings.showNameToPlayers); token.set('showplayers_aura1', settings.showAura1ToPlayers); token.set('showplayers_aura2', settings.showAura2ToPlayers); token.set('light_radius', settings.light.radius); token.set('light_dimradius', settings.light.dimRadius); token.set('light_otherplayers', settings.light.otherPlayers); token.set('light_hassight', settings.light.hasSight); token.set('light_angle', settings.light.angle); token.set('light_losangle', settings.light.losAngle); token.set('light_multiplier', settings.light.multiplier); }; }; this.getTokenVisionConfigurer = function getTokenVisionConfigurer(token, sensesString) { if (_.isEmpty(sensesString)) { return _.noop; } function fullRadiusLightConfigurer() { token.set('light_radius', Math.max(token.get('light_radius') || 0, this.lightRadius)); token.set('light_dimradius', Math.max(token.get('light_dimradius') || 0, this.lightRadius)); } function darkvisionLightConfigurer() { token.set('light_radius', Math.max(token.get('light_radius') || 0, Math.round(this.lightRadius * 1.1666666))); if (!token.get('light_dimradius')) { token.set('light_dimradius', -5); } } const configureFunctions = { blindsight: fullRadiusLightConfigurer, truesight: fullRadiusLightConfigurer, tremorsense: fullRadiusLightConfigurer, darkvision: darkvisionLightConfigurer, }; const re = /(blindsight|darkvision|tremorsense|truesight)\s+(\d+)/; let match; const senses = []; while ((match = sensesString.match(re))) { senses.push({ name: match[1], lightRadius: parseInt(match[2], 10), configureVision: configureFunctions[match[1]], }); sensesString = sensesString.slice(match.index + match[0].length); } return function configureTokenVision() { senses.forEach(sense => sense.configureVision()); }; }; this.getImportDataWrapper = function getImportDataWrapper(character) { return { setNewImportData(importData) { if (_.isEmpty(importData)) { return; } roll20.setAttrByName(character.id, 'import_data', JSON.stringify(importData)); roll20.setAttrByName(character.id, 'import_data_present', 'on'); }, mergeImportData(importData) { if (_.isEmpty(importData)) { return undefined; } const attr = roll20.getOrCreateAttr(character.id, 'import_data'); const dataPresentAttr = roll20.getOrCreateAttr(character.id, 'import_data_present'); let current = {}; try { if (!_.isEmpty(attr.get('current').trim())) { current = JSON.parse(attr.get('current')); } } catch (e) { logger.warn('Existing import_data attribute value was not valid JSON: [$$$]', attr.get('current')); } _.each(importData, (value, key) => { const currentVal = current[key]; if (currentVal) { if (!_.isArray(currentVal)) { current[key] = [currentVal]; } current[key] = current[key].concat(value); } else { current[key] = value; } }); logger.debug('Setting import data to $$$', current); attr.set('current', JSON.stringify(current)); dataPresentAttr.set('current', 'on'); return current; }, logWrap: 'importDataWrapper', }; }; this.handleSlots = function handleSlots(options) { if (options.use) { roll20.processAttrValue(options.character.id, `spell_slots_l${options.use}`, val => Math.max(0, --val)); } if (options.restore) { const attrName = `spell_slots_l${options.restore}`; const max = roll20.getAttrByName(options.character.id, attrName, 'max'); roll20.processAttrValue(options.character.id, `spell_slots_l${options.restore}`, val => { const retVal = Math.min(max, ++val); logger.debug('Setting attribute to $$$', retVal); return retVal; }); } }; ///////////////////////////////////////////////// // Event Handlers ///////////////////////////////////////////////// this.handleAddToken = function handleAddToken(token) { const represents = token.get('represents'); if (_.isEmpty(represents)) { return; } const character = roll20.getObj('character', represents); if (!character) { return; } addedTokenIds.push(token.id); const wrappedChangeToken = this.wrapHandler(this.handleChangeToken); // URGH. Thanks Roll20. setTimeout((function wrapper(id) { return function innerWrapper() { const addedToken = roll20.getObj('graphic', id); if (addedToken) { wrappedChangeToken(addedToken); } }; /* eslint-disable no-spaced-func */ }(token.id)), 100); /* eslint-enable no-spaced-func */ }; this.handleChangeToken = function handleChangeToken(token) { if (_.contains(addedTokenIds, token.id)) { addedTokenIds = _.without(addedTokenIds, token.id); this.setTokenBarsOnDrop(token, true); advantageTracker.handleTokenChange(token); } }; this.handleAddCharacter = function handleAddCharacter(character) { if (myState.config.newCharSettings.applyToAll) { this.applyCharacterDefaults(character); } }; this.setTokenBarsOnDrop = function setTokenBarsOnDrop(token, overwrite) { const character = roll20.getObj('character', token.get('represents')); if (!character) { return; } function setBar(barName, bar, value) { if (value) { token.set(`${barName}_value`, value); if (bar.max) { token.set(`${barName}_max`, value); } } } _.chain(myState.config.tokenSettings) .pick('bar1', 'bar2', 'bar3') .each((bar, barName) => { if (bar.attribute && !token.get(`${barName}_link`) && (!token.get(`${barName}_value`) || overwrite)) { if (bar.attribute === 'HP' && myState.config.sheetEnhancements.rollHPOnDrop) { // Guard against characters that aren't properly configured - i.e. ones used for templates and system // things rather than actual characters if (_.isEmpty(roll20.getAttrByName(character.id, 'hp_formula'))) { logger.debug('Ignoring character $$$ for rolling HP - has no hp_formula attribute', character.get('name')); return; } roll20.sendChat('', `%{${character.get('name')}|shaped_npc_hp}`, results => { if (results && results.length === 1) { const message = this.processInlinerolls(results[0]); if (!results[0].inlinerolls || !results[0].inlinerolls[0]) { logger.warn('HP roll didn\'t have the expected structure. This is what we got back: $$$', results[0]); } else { roll20.sendChat('HP Roller', `/w GM &{template:5e-shaped} ${message}`); setBar(barName, bar, results[0].inlinerolls[0].results.total); } } }); } else { setBar(barName, bar, roll20.getAttrByName(character.id, bar.attribute)); } } }); }; this.registerChatWatcher = function registerChatWatcher(handler, triggerFields) { const matchers = []; if (triggerFields && !_.isEmpty(triggerFields)) { matchers.push((msg, options) => { logger.debug('Matching options: $$$ against triggerFields $$$', options, triggerFields); return _.intersection(triggerFields, _.keys(options)).length === triggerFields.length; }); } chatWatchers.push({ matchers, handler: handler.bind(this) }); }; this.triggerChatWatchers = function triggerChatWatchers(msg) { const options = this.getRollTemplateOptions(msg); logger.debug('Roll template options: $$$', options); _.each(chatWatchers, watcher => { if (_.every(watcher.matchers, matcher => matcher(msg, options))) { watcher.handler(options, msg); } }); }; /** * * @param options * @param {ChatMessage} msg */ this.handleAmmo = function handleAmmo(options, msg) { if (!roll20.checkCharacterFlag(options.character.id, 'ammo_auto_use')) { return; } ammoManager.consumeAmmo(options, msg); }; this.handleHD = function handleHD(options, msg) { const match = options.title.match(/(\d+)d(\d+) HIT_DICE/); if (match && myState.config.sheetEnhancements.autoHD) { const hdCount = parseInt(match[1], 10); const hdSize = match[2]; const hdAttr = roll20.getAttrObjectByName(options.character.id, `hd_d${hdSize}`); const hpAttr = roll20.getOrCreateAttr(options.character.id, 'HP'); const newHp = Math.min(parseInt(hpAttr.get('current') || 0, 10) + this.getRollValue(msg, options.roll1), hpAttr.get('max') || Infinity); if (hdAttr) { if (hdCount <= hdAttr.get('current')) { hdAttr.set('current', hdAttr.get('current') - hdCount); hpAttr.set('current', newHp); if (!hpAttr.get('max')) { hpAttr.set('max', newHp); } } else { reportPublic('HD Police', `${options.characterName} can't use ${hdCount}d${hdSize} hit dice because they ` + `only have ${hdAttr.get('current')} left`); } } } }; this.handleD20Roll = function handleD20Roll(options) { if (options.disadvantage || options.advantage) { const autoRevertOptions = roll20.getAttrByName(options.character.id, 'auto_revert_advantage'); if (autoRevertOptions === 'on') { advantageTracker.setRollOption('normal', [options.character]); } } }; this.handleTraitClick = function handleTraitClick(options) { if (myState.config.sheetEnhancements.autoTraits) { traitManager.handleTraitClick(options); } }; this.handleSpellCast = function handleSpellCast(options) { if (options.friendlyLevel === 'Cantrip' || !myState.config.sheetEnhancements.autoSpellSlots) { return; } const spellLevel = parseInt(options.friendlyLevel.slice(0, 1), 10); const level = options.castAsLevel ? parseInt(options.castAsLevel, 10) : spellLevel; const availableSlots = _.chain(_.range(spellLevel, 10)) .map(slotLevel => roll20.getAttrObjectByName(options.character.id, `spell_slots_l${slotLevel}`)) .compact() .filter(attr => attr.get('current') > 0) .value(); const spellId = _.chain(roll20.getRepeatingSectionItemIdsByName(options.character.id, 'spell')) .pick(options.title.toLowerCase()) .values() .first() .value(); logger.debug('Spell id : $$$', spellId); const ritual = spellId ? !!roll20.getAttrByName(options.character.id, `repeating_spell_${spellId}_ritual`) : false; let msg; const bestSlot = availableSlots .find(slot => parseInt(slot.get('name').match(/spell_slots_l(\d)/)[1], 10) === level) || _.first(availableSlots); if (bestSlot) { const slotLevel = parseInt(bestSlot.get('name').match(/spell_slots_l(\d)/)[1], 10); if (slotLevel === level) { bestSlot.set('current', bestSlot.get('current') - 1); if (ritual) { msg = `1 slot of level ${level} used. [Cast as ritual](!shaped-slots --restore ${level} ` + `--character ${options.character.id}) instead?`; } } else if (!options.castAsLevel) { msg = `You have no level ${level} spell slots left. Do you want to ` + `[Cast at level ${slotLevel}](!shaped-slots --use ${slotLevel} --character ${options.character.id}) instead?`; if (ritual) { msg += ' Alternatively, you could cast a ritual without using a slot.'; } } else { msg = `You have no ${level} spell slots left. You can ` + `[Recast at level ${slotLevel}](!&#13;&#37;{${options.character.get('name')}` + `|repeating_spell_${spellId}_spell})`; if (ritual) { msg += ' or cast as a ritual instead.'; } } } else { msg = `${options.character.get('name')} has no spell slots of level ${level} to cast ${options.title}`; if (ritual) { msg += ' but could cast as a ritual instead without using a slot.'; } } if (msg) { roll20.sendChat('Spell Slots Police', msg); } }; this.handleDeathSave = function handleDeathSave(options, msg) { // TODO: Do we want to output text on death/recovery? function increment(val) { return ++val; } // TODO: Advantage? if (roll20.getAttrByName(options.character.id, 'roll_setting') !== '{{roll2=[[d20@{d20_mod}') { const result = this.getRollValue(msg, options.roll1); const attributeToIncrement = result >= 10 ? 'death_saving_throw_successes' : 'death_saving_throw_failures'; roll20.processAttrValue(options.character.id, attributeToIncrement, increment); } }; this.handleFX = function handleFX(options, msg) { const parts = options.fx.split(' '); if (parts.length < 2 || _.some(parts.slice(0, 2), _.isEmpty)) { logger.warn('FX roll template variable is not formated correctly: [$$$]', options.fx); return; } const fxType = parts[0]; const pointsOfOrigin = parts[1]; let targetTokenId; const sourceCoords = {}; const targetCoords = {}; let fxCoords = []; let pageId; // noinspection FallThroughInSwitchStatementJS switch (pointsOfOrigin) { case 'sourceToTarget': case 'source': targetTokenId = parts[2]; fxCoords.push(sourceCoords, targetCoords); break; case 'targetToSource': case 'target': targetTokenId = parts[2]; fxCoords.push(targetCoords, sourceCoords); break; default: throw new Error(`Unrecognised pointsOfOrigin type in fx spec: ${pointsOfOrigin}`); } if (targetTokenId) { const targetToken = roll20.getObj('graphic', targetTokenId); pageId = targetToken.get('_pageid'); targetCoords.x = targetToken.get('left'); targetCoords.y = targetToken.get('top'); } else { pageId = roll20.getCurrentPage(msg.playerid).id; } const casterTokens = roll20.findObjs({ type: 'graphic', pageid: pageId, represents: options.character.id }); if (casterTokens.length) { // If there are multiple tokens for the character on this page, then try and find one of them that is selected // This doesn't work without a selected token, and the only way we can get this is to use @{selected} which is a // pain for people who want to launch without a token selected if(casterTokens.length > 1) { const selected = // _.findWhere(casterTokens, {id: sourceTokenId}); if (selected) { casterTokens = [selected]; } } sourceCoords.x = casterTokens[0].get('left'); sourceCoords.y = casterTokens[0].get('top'); } if (!fxCoords[0]) { logger.warn('Couldn\'t find required point for fx for character $$$, casterTokens: $$$, fxSpec: $$$ ', options.character.id, casterTokens, options.fx); return; } else if (!fxCoords[1]) { fxCoords = fxCoords.slice(0, 1); } roll20.spawnFx(fxCoords, fxType, pageId); }; this.getRollValue = function getRollValue(msg, rollOutputExpr) { const rollIndex = rollOutputExpr.match(/\$\[\[(\d+)\]\]/)[1]; return msg.inlinerolls[rollIndex].results.total; }; /** * * @returns {*} */ this.getRollTemplateOptions = function getRollTemplateOptions(msg) { if (msg.rolltemplate === '5e-shaped') { const regex = /\{\{(.*?)\}\}/g; let match; const options = {}; while (!!(match = regex.exec(msg.content))) { if (match[1]) { const splitAttr = match[1].split('='); const propertyName = splitAttr[0].replace(/_([a-z])/g, (m, letter) => letter.toUpperCase()); options[propertyName] = splitAttr.length === 2 ? splitAttr[1].replace(/\^\{/, '') : ''; } } if (options.characterName) { options.character = roll20.findObjs({ _type: 'character', name: options.characterName, })[0]; } return options; } return {}; }; this.processInlinerolls = function processInlinerolls(msg) { if (_.has(msg, 'inlinerolls')) { return _.chain(msg.inlinerolls) .reduce((previous, current, index) => { previous[`$[[${index}]]`] = current.results.total || 0; return previous; }, {}) .reduce((previous, current, index) => previous.replace(index.toString(), current), msg.content) .value(); } return msg.content; }; // This method can go once all functions are moved into modules which handle their own configuration this.commandProcConfigured = false; this.oldStyleModulesConfigure = function oldStyleModulesConfigure(cp) { if (this.commandProcConfigured) { return cp; } this.commandProcConfigured = true; return cp // !shaped-import-statblock .addCommand('import-statblock', this.importStatblock.bind(this), true) .option('overwrite', ShapedConfig.booleanValidator) .option('replace', ShapedConfig.booleanValidator) .withSelection({ graphic: { min: 1, max: Infinity, }, }) // !shaped-import-monster , !shaped-monster .addCommand(['import-monster', 'monster'], this.importMonstersFromJson.bind(this), true) .option('all', ShapedConfig.booleanValidator) .optionLookup('monsters', _.partial(entityLookup.findEntity.bind(entityLookup), 'monsters', _, false)) .option('overwrite', ShapedConfig.booleanValidator) .option('replace', ShapedConfig.booleanValidator) .withSelection({ graphic: { min: 0, max: 1, }, }) // !shaped-import-spell, !shaped-spell .addCommand(['import-spell', 'spell'], this.importSpellsFromJson.bind(this), false) .optionLookup('spells', _.partial(entityLookup.findEntity.bind(entityLookup), 'spells', _, false)) .withSelection({ character: { min: 1, max: 1, }, }) // !shaped-import-spell-list .addCommand('import-spell-list', this.importSpellListFromJson.bind(this), false) .options(ShapedConfig.spellSearchOptions) .withSelection({ character: { min: 1, max: 1, }, }) // !shaped-token-defaults .addCommand(['token-defaults', 'apply-defaults'], this.applyTokenDefaults.bind(this), false) .withSelection({ graphic: { min: 1, max: Infinity, }, }) // !shaped-slots .addCommand('slots', this.handleSlots.bind(this), false) .option('character', ShapedConfig.getCharacterValidator(roll20), true) .option('use', ShapedConfig.integerValidator) .option('restore', ShapedConfig.integerValidator); }; this.checkInstall = function checkInstall() { logger.info('-=> ShapedScripts v4.4.5 <=-'); Migrator.migrateShapedConfig(myState, logger); }; this.wrapHandler = function wrapHandler(handler) { const self = this; return function handlerWrapper() { try { handler.apply(self, arguments); } catch (e) { if (typeof e === 'string' || e instanceof parseModule.ParserError || e instanceof UserError) { reportError(e); logger.error('Error: $$$', e.toString()); } else { logger.error(e.toString()); logger.error(e.stack); reportError('An error occurred. Please see the log for more details.'); } } finally { logger.prefixString = ''; } }; }; this.updateBarsForCharacterTokens = function updateBarsForCharacterTokens(curr) { roll20.findObjs({ type: 'graphic', represents: curr.get('characterid') }) .forEach(token => this.setTokenBarsOnDrop(token, false)); }; this.getAttributeChangeHandler = function getAttributeChangeHandler(attributeName) { const handlers = { roll_setting: advantageTracker.handleRollOptionChange.bind(advantageTracker), }; _.chain(myState.config.tokenSettings) .pick('bar1', 'bar2', 'bar3') .pluck('attribute') .each(attrName => { if (attrName === 'HP') { attrName = 'hp_formula'; } handlers[attrName] = this.updateBarsForCharacterTokens.bind(this); }); return handlers[attributeName]; }; this.registerEventHandlers = function registerEventHandlers() { roll20.on('chat:message', this.wrapHandler(this.handleInput)); roll20.on('add:token', this.wrapHandler(this.handleAddToken)); roll20.on('change:token', this.wrapHandler(this.handleChangeToken)); roll20.on('change:attribute', this.wrapHandler((curr, prev) => { const handler = this.getAttributeChangeHandler(curr.get('name')); if (handler) { handler(curr, prev); } })); roll20.on('add:character', this.wrapHandler(this.handleAddCharacter)); this.registerChatWatcher(this.handleDeathSave, ['deathSavingThrow', 'character', 'roll1']); this.registerChatWatcher(this.handleAmmo, ['ammoName', 'character']); this.registerChatWatcher(this.handleFX, ['fx', 'character']); this.registerChatWatcher(this.handleHD, ['character', 'title']); this.registerChatWatcher(this.handleD20Roll, ['character', 'roll1']); this.registerChatWatcher(this.handleTraitClick, ['character', 'trait']); // this.registerChatWatcher(this.handleSpellCast, ['character', 'spell', 'friendlyLevel']); }; logger.wrapModule(this); } ShapedScripts.prototype.logWrap = 'ShapedScripts'; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const UserError = __webpack_require__(12); const ShapedModule = __webpack_require__(13); function getParser(optionString, validator) { return function parseOptions(arg, errors, options) { const argParts = arg.split(/\s+/); if (argParts[0].toLowerCase() === optionString.toLowerCase()) { const value = argParts.length === 1 ? true : argParts.slice(1).join(' '); const result = validator(value); if (result.valid) { options[argParts[0]] = result.converted; } else { errors.push(`Invalid value [${value}] for option [${argParts[0]}]`); } return true; } return false; }; } function getObjectParser(specObject) { return function parseOptions(arg, errors, options) { const argParts = arg.split(/\s+/); const newObject = utils.createObjectFromPath(argParts[0], argParts.slice(1).join(' ')); const comparison = { spec: specObject, actual: newObject }; while (comparison.spec) { const key = _.keys(comparison.actual)[0]; const spec = comparison.spec[key]; if (!spec) { return false; } if (_.isFunction(comparison.spec[key])) { const result = comparison.spec[key](comparison.actual[key]); if (result.valid) { comparison.actual[key] = result.converted; utils.deepExtend(options, newObject); } else { errors.push(`Invalid value [${comparison.actual[key]}] for option [${argParts[0]}]`); } return true; } else if (_.isArray(comparison.actual[key])) { const newVal = []; newVal[comparison.actual[key].length - 1] = comparison.spec[key][0]; comparison.spec = newVal; comparison.actual = comparison.actual[key]; } else { comparison.spec = comparison.spec[key]; comparison.actual = comparison.actual[key]; } } return false; }; } /** * @constructor */ class Command { constructor(root, handler, roll20, name, gmOnly) { this.root = root; this.handler = handler; this.parsers = []; this.roll20 = roll20; this.name = name; this.gmOnly = gmOnly; } option(optionString, validator, required) { let parser; if (_.isFunction(validator)) { parser = getParser(optionString, validator); } else if (_.isObject(validator)) { const dummy = {}; dummy[optionString] = validator; parser = getObjectParser(dummy); } else { throw new Error(`Bad validator [${validator}] specified for option ${optionString}`); } parser.required = required; parser.optName = optionString; this.parsers.push(parser); return this; } options(optsSpec) { _.each(optsSpec, (validator, key) => this.option(key, validator)); return this; } optionLookup(groupName, lookup, required) { if (typeof lookup !== 'function') { lookup = _.propertyOf(lookup); } const parser = (arg, errors, options) => { const singleResolved = lookup(arg, options); if (singleResolved) { options[groupName] = options[groupName] || []; options[groupName].push.apply(options[groupName], _.isArray(singleResolved) ? singleResolved : [singleResolved]); return true; } const results = _.chain(arg.split(',')) .map(_.partial(_.result, _, 'trim')) .uniq() .reduce((memo, name) => { const resolvedPart = lookup(name, options); if (resolvedPart) { memo.resolved.push(resolvedPart); } else { memo.errors.push(`Unrecognised item ${name} for option group ${groupName}`); } return memo; }, { errors: [], resolved: [] }) .value(); if (!_.isEmpty(results.resolved)) { options[groupName] = results.resolved; errors.push.apply(errors, results.errors); return true; } return false; }; parser.optName = groupName; parser.required = required; this.parsers.push(parser); return this; } handle(args, selection, cmdString, playerIsGM, playerId) { if (!playerIsGM && this.gmOnly) { throw new UserError('You must be a GM to run this command'); } const caches = {}; const startOptions = { errors: [], }; Object.defineProperty(startOptions, 'getCache', { enumerable: false, value: function getCache(key) { return (caches[key] = caches[key] || {}); }, }); startOptions.selected = this.selectionSpec && processSelection(selection || [], this.selectionSpec, this.roll20); const finalOptions = _.chain(args) .reduce((options, arg) => { if (!_.some(this.parsers, parser => parser(arg, options.errors, options))) { options.errors.push(`Unrecognised or poorly formed option ${arg}`); } return options; }, startOptions) .each((propVal, propName, obj) => { // NB Cannot use omit or it will remove the getCache property if (_.isUndefined(propVal)) { delete obj[propName]; } }) .value(); if (finalOptions.errors.length > 0) { throw finalOptions.errors.join('\n'); } delete finalOptions.errors; const missingOpts = _.chain(this.parsers) .where({ required: true }) .pluck('optName') .difference(_.keys(finalOptions)) .value(); if (!_.isEmpty(missingOpts)) { throw new UserError(`Command ${cmdString} was missing options: [${missingOpts.join(',')}]`); } if (finalOptions.character && !playerIsGM) { finalOptions.character.forEach(character => { if (!character.controlledby.contains(playerId) && !character.controlledby.contains('all')) { throw new UserError(`You do not have permission to make changes to character ${character.get('name')}`); } }); } this.handler(finalOptions); } withSelection(selectionSpec) { this.selectionSpec = selectionSpec; return this; } addCommand() { return this.root.addCommand.apply(this.root, arguments); } addModule() { return this.root.addModule.apply(this.root, arguments); } processCommand() { return this.root.processCommand.apply(this.root, arguments); } get logWrap() { return `command [${this.name}]`; } } function processSelection(selection, constraints, roll20) { return _.reduce(constraints, (result, constraintDetails, type) => { const objects = _.chain(selection) .where({ _type: type === 'character' ? 'graphic' : type }) .map(selected => roll20.getObj(selected._type, selected._id)) .map(object => { if (type === 'character' && object) { return roll20.getObj('character', object.get('represents')); } return object; }) .compact() .uniq() .value(); if (_.size(objects) < constraintDetails.min || _.size(objects) > constraintDetails.max) { throw new UserError(`Wrong number of objects of type [${type}] selected, should be between ` + `${constraintDetails.min} and ${constraintDetails.max}`); } switch (_.size(objects)) { case 0: break; case 1: if (constraintDetails.max === 1) { result[type] = objects[0]; } else { result[type] = objects; } break; default: result[type] = objects; } return result; }, {}); } module.exports = function commandParser(rootCommand, roll20) { const commands = {}; return { addCommand(cmds, handler, gmOnly) { const command = new Command(this, handler, roll20, _.isArray(cmds) ? cmds.join(',') : cmds, gmOnly); (_.isArray(cmds) ? cmds : [cmds]).forEach(cmdString => (commands[cmdString] = command)); return command; }, addModule(module) { if (!module instanceof ShapedModule) { throw new Error('Can only pass ShapedModules to addModule'); } return module.configure(this); }, processCommand(msg) { const prefix = `!${rootCommand}-`; if (msg.type === 'api' && msg.content.indexOf(prefix) === 0) { const cmdString = msg.content.slice(prefix.length); const parts = cmdString.split(/\s+--/); const cmdName = parts.shift(); const cmd = commands[cmdName]; if (!cmd) { throw new UserError(`Unrecognised command ${prefix}${cmdName}`); } cmd.handle(parts, msg.selected, `${prefix}${cmdName}`, roll20.playerIsGM(msg.playerid), msg.playerid); } }, logWrap: 'commandParser', }; }; /***/ }, /* 12 */ /***/ function(module, exports) { 'use strict'; class UserError extends Error { constructor(message) { super(); this.message = message; } } module.exports = UserError; /***/ }, /* 13 */ /***/ function(module, exports) { 'use strict'; module.exports = class ShapedModule { configure(roll20, reporter, logger, myState, commandProcessor) { this.roll20 = roll20; this.reporter = reporter; this.logger = logger; this.myState = myState; this.addCommands(commandProcessor); logger.wrapModule(this); } addCommands(/* commandProcessor */) { throw new Error('Subclasses must implement addCommands'); } reportPublic(heading, text) { this.reporter.reportPublic(heading, text); } reportPlayer(heading, text) { this.reporter.reportPlayer(heading, text); } reportError(text) { this.reporter.reportError(text); } get logWrap() { return this.constructor.name; } }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const oneSixConfig = { logLevel: 'INFO', tokenSettings: { number: false, bar1: { attribute: 'HP', max: true, link: false, showPlayers: false, }, bar2: { attribute: 'speed', max: false, link: true, showPlayers: false, }, bar3: { attribute: '', max: false, link: false, showPlayers: false, }, aura1: { radius: '', color: '#FFFF99', square: false, }, aura2: { radius: '', color: '#59e594', square: false, }, light: { radius: '', dimRadius: '', otherPlayers: false, hasSight: false, angle: 360, losAngle: 360, multiplier: 1, }, showName: true, showNameToPlayers: false, showAura1ToPlayers: true, showAura2ToPlayers: true, }, newCharSettings: { sheetOutput: '@{output_to_all}', deathSaveOutput: '@{output_to_all}', initiativeOutput: '@{output_to_all}', showNameOnRollTemplate: '@{show_character_name_yes}', rollOptions: '@{normal}', initiativeRoll: '@{normal_initiative}', initiativeToTracker: '@{initiative_to_tracker_yes}', breakInitiativeTies: '@{initiative_tie_breaker_var}', showTargetAC: '@{attacks_vs_target_ac_no}', showTargetName: '@{attacks_vs_target_name_no}', autoAmmo: '@{ammo_auto_use_var}', autoRevertAdvantage: false, houserules: { savingThrowsHalfProf: false, mediumArmorMaxDex: 2, }, }, advTrackerSettings: { showMarkers: false, ignoreNpcs: false, advantageMarker: 'green', disadvantageMarker: 'red', output: 'silent', }, sheetEnhancements: { rollHPOnDrop: true, autoHD: true, autoSpellSlots: true, }, genderPronouns: [ { matchPattern: '^f$|female|girl|woman|feminine', nominative: 'she', accusative: 'her', possessive: 'her', reflexive: 'herself', }, { matchPattern: '^m$|male|boy|man|masculine', nominative: 'he', accusative: 'him', possessive: 'his', reflexive: 'himself', }, { matchPattern: '^n$|neuter|none|construct|thing|object', nominative: 'it', accusative: 'it', possessive: 'its', reflexive: 'itself', }, ], defaultGenderIndex: 2, }; class Migrator { constructor(startVersion) { this._versions = [{ version: startVersion || 0.1, migrations: [] }]; } skipToVersion(version) { this._versions.push({ version, migrations: [] }); return this; } nextVersion() { const currentVersion = this._versions.slice(-1)[0].version; const nextVersion = (currentVersion * 10 + 1) / 10; // Avoid FP errors this._versions.push({ version: nextVersion, migrations: [] }); return this; } addProperty(path, value) { const expandedProperty = utils.createObjectFromPath(path, value); return this.transformConfig((config) => utils.deepExtend(config, expandedProperty), `Adding property ${path} with value ${value}`); } overwriteProperty(path, value) { return this.transformConfig((config) => { const parts = path.split('.'); const obj = parts.length > 1 ? utils.getObjectFromPath(config, parts.slice(0, -1).join('.')) : config; obj[parts.slice(-1)[0]] = value; return config; }, `Overwriting property ${path} with value ${JSON.stringify(value)}`); } copyProperty(oldPath, newPath) { return this.transformConfig(Migrator.propertyCopy.bind(null, oldPath, newPath), `Copying property from ${oldPath} to ${newPath}`); } static propertyCopy(oldPath, newPath, config) { const oldVal = utils.getObjectFromPath(config, oldPath); if (!_.isUndefined(oldVal)) { const expandedProperty = utils.createObjectFromPath(newPath, oldVal); utils.deepExtend(config, expandedProperty); } return config; } static propertyDelete(path, config) { const parts = path.split('.'); const obj = parts.length > 1 ? utils.getObjectFromPath(config, parts.slice(0, -1).join('.')) : config; if (obj && !_.isUndefined(obj[parts.slice(-1)[0]])) { delete obj[parts.slice(-1)[0]]; } return config; } deleteProperty(propertyPath) { return this.transformConfig(Migrator.propertyDelete.bind(null, propertyPath), `Deleting property ${propertyPath} from config`); } moveProperty(oldPath, newPath) { return this.transformConfig((config) => { config = Migrator.propertyCopy(oldPath, newPath, config); return Migrator.propertyDelete(oldPath, config); }, `Moving property from ${oldPath} to ${newPath}`); } transformConfig(transformer, message) { const lastVersion = this._versions.slice(-1)[0]; lastVersion.migrations.push({ transformer, message }); return this; } migrateConfig(state, logger) { logger.info('Checking config for upgrade, starting state: $$$', state); if (_.isEmpty(state)) { // working with a fresh install here state.version = 0; } if (!this._versions.find(version => version.version >= state.version)) { throw new Error(`Unrecognised schema state ${state.version} - cannot upgrade.`); } return this._versions .filter(version => version.version > state.version) .reduce((versionResult, version) => { logger.info('Upgrading schema to version $$$', version.version); versionResult = version.migrations.reduce((result, migration) => { logger.info(migration.message); return migration.transformer(result); }, versionResult); versionResult.version = version.version; logger.info('Post-upgrade state: $$$', versionResult); return versionResult; }, state); } } const migrator = new Migrator() .addProperty('config', {}) .skipToVersion(0.4) .overwriteProperty('config.genderPronouns', utils.deepClone(oneSixConfig).genderPronouns) .skipToVersion(1.2) .moveProperty('config.autoHD', 'config.sheetEnhancements.autoHD') .moveProperty('config.rollHPOnDrop', 'config.sheetEnhancements.rollHPOnDrop') .skipToVersion(1.4) .moveProperty('config.newCharSettings.savingThrowsHalfProf', 'config.newCharSettings.houserules.savingThrowsHalfProf') .moveProperty('config.newCharSettings.mediumArmorMaxDex', 'config.newCharSettings.houserules.mediumArmorMaxDex') .skipToVersion(1.6) .transformConfig(state => { _.defaults(state.config, oneSixConfig); _.defaults(state.config.tokenSettings, oneSixConfig.tokenSettings); _.defaults(state.config.newCharSettings, oneSixConfig.newCharSettings); _.defaults(state.config.advTrackerSettings, oneSixConfig.advTrackerSettings); _.defaults(state.config.sheetEnhancements, oneSixConfig.sheetEnhancements); return state; }, 'Applying defaults as at schema version 1.6') // 1.7 // add base houserules and variants section // add sheetEnhancements.autoTraits .nextVersion() .addProperty('config.variants', { rests: { longNoHpFullHd: false, }, }) .addProperty('config.sheetEnhancements.autoTraits', true) // 1.8 // Set tokens to have vision by default so that people see the auto-generated stuff based on senses .nextVersion() .overwriteProperty('config.tokenSettings.light.hasSight', true) // 1.9 Add default tab setting .nextVersion() .addProperty('config.newCharSettings.tab', 'core') // 2.0 Add default token actions .nextVersion() .addProperty('config.newCharSettings.tokenActions', { initiative: false, abilityChecks: null, advantageTracker: null, savingThrows: null, attacks: null, statblock: false, traits: null, actions: null, reactions: null, legendaryActions: null, lairActions: null, regionalEffects: null, rests: false, }) // 2.1 Add spells token action .nextVersion() .addProperty('config.newCharSettings.tokenActions.spells', false) // 2.2 Changes to support new roll behaviour in sheet 4.2.1 .nextVersion() .overwriteProperty('config.newCharSettings.sheetOutput', '') .overwriteProperty('config.newCharSettings.deathSaveOutput', '') .overwriteProperty('config.newCharSettings.initiativeOutput', '') .overwriteProperty('config.newCharSettings.showNameOnRollTemplate', '') .overwriteProperty('config.newCharSettings.rollOptions', '') .overwriteProperty('config.newCharSettings.initiativeRoll', '') .overwriteProperty('config.newCharSettings.initiativeToTracker', '') .overwriteProperty('config.newCharSettings.breakInitiativeTies', '') .overwriteProperty('config.newCharSettings.showTargetAC', '') .overwriteProperty('config.newCharSettings.showTargetName', '') .overwriteProperty('config.newCharSettings.autoAmmo', '1') // 2.3 Remove "small" macros .nextVersion() .transformConfig(config => { _.each(config.config.newCharSettings.tokenActions, (value, key) => { if (typeof value === 'string' && value.match('.*Small$')) { config.config.newCharSettings.tokenActions[key] = value.replace(/Small$/, ''); } }); return config; }, 'Removing "small" macros') .addProperty('config.newCharSettings.textSizes', { spellsTextSize: 'text', abilityChecksTextSize: 'text', savingThrowsTextSize: 'text', }) // 2.4 Don't set default values for sheet options to save on attribute bloat .nextVersion() .transformConfig(config => { const ncs = config.config.newCharSettings; const defaults = { sheetOutput: '', deathSaveOutput: '', initiativeOutput: '', showNameOnRollTemplate: '', rollOptions: '{{ignore=[[0', initiativeRoll: '@{shaped_d20}', initiativeToTracker: '@{selected|initiative_formula} &{tracker}', breakInitiativeTies: '', showTargetAC: '', showTargetName: '', autoAmmo: '', tab: 'core', }; _.each(defaults, (defaultVal, key) => { if (ncs[key] === defaultVal) { ncs[key] = '***default***'; } }); if (ncs.houserules.mediumArmorMaxDex === '2') { ncs.houserules.mediumArmorMaxDex = '***default***'; } ['spellsTextSize', 'abilityChecksTextSize', 'savingThrowsTextSize'].forEach(prop => { if (ncs.textSizes[prop] === 'text_big') { ncs.textSizes[prop] = '***default***'; } }); return config; }, 'Removing default values') // 2.5 Custom saving throws .nextVersion() .addProperty('config.newCharSettings.houserules.saves', { useCustomSaves: '***default***', useAverageOfAbilities: '***default***', fortitude: { fortitudeStrength: '***default***', fortitudeDexterity: '***default***', fortitudeConstitution: '***default***', fortitudeIntelligence: '***default***', fortitudeWisdom: '***default***', fortitudeCharisma: '***default***', }, reflex: { reflexStrength: '***default***', reflexDexterity: '***default***', reflexConstitution: '***default***', reflexIntelligence: '***default***', reflexWisdom: '***default***', reflexCharisma: '***default***', }, will: { willStrength: '***default***', willDexterity: '***default***', willConstitution: '***default***', willIntelligence: '***default***', willWisdom: '***default***', willCharisma: '***default***', }, }) .moveProperty('config.newCharSettings.houserules.savingThrowsHalfProf', 'config.newCharSettings.houserules.saves.savingThrowsHalfProf') .addProperty('config.newCharSettings.houserules.baseDC', '***default***') // 2.6 expertise_as_advantage .nextVersion() .addProperty('config.newCharSettings.houserules.expertiseAsAdvantage', '***default***') // 2.7 add hide options .nextVersion() .addProperty('config.newCharSettings.hide', { hideAttack: '***default***', hideDamage: '***default***', hideAbilityChecks: '***default***', hideSavingThrows: '***default***', hideSavingThrowDC: '***default***', hideSpellContent: '***default***', hideActionFreetext: '***default***', hideSavingThrowFailure: '***default***', hideSavingThrowSuccess: '***default***', hideRecharge: '***default***', }) // 2.8 rename hideActionFreetext .nextVersion() .moveProperty('config.newCharSettings.hide.hideActionFreetext', 'config.newCharSettings.hide.hideFreetext') // 2.9 make auto-applying new character settings optional (and switched off by default) .nextVersion() .addProperty('config.newCharSettings.applyToAll', false); Migrator.migrateShapedConfig = migrator.migrateConfig.bind(migrator); module.exports = Migrator; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); module.exports = class ShapedConfig { static get configToAttributeLookup() { const lookup = { sheetOutput: 'output_option', deathSaveOutput: 'death_save_output_option', initiativeOutput: 'initiative_output_option', showNameOnRollTemplate: 'show_character_name', rollOptions: 'roll_setting', initiativeRoll: 'initiative_roll', initiativeToTracker: 'initiative_to_tracker', breakInitiativeTies: 'initiative_tie_breaker', showTargetAC: 'attacks_vs_target_ac', showTargetName: 'attacks_vs_target_name', autoAmmo: 'ammo_auto_use', autoRevertAdvantage: 'auto_revert_advantage', savingThrowsHalfProf: 'saving_throws_half_proficiency', mediumArmorMaxDex: 'medium_armor_max_dex', spellsTextSize: 'spells_text_size', abilityChecksTextSize: 'ability_checks_text_size', savingThrowsTextSize: 'saving_throws_text_size', baseDC: 'base_dc', tab: 'tab', useCustomSaves: 'use_custom_saving_throws', useAverageOfAbilities: 'average_of_abilities', expertiseAsAdvantage: 'expertise_as_advantage', hideAttack: 'hide_attack', hideDamage: 'hide_damage', hideAbilityChecks: 'hide_ability_checks', hideSavingThrows: 'hide_saving_throws', hideSavingThrowDC: 'hide_saving_throw_dc', hideSpellContent: 'hide_spell_content', hideFreetext: 'hide_freetext', hideSavingThrowFailure: 'hide_saving_throw_failure', hideSavingThrowSuccess: 'hide_saving_throw_success', hideRecharge: 'hide_recharge', customSkills: 'custom_skills', }; ['fortitude', 'reflex', 'will'].forEach(save => { ['Strength', 'Dexterity', 'Constitution', 'Intelligence', 'Wisdom', 'Charisma'].forEach(ability => { lookup[`${save}${ability}`] = `${save}_${ability.toLowerCase()}`; }); }); return lookup; } static booleanValidator(value) { const converted = value === 'true' || (value === 'false' ? false : value); return { valid: typeof value === 'boolean' || value === 'true' || value === 'false', converted, }; } static stringValidator(value) { return { valid: true, converted: value, }; } static arrayValidator(value) { return { valid: true, converted: value.split(',').map(s => s.trim()), }; } static getOptionList(options) { return function optionList(value) { if (value === undefined) { return options; } return { converted: options[value], valid: options[value] !== undefined, }; }; } static getHideOption(propertyName) { return this.getOptionList({ false: '***default***', true: `{{${propertyName}=1}}` }); } static getBooleanOptionList() { return this.getOptionList({ true: 1, false: '***default***', }); } static integerValidator(value) { const parsed = parseInt(value, 10); return { converted: parsed, valid: !isNaN(parsed), }; } static colorValidator(value) { return { converted: value, valid: /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(value), }; } static get sheetOutputValidator() { return this.getOptionList({ public: '***default***', whisper: '/w GM', }); } static get commandOutputValidator() { return this.getOptionList({ public: 'public', whisper: 'whisper', silent: 'silent', }); } static get statusMarkerValidator() { return this.getOptionList(ShapedConfig.validStatusMarkers()); } static get barValidator() { return { attribute: this.stringValidator, max: this.booleanValidator, link: this.booleanValidator, showPlayers: this.booleanValidator, }; } static get auraValidator() { return { radius: this.stringValidator, color: this.colorValidator, square: this.booleanValidator, }; } static get lightValidator() { return { radius: this.stringValidator, dimRadius: this.stringValidator, otherPlayers: this.booleanValidator, hasSight: this.booleanValidator, angle: this.integerValidator, losAngle: this.integerValidator, multiplier: this.integerValidator, }; } static getCharacterValidator(roll20) { return function characterValidator(value) { const char = roll20.getObj('character', value); return { converted: char, valid: !!char, }; }; } static get spellSearchOptions() { return { classes: this.arrayValidator, domains: this.arrayValidator, oaths: this.arrayValidator, patrons: this.arrayValidator, school: this.stringValidator, level: this.integerValidator, }; } static regExpValidator(value) { try { new RegExp(value, 'i').test(''); return { converted: value, valid: true, }; } catch (e) { return { converted: null, valid: false, }; } } static get configOptionsSpec() { return { tokenSettings: { number: this.booleanValidator, bar1: this.barValidator, bar2: this.barValidator, bar3: this.barValidator, aura1: this.auraValidator, aura2: this.auraValidator, light: this.lightValidator, showName: this.booleanValidator, showNameToPlayers: this.booleanValidator, showAura1ToPlayers: this.booleanValidator, showAura2ToPlayers: this.booleanValidator, }, newCharSettings: { applyToAll: this.booleanValidator, sheetOutput: this.sheetOutputValidator, deathSaveOutput: this.sheetOutputValidator, initiativeOutput: this.sheetOutputValidator, showNameOnRollTemplate: this.getOptionList({ true: '{{show_character_name=1}}', false: '***default***', }), rollOptions: this.getOptionList({ normal: '***default***', advantage: 'adv {{ignore=[[0', disadvantage: 'dis {{ignore=[[0', two: '{{roll2=[[d20@{d20_mod}', }), initiativeRoll: this.getOptionList({ normal: '***default***', advantage: '2d20@{d20_mod}kh1', disadvantage: '2d20@{d20_mod}kl1', }), initiativeToTracker: this.getOptionList({ true: '***default***', false: '@{initiative_formula}', }), breakInitiativeTies: this.getOptionList({ true: '[[@{initiative} / 100]][tie breaker]', false: '***default***', }), showTargetAC: this.getOptionList({ true: '[[@{target|AC}]]', false: '***default***', }), showTargetName: this.getOptionList({ true: '@{target|token_name}', false: '***default***', }), autoAmmo: this.getOptionList({ true: '1', false: '***default***', }), autoRevertAdvantage: this.booleanValidator, houserules: { baseDC: this.getOptionList(_.range(0, 21).reduce((result, val) => { result[val] = val === 8 ? '***default***' : val; return result; }, {})), mediumArmorMaxDex: this.getOptionList(_.range(0, 11).reduce((result, val) => { result[val] = val === 2 ? '***default***' : val; return result; }, {})), expertiseAsAdvantage: this.getBooleanOptionList(), saves: { savingThrowsHalfProf: this.booleanValidator, useCustomSaves: this.getBooleanOptionList(), useAverageOfAbilities: this.getBooleanOptionList(), fortitude: { fortitudeStrength: this.getBooleanOptionList(), fortitudeDexterity: this.getBooleanOptionList(), fortitudeConstitution: this.getBooleanOptionList(), fortitudeIntelligence: this.getBooleanOptionList(), fortitudeWisdom: this.getBooleanOptionList(), fortitudeCharisma: this.getBooleanOptionList(), }, reflex: { reflexStrength: this.getBooleanOptionList(), reflexDexterity: this.getBooleanOptionList(), reflexConstitution: this.getBooleanOptionList(), reflexIntelligence: this.getBooleanOptionList(), reflexWisdom: this.getBooleanOptionList(), reflexCharisma: this.getBooleanOptionList(), }, will: { willStrength: this.getBooleanOptionList(), willDexterity: this.getBooleanOptionList(), willConstitution: this.getBooleanOptionList(), willIntelligence: this.getBooleanOptionList(), willWisdom: this.getBooleanOptionList(), willCharisma: this.getBooleanOptionList(), }, }, }, tab: this.getOptionList({ core: '***default***', spells: 'spells', equipment: 'equipment', character: 'character', settings: 'settings', all: 'all', }), tokenActions: { initiative: this.booleanValidator, abilityChecks: this.getOptionList({ none: null, query: 'abilityChecksQuery', chatWindow: 'abilityChecks', queryShort: 'abilChecksQuery', chatWindowShort: 'abilChecks', }), advantageTracker: this.getOptionList({ none: null, normal: 'advantageTracker', short: 'advantageTrackerShort', shortest: 'advantageTrackerShortest', query: 'advantageTrackerQuery', }), savingThrows: this.getOptionList({ none: null, query: 'savingThrowsQuery', chatWindow: 'savingThrows', queryShort: 'savesQuery', chatWindowShort: 'saves', }), attacks: this.getOptionList({ none: null, individualActions: 'attacks', chatWindow: 'attacksMacro', }), statblock: this.booleanValidator, traits: this.getOptionList({ none: null, individualActions: 'traits', chatWindow: 'traitsMacro', }), actions: this.getOptionList({ none: null, individualActions: 'actions', chatWindow: 'actionsMacro', }), spells: this.booleanValidator, reactions: this.getOptionList({ none: null, individualActions: 'reactions', chatWindow: 'reactionsMacro', }), legendaryActions: this.getOptionList({ none: null, individualActions: 'legendaryActions', chatWindow: 'legendaryActionsMacro', chatWindowShort: 'legendaryA', }), lairActions: this.getOptionList({ none: null, chatWindow: 'lairActions', chatWindowShort: 'lairA', }), regionalEffects: this.getOptionList({ none: null, chatWindow: 'regionalEffects', chatWindowShort: 'regionalE', }), rests: this.booleanValidator, }, textSizes: { spellsTextSize: this.getOptionList({ normal: '***default***', big: 'big', }), abilityChecksTextSize: this.getOptionList({ normal: 'text', big: '***default***', }), savingThrowsTextSize: this.getOptionList({ normal: 'text', big: '***default***', }), }, hide: { hideAbilityChecks: this.getHideOption('hide_ability_checks'), hideSavingThrows: this.getHideOption('hide_saving_throws'), hideAttack: this.getHideOption('hide_attack'), hideDamage: this.getHideOption('hide_damage'), hideFreetext: this.getHideOption('hide_freetext'), hideRecharge: this.getHideOption('hide_recharge'), hideSavingThrowDC: this.getHideOption('hide_saving_throw_dc'), hideSavingThrowFailure: this.getHideOption('hide_saving_throw_failure'), hideSavingThrowSuccess: this.getHideOption('hide_saving_throw_success'), hideSpellContent: this.getHideOption('hide_spell_content'), }, customSkills: this.stringValidator, }, advTrackerSettings: { showMarkers: this.booleanValidator, ignoreNpcs: this.booleanValidator, advantageMarker: this.statusMarkerValidator, disadvantageMarker: this.statusMarkerValidator, output: this.commandOutputValidator, }, sheetEnhancements: { rollHPOnDrop: this.booleanValidator, autoHD: this.booleanValidator, autoSpellSlots: this.booleanValidator, autoTraits: this.booleanValidator, }, genderPronouns: [ { matchPattern: this.regExpValidator, nominative: this.stringValidator, accusative: this.stringValidator, possessive: this.stringValidator, reflexive: this.stringValidator, }, ], defaultGenderIndex: this.integerValidator, variants: { rests: { longNoHpFullHd: this.booleanValidator, }, }, }; } static validStatusMarkers() { const markers = [ 'red', 'blue', 'green', 'brown', 'purple', 'pink', 'yellow', 'dead', 'skull', 'sleepy', 'half-heart', 'half-haze', 'interdiction', 'snail', 'lightning-helix', 'spanner', 'chained-heart', 'chemical-bolt', 'death-zone', 'drink-me', 'edge-crack', 'ninja-mask', 'stopwatch', 'fishing-net', 'overdrive', 'strong', 'fist', 'padlock', 'three-leaves', 'fluffy-wing', 'pummeled', 'tread', 'arrowed', 'aura', 'back-pain', 'black-flag', 'bleeding-eye', 'bolt-shield', 'broken-heart', 'cobweb', 'broken-shield', 'flying-flag', 'radioactive', 'trophy', 'broken-skull', 'frozen-orb', 'rolling-bomb', 'white-tower', 'grab', 'screaming', 'grenade', 'sentry-gun', 'all-for-one', 'angel-outfit', 'archery-target', ]; const obj = {}; for (let i = 0; i < markers.length; i++) { obj[markers[i]] = markers[i]; } return obj; } }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); class MacroMaker { constructor(roll20) { if (!roll20) { throw new Error('Rol20 parameter is required for MacroMaker constructor'); } this.roll20 = roll20; this.sortKey = 'originalOrder'; } getAbilityMaker(character) { const self = this; return function abilityMaker(abilitySpec) { const ability = self.roll20.getOrCreateObj('ability', { characterid: character.id, name: abilitySpec.name }); ability.set({ action: abilitySpec.action, istokenaction: true }); // TODO configure this return abilitySpec.name; }; } } class AbilityDeleter extends MacroMaker { constructor(roll20) { super(roll20); this.sortKey = ''; } run(character) { const abilities = this.roll20.findObjs({ type: 'ability', characterid: character.id }); const deleted = _.map(abilities, obj => { const name = obj.get('name'); obj.remove(); return name; }); return `Deleted: ${_.isEmpty(deleted) ? 'None' : deleted.join(', ')}`; } } class RepeatingAbilityMaker extends MacroMaker { constructor(repeatingSection, abilityName, label, canMark, roll20) { super(roll20); this.repeatingSection = repeatingSection; this.abilityName = abilityName; this.label = label; this.canMark = canMark; } run(character, options) { const cache = options.getCache(character.id); cache[this.repeatingSection] = cache[this.repeatingSection] || this.roll20.getRepeatingSectionItemIdsByName(character.id, this.repeatingSection); const configured = _.chain(cache[this.repeatingSection]) .map((repeatingId, repeatingName) => { let repeatingAction = `%{${character.get('name')}|repeating_${this.repeatingSection}_${repeatingId}` + `_${this.abilityName}}`; if (this.canMark && options.mark) { repeatingAction += '\n!mark @{target|token_id}'; } return { name: utils.toTitleCase(repeatingName), action: repeatingAction }; }) .map(this.getAbilityMaker(character)) .value(); const addedText = _.isEmpty(configured) ? 'Not present for character' : configured.join(', '); return `${this.label}: ${addedText}`; } } class RollAbilityMaker extends MacroMaker { constructor(abilityName, newName, roll20) { super(roll20); this.abilityName = abilityName; this.newName = newName; } run(character) { return this.getAbilityMaker(character)({ name: this.newName, action: `%{${character.get('name')}|${this.abilityName}}`, }); } } class CommandAbilityMaker extends MacroMaker { constructor(command, options, newName, roll20) { super(roll20); this.command = command; this.options = options; this.newName = newName; } run(character) { return this.getAbilityMaker(character)({ name: this.newName, action: `!${this.command} ${utils.toOptionsString(this.options)}`, }); } } class MultiCommandAbilityMaker extends MacroMaker { constructor(commandSpecs, roll20) { super(roll20); this.commandSpecs = commandSpecs; } run(character) { const abilMaker = this.getAbilityMaker(character); return this.commandSpecs.map(cmdSpec => abilMaker({ name: cmdSpec.abilityName, action: `!${cmdSpec.command} ${utils.toOptionsString(cmdSpec.options)}`, }) ); } } class RepeatingSectionMacroMaker extends MacroMaker { constructor(abilityName, repeatingSection, macroName, roll20) { super(roll20); this.abilityName = abilityName; this.repeatingSection = repeatingSection; this.macroName = macroName; this.sortKey = 'originalOrder'; } run(character) { if (!_.isEmpty(this.roll20.getRepeatingSectionAttrs(character.id, this.repeatingSection))) { return this.getAbilityMaker(character)({ name: this.macroName, action: `%{${character.get('name')}|${this.abilityName}}`, }); } return `${this.macroName}: Not present for character`; } } function getRepeatingSectionAbilityLookup(sectionName, rollName, roll20) { return function repeatingSectionAbilityLookup(optionName, existingOptions) { const characterId = existingOptions.selected.character[0].id; const cache = existingOptions.getCache(characterId); cache[sectionName] = cache[sectionName] || roll20.getRepeatingSectionItemIdsByName(characterId, sectionName); const repeatingId = cache[sectionName][optionName.toLowerCase()]; if (repeatingId) { return new RollAbilityMaker(`repeating_${sectionName}_${repeatingId}_${rollName}`, utils.toTitleCase(optionName), roll20); } return undefined; }; } module.exports = class AbilityMaker extends ShapedModule { addCommands(commandProcessor) { const roll20 = this.roll20; this.staticAbilityOptions = { DELETE: new AbilityDeleter(roll20), advantageTracker: new MultiCommandAbilityMaker([ { command: 'shaped-at', options: ['advantage'], abilityName: 'Advantage' }, { command: 'shaped-at', options: ['disadvantage'], abilityName: 'Disadvantage' }, { command: 'shaped-at', options: ['normal'], abilityName: 'Normal' }, ], roll20), advantageTrackerShort: new MultiCommandAbilityMaker([ { command: 'shaped-at', options: ['advantage'], abilityName: 'Adv' }, { command: 'shaped-at', options: ['disadvantage'], abilityName: 'Dis' }, { command: 'shaped-at', options: ['normal'], abilityName: 'Normal' }, ], roll20), advantageTrackerShortest: new MultiCommandAbilityMaker([ { command: 'shaped-at', options: ['advantage'], abilityName: 'Adv' }, { command: 'shaped-at', options: ['disadvantage'], abilityName: 'Dis' }, ], roll20), advantageTrackerQuery: new CommandAbilityMaker('shaped-at', ['?{Roll Option|Normal,normal|w/ Advantage,advantage|w/ Disadvantage,disadvantage}'], '(dis)Adv Query', roll20), initiative: new RollAbilityMaker('shaped_initiative', 'Init', roll20), abilityChecks: new RollAbilityMaker('shaped_ability_checks', 'Ability Checks', roll20), abilityChecksQuery: new RollAbilityMaker('shaped_ability_checks_query', 'Ability Checks', roll20), abilChecks: new RollAbilityMaker('shaped_ability_checks', 'AbilChecks', roll20), abilChecksQuery: new RollAbilityMaker('shaped_ability_checks_query', 'AbilChecks', roll20), savingThrows: new RollAbilityMaker('shaped_saving_throw', 'Saving Throws', roll20), savingThrowsQuery: new RollAbilityMaker('shaped_saving_throw_query', 'Saving Throws', roll20), saves: new RollAbilityMaker('shaped_saving_throw', 'Saves', roll20), savesQuery: new RollAbilityMaker('shaped_saving_throw_query', 'Saves', roll20), rests: new CommandAbilityMaker('shaped-rest', ['?{Rest type|Short,short|Long,long}'], 'Rests', roll20), attacks: new RepeatingAbilityMaker('attack', 'attack', 'Attacks', true, roll20), attacksMacro: new RepeatingSectionMacroMaker('shaped_attacks', 'attack', 'Attacks', roll20), spells: new RepeatingSectionMacroMaker('shaped_spells', 'spell', 'Spells', roll20), statblock: new RollAbilityMaker('shaped_statblock', 'Statblock', roll20), traits: new RepeatingAbilityMaker('trait', 'trait', 'Traits', false, roll20), traitsMacro: new RepeatingSectionMacroMaker('shaped_traits', 'trait', 'Traits', roll20), actions: new RepeatingAbilityMaker('action', 'action', 'Actions', true, roll20), actionsMacro: new RepeatingSectionMacroMaker('shaped_actions', 'action', 'Actions', roll20), reactions: new RepeatingAbilityMaker('reaction', 'action', 'Reactions', false, roll20), reactionsMacro: new RepeatingSectionMacroMaker('shaped_reactions', 'reaction', 'Reactions', roll20), legendaryActions: new RepeatingAbilityMaker('legendaryaction', 'action', 'Legendary Actions', false, roll20), legendaryActionsMacro: new RepeatingSectionMacroMaker('shaped_legendaryactions', 'legendaryaction', 'Legendary Actions', roll20), legendaryA: new RepeatingSectionMacroMaker('shaped_legendaryactions', 'legendaryaction', 'LegendaryA', roll20), lairActions: new RepeatingSectionMacroMaker('shaped_lairactions', 'lairaction', 'Lair Actions', roll20), lairA: new RepeatingSectionMacroMaker('shaped_lairactions', 'lairaction', 'LairA', roll20), regionalEffects: new RepeatingSectionMacroMaker('shaped_regionaleffects', 'regionaleffect', 'Regional Effects', roll20), regionalE: new RepeatingSectionMacroMaker('shaped_regionaleffects', 'regionaleffect', 'RegionalE', roll20), }; return commandProcessor.addCommand('abilities', this.addAbility.bind(this), false) .withSelection({ character: { min: 1, max: Infinity, }, }) .optionLookup('abilities', this.staticAbilityOptions) .optionLookup('abilities', getRepeatingSectionAbilityLookup('spell', 'spell', this.roll20)) .optionLookup('abilities', getRepeatingSectionAbilityLookup('trait', 'trait', this.roll20)) .option('mark', ShapedConfig.booleanValidator); } addAbilitiesByName(abilities, character) { const caches = {}; const options = { getCache(key) { return (caches[key] = caches[key] || {}); }, }; // Slightly backwards way of doing this that ensures that we run the items in the order they are listed above // rather than the order they are passed in the parameter. Ideally we'd allow users to configure this but // since we haven't implemented that functionality the order is determine by the order in the saved configuration // object which is quite hard to control. _.chain(this.staticAbilityOptions) .pick((value, key) => _.contains(abilities, key)) .each(abilityMaker => abilityMaker.run(character, options)); } addAbility(options) { if (_.isEmpty(options.abilities)) { this.reportError('No abilities specified. ' + 'Take a look at the documentation for a list of ability options.'); return; } const messages = _.map(options.selected.character, (character) => { const operationMessages = _.chain(options.abilities) .sortBy('sortKey') .map(maker => maker.run(character, options)) .value(); if (_.isEmpty(operationMessages)) { return `<li>${character.get('name')}: Nothing to do</li>`; } let message; message = `<li>Configured the following abilities for character ${character.get('name')}:<ul><li>`; message += operationMessages.join('</li><li>'); message += '</li></ul></li>'; return message; }); this.reportPlayer('Ability Creation', `<ul>${messages.join('')}</ul>`); } }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); class ConfigUi extends ShapedModule { addCommands(commandProcessor) { const menus = { atMenu: new AdvantageTrackerMenu(this.myState.config, ShapedConfig.configOptionsSpec), tsMenu: new TokensMenu(this.myState.config, ShapedConfig.configOptionsSpec), barMenu: new TokenBarsMenu(this.myState.config, ShapedConfig.configOptionsSpec), auraMenu: new TokenAurasMenu(this.myState.config, ShapedConfig.configOptionsSpec), ncMenu: new NewCharacterMenu(this.myState.config, ShapedConfig.configOptionsSpec), taMenu: new TokenActionsMenu(this.myState.config, ShapedConfig.configOptionsSpec), hideMenu: new HideMenu(this.myState.config, ShapedConfig.configOptionsSpec), hrMenu: new NewCharacterHouseruleMenu(this.myState.config, ShapedConfig.configOptionsSpec), savesMenu: new SavesMenu(this.myState.config, ShapedConfig.configOptionsSpec), fortitudeMenu: new CustomSaveTypeMenu(this.myState.config, ShapedConfig.configOptionsSpec, 'fortitude'), reflexMenu: new CustomSaveTypeMenu(this.myState.config, ShapedConfig.configOptionsSpec, 'reflex'), willMenu: new CustomSaveTypeMenu(this.myState.config, ShapedConfig.configOptionsSpec, 'will'), textMenu: new NewCharacterTextSizeMenu(this.myState.config, ShapedConfig.configOptionsSpec), varsMenu: new VariantsMenu(this.myState.config, ShapedConfig.configOptionsSpec), seMenu: new SheetEnhancementsMenu(this.myState.config, ShapedConfig.configOptionsSpec), }; _.each(menus, menu => this.logger.wrapModule(menu)); return commandProcessor.addCommand('config', this.process.bind(this), true) .options(ShapedConfig.configOptionsSpec) .optionLookup('menu', menus); } process(options) { // drop "menu" options utils.deepExtend(this.myState.config, _.omit(options, 'menu')); if (options.menu) { this.reportPlayer('Configuration', options.menu[0].getMenu()); } else { const menu = new MainMenu(this.myState.config, ShapedConfig.configOptionsSpec); this.reportPlayer('Configuration', menu.getMenu()); } } } module.exports = ConfigUi; ///////////////////////////////////////////////// // Menu Base ///////////////////////////////////////////////// class ConfigMenu { constructor(config, specRoot) { this.config = config; this.specRoot = specRoot; } makeToggleSetting(params) { let currentVal = utils.getObjectFromPath(this.config, params.path); if (params.spec) { currentVal = _.invert(params.spec)[currentVal] === 'true'; } params.command = `${!currentVal}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = this.makeBoolText(currentVal); params.tooltip = 'click to toggle'; params.buttonColor = currentVal ? '#65c4bd' : '#f84545'; return this.makeOptionRow(params); } makeQuerySetting(params) { const currentVal = _.invert(params.spec)[utils.getObjectFromPath(this.config, params.path)]; const cmd = this.getQueryCommand(params.path, params.title, params.spec); params.command = `${cmd}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = this.makeText(currentVal); params.tooltip = 'click to change'; params.buttonColor = '#02baf2'; return this.makeOptionRow(params); } makeInputSetting(params) { const currentVal = utils.getObjectFromPath(this.config, params.path); params.command = `?{${params.prompt}|${currentVal}}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = currentVal || '[not set]'; params.tooltip = 'click to edit'; params.buttonColor = params.linkText === '[not set]' ? '#f84545' : '#02baf2'; return this.makeOptionRow(params); } // noinspection JSUnusedGlobalSymbols makeColorSetting(params) { const currentVal = utils.getObjectFromPath(this.config, params.path); params.command = `?{${params.prompt}|${currentVal}}${!_.isUndefined(params.menuCmd) ? ` --${params.menuCmd}` : ''}`; params.linkText = currentVal || '[not set]'; params.tooltip = 'click to edit'; params.buttonColor = params.linkText === '[not set]' ? '#02baf2' : currentVal; params.buttonTextColor = utils.getContrastYIQ(params.buttonColor); return this.makeOptionRow(params); } backToMainMenuButton() { return utils.buildHTML('a', '&lt;-- Main Menu', { href: '!shaped-config', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToTokenOptions() { return utils.buildHTML('a', '&lt;-- Token Options', { href: '!shaped-config --tsMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToNewCharOptions() { return utils.buildHTML('a', '&lt;-- New Character Options', { href: '!shaped-config --ncMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToHouseRuleOptions() { return utils.buildHTML('a', '&lt;-- Houserule Options', { href: '!shaped-config --hrMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } backToSavesOptions() { return utils.buildHTML('a', '&lt;-- Saves Options', { href: '!shaped-config --savesMenu', style: 'text-align: center; margin: 5px 0 0 0; padding: 2px 2px ; border-radius: 10px; white-space: nowrap; ' + 'overflow: hidden; text-overflow: ellipsis; background-color: #02baf2; border-color: #c0c0c0;', }); } getQueryCommand(path, title, optionsSpec) { let currentVal = _.invert(optionsSpec)[utils.getObjectFromPath(this.config, path)]; const optionList = _.keys(optionsSpec); // Fix up if we've somehow ended up with an illegal value if (_.isUndefined(currentVal)) { currentVal = _.first(optionList); utils.deepExtend(this.config, utils.createObjectFromPath(path, optionsSpec[currentVal])); } // move the current option to the front of the list optionList.splice(optionList.indexOf(currentVal), 1); optionList.unshift(currentVal); return `?{${title}|${optionList.join('|')}}`; } makeOptionRow(params) { const col1 = utils.buildHTML('td', params.title); const col2 = utils.buildHTML('td', this.makeOptionButton(params), { style: 'text-align:right;' }); return utils.buildHTML('tr', col1 + col2, { style: 'border: 1px solid gray;' }); } makeOptionButton(params) { if (_.isUndefined(params.width)) { params.width = 80; } let css = `text-align: center; width: ${params.width}px; margin: 2px 0 -3px 0; ` + 'padding: 2px 2px ; border-radius: 10px; border-color: #c0c0c0;' + `white-space: nowrap; overflow: hidden; text-overflow: ellipsis; background-color: ${params.buttonColor};`; if (params.buttonTextColor) { css += `color: ${params.buttonTextColor}`; } return utils.buildHTML('a', params.linkText, { style: css, href: `!shaped-config --${params.path} ${params.command}`, }); } makeText(value) { return utils.buildHTML('span', value, { style: 'padding: 0 2px;' }); } makeBoolText(value) { return value === true ? utils.buildHTML('span', 'on', { style: 'padding: 0 2px;' }) : utils.buildHTML('span', 'off', { style: 'padding: 0 2px;' }); } makeThreeColOptionTable(options) { return utils .buildHTML('tr', [ { tag: 'td', innerHtml: [ { tag: 'table', innerHtml: [ { tag: 'tr', innerHtml: [{ tag: 'th', innerHtml: options.tableTitle, attrs: { colspan: 3 } }], }, { tag: 'tr', innerHtml: [ { tag: 'td', innerHtml: options.colTitles[0], }, { tag: 'td', innerHtml: options.colTitles[1], }, { tag: 'td', innerHtml: options.colTitles[2], }, ], attrs: { style: 'line-height: 1;' }, }, { tag: 'tr', innerHtml: [ { tag: 'td', innerHtml: options.buttons[0], }, { tag: 'td', innerHtml: options.buttons[1], }, { tag: 'td', innerHtml: options.buttons[2], }, ], }, ], attrs: { style: 'width: 100%; text-align: center;' }, }, ], attrs: { colspan: '2' }, }, ], { style: 'border: 1px solid gray;' }); } get logWrap() { return this.constructor.name; } toJSON() { return {}; } } ///////////////////////////////////////////////// // Menus ///////////////////////////////////////////////// class MainMenu extends ConfigMenu { getMenu() { const optionRows = this.makeOptionRow({ title: 'Advantage Tracker', path: 'atMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Token Defaults', path: 'tsMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'New Characters', path: 'ncMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Char. Sheet Enhancements', path: 'seMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Houserules & Variants', path: 'varsMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Main Menu', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); return utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); } } class AdvantageTrackerMenu extends ConfigMenu { getMenu() { const ats = 'advTrackerSettings'; const menu = 'atMenu'; const optionRows = this.makeQuerySetting({ path: `${ats}.output`, title: 'Output', menuCmd: menu, spec: this.specRoot.advTrackerSettings.output(), }) + this.makeToggleSetting({ path: `${ats}.showMarkers`, title: 'Show Markers', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ats}.ignoreNpcs`, title: 'Ignore NPCs', menuCmd: menu, }) + this.makeQuerySetting({ path: `${ats}.advantageMarker`, title: 'Advantage Marker', menuCmd: menu, spec: this.specRoot.advTrackerSettings.advantageMarker(), }) + this.makeQuerySetting({ path: `${ats}.disadvantageMarker`, title: 'Disadvantage Marker', menuCmd: menu, spec: this.specRoot.advTrackerSettings.disadvantageMarker(), }); const th = utils.buildHTML('th', 'Advantage Tracker Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class TokensMenu extends ConfigMenu { getMenu() { // config) { // this.config = config; const ts = 'tokenSettings'; const menu = 'tsMenu'; const optionRows = this.makeToggleSetting({ path: `${ts}.number`, title: 'Numbered Tokens', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.showName`, title: 'Show Name Tag', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.showNameToPlayers`, title: 'Show Name to Players', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.radius`, title: 'Light Radius', prompt: 'Light Radius (empty to unset)', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.dimRadius`, title: 'Dim Radius', prompt: 'Light Dim Radius (empty to unset)', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.light.otherPlayers`, title: 'Other players see light', menuCmd: menu, }) + this.makeToggleSetting({ path: `${ts}.light.hasSight`, title: 'Has Sight', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.angle`, title: 'Light Angle', prompt: 'Light Angle', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.losAngle`, title: 'LOS Angle', prompt: 'LOS Angle', menuCmd: menu, }) + this.makeInputSetting({ path: `${ts}.light.multiplier`, title: 'Light Muliplier', prompt: 'Light Muliplier', menuCmd: menu, }) + this.makeOptionRow({ title: 'Token Bar Options', path: 'barMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Token Aura Options', path: 'auraMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Token Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class TokenBarsMenu extends ConfigMenu { getMenu() { const ts = 'tokenSettings'; const menu = 'barMenu'; let optionRows = ''; for (let i = 1; i <= 3; i++) { const currAttr = utils.getObjectFromPath(this.config, `${ts}.bar${i}.attribute`); const currAttrEmptyHint = currAttr || '[not set]'; const currMax = utils.getObjectFromPath(this.config, `${ts}.bar${i}.max`); const currLink = utils.getObjectFromPath(this.config, `${ts}.bar${i}.link`); const attBtn = this.makeOptionButton({ path: `${ts}.bar${i}.attribute`, linkText: this.makeText(currAttrEmptyHint), tooltip: 'click to edit', buttonColor: currAttrEmptyHint === '[not set]' ? '#f84545' : '#02baf2', width: 60, command: `?{Bar ${i} Attribute (empty to unset)|${currAttr}} --${menu}`, }); const maxBtn = this.makeOptionButton({ path: `${ts}.bar${i}.max`, linkText: this.makeBoolText(currMax), tooltip: 'click to toggle', buttonColor: currMax ? '#65c4bd' : '#f84545', width: 60, command: `${!currMax} --${menu}`, }); const linkBtn = this.makeOptionButton({ path: `${ts}.bar${i}.link`, linkText: this.makeBoolText(currLink), tooltip: 'click to togle', buttonColor: currLink ? '#65c4bd' : '#f84545', width: 60, command: `${!currLink} --${menu}`, }); optionRows += this.makeThreeColOptionTable({ tableTitle: `Bar ${i}`, colTitles: ['Attribute', 'Max', 'Link'], buttons: [attBtn, maxBtn, linkBtn], }); } for (let i = 1; i <= 3; i++) { optionRows += this.makeToggleSetting({ path: `${ts}.bar${i}.showPlayers`, title: `Bar ${i} Show Players`, menuCmd: 'barMenu', }); } const th = utils.buildHTML('th', 'Token Bar Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToTokenOptions(); } } class TokenAurasMenu extends ConfigMenu { getMenu() { const ts = 'tokenSettings'; const menu = 'auraMenu'; let optionRows = ''; for (let i = 1; i <= 2; i++) { const currRad = utils.getObjectFromPath(this.config, `${ts}.aura${i}.radius`); const currRadEmptyHint = currRad || '[not set]'; const currColor = utils.getObjectFromPath(this.config, `${ts}.aura${i}.color`); const currSquare = utils.getObjectFromPath(this.config, `${ts}.aura${i}.square`); const radBtn = this.makeOptionButton({ path: `${ts}.aura${i}.radius`, linkText: this.makeText(currRadEmptyHint), tooltip: 'click to edit', buttonColor: currRadEmptyHint === '[not set]' ? '#f84545' : '#02baf2', width: 60, command: `?{Aura ${i} Radius (empty to unset)|${currRad}} --${menu}`, }); const colorBtn = this.makeOptionButton({ path: `tokenSettings.aura${i}.color`, linkText: this.makeText(currColor), tooltip: 'click to edit', buttonColor: currColor, buttonTextColor: utils.getContrastYIQ(currColor), width: 60, command: `?{Aura ${i} Color (hex colors)|${currColor}} --${menu}`, }); const squareBtn = this.makeOptionButton({ path: `tokenSettings.aura${i}.square`, linkText: this.makeBoolText(currSquare), tooltip: 'click to toggle', buttonColor: currSquare ? '#65c4bd' : '#f84545', width: 60, command: `${!currSquare} --${menu}`, }); optionRows += this.makeThreeColOptionTable({ tableTitle: `Aura ${i}`, colTitles: ['Range', 'Color', 'Square'], buttons: [radBtn, colorBtn, squareBtn], }); } for (let i = 1; i <= 2; i++) { optionRows += this.makeToggleSetting({ path: `${ts}.showAura${i}ToPlayers`, title: `Aura ${i} Show Players`, menuCmd: 'auraMenu', }); } const th = utils.buildHTML('th', 'Token Aura Options', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToTokenOptions(); } } class NewCharacterMenu extends ConfigMenu { getMenu() { const menu = 'ncMenu'; const ncs = 'newCharSettings'; let optionRows = this.makeToggleSetting({ path: `${ncs}.applyToAll`, title: 'Apply to all new chars?', menuCmd: menu }); const spec = this.specRoot.newCharSettings; const currSheetOut = _.invert(spec.sheetOutput())[utils.getObjectFromPath(this.config, `${ncs}.sheetOutput`)]; const currDSaveOut = _.invert(spec.deathSaveOutput())[utils.getObjectFromPath(this.config, `${ncs}.deathSaveOutput`)]; const currInitOut = _.invert(spec.initiativeOutput())[utils.getObjectFromPath(this.config, `${ncs}.initiativeOutput`)]; const sheetBtn = this.makeOptionButton({ path: `${ncs}.sheetOutput`, linkText: this.makeText(currSheetOut), tooltip: 'click to change', buttonColor: '#02baf2', width: 60, command: `${this.getQueryCommand(`${ncs}.sheetOutput`, 'Sheet Output', spec.sheetOutput())}` + ` --${menu}`, }); const dSaveBtn = this.makeOptionButton({ path: `${ncs}.deathSaveOutput`, linkText: this.makeText(currDSaveOut), tooltip: 'click to change', buttonColor: '#02baf2', width: 60, command: `${this.getQueryCommand(`${ncs}.deathSaveOutput`, 'Death Save Output', spec.deathSaveOutput())}` + ` --${menu}`, }); const initBtn = this.makeOptionButton({ path: `${ncs}.initiativeOutput`, linkText: this.makeText(currInitOut), tooltip: 'click to change', buttonColor: '#02baf2', width: 60, command: `${this.getQueryCommand(`${ncs}.initiativeOutput`, 'Initiative Output', spec.initiativeOutput())}` + ` --${menu}`, }); optionRows += this.makeThreeColOptionTable({ tableTitle: 'Output', colTitles: ['Sheet', 'Death Save', 'Initiative'], buttons: [sheetBtn, dSaveBtn, initBtn], }); optionRows += this.makeToggleSetting({ path: `${ncs}.showNameOnRollTemplate`, title: 'Show Name on Roll Template', menuCmd: menu, spec: spec.showNameOnRollTemplate(), }) + this.makeQuerySetting({ path: `${ncs}.rollOptions`, title: 'Roll Options', menuCmd: menu, spec: spec.rollOptions(), }) + this.makeToggleSetting({ path: `${ncs}.autoRevertAdvantage`, title: 'Revert Advantage', menuCmd: menu, }) + this.makeQuerySetting({ path: `${ncs}.initiativeRoll`, title: 'Init Roll', menuCmd: menu, spec: spec.initiativeRoll(), }) + this.makeToggleSetting({ path: `${ncs}.initiativeToTracker`, title: 'Init To Tracker', menuCmd: menu, spec: spec.initiativeToTracker(), }) + this.makeToggleSetting({ path: `${ncs}.breakInitiativeTies`, title: 'Break Init Ties', menuCmd: menu, spec: spec.breakInitiativeTies(), }) + this.makeToggleSetting({ path: `${ncs}.showTargetAC`, title: 'Show Target AC', menuCmd: menu, spec: spec.showTargetAC(), }) + this.makeToggleSetting({ path: `${ncs}.showTargetName`, title: 'Show Target Name', menuCmd: menu, spec: spec.showTargetName(), }) + this.makeToggleSetting({ path: `${ncs}.autoAmmo`, title: 'Auto Use Ammo', menuCmd: menu, spec: spec.autoAmmo(), }) + this.makeQuerySetting({ path: `${ncs}.tab`, title: 'Default tab', menuCmd: menu, spec: spec.tab(), }) + this.makeOptionRow({ title: 'Default Token Actions', path: 'taMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Houserule Settings', path: 'hrMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Hide Settings', path: 'hideMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Text sizes', path: 'textMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'New Character Sheets', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class NewCharacterHouseruleMenu extends ConfigMenu { getMenu() { const hr = 'newCharSettings.houserules'; const menu = 'hrMenu'; const optionRows = this.makeQuerySetting({ path: `${hr}.baseDC`, title: 'Base DC', prompt: 'Base DC', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.baseDC(), }) + this.makeQuerySetting({ path: `${hr}.mediumArmorMaxDex`, title: 'Medium Armor Max Dex', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.mediumArmorMaxDex(), }) + this.makeToggleSetting({ path: `${hr}.expertiseAsAdvantage`, title: 'Expertise as advantage', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.expertiseAsAdvantage(), }) + this.makeOptionRow({ title: 'Saving Throws', path: 'savesMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Houserule Settings', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToNewCharOptions(); } } class HideMenu extends ConfigMenu { getMenu() { const hide = 'newCharSettings.hide'; const menu = 'hideMenu'; const optionRows = [ 'hideAbilityChecks', 'hideSavingThrows', 'hideAttack', 'hideDamage', 'hideFreetext', 'hideRecharge', 'hideSavingThrowDC', 'hideSavingThrowFailure', 'hideSavingThrowSuccess', 'hideSpellContent', ].reduce((result, functionName) => { const title = utils.toTitleCase( functionName.replace(/([a-z])([A-Z]+)/g, (match, lower, upper) => `${lower} ${upper.toLowerCase()}`)); result += this.makeToggleSetting({ path: `${hide}.${functionName}`, title, menuCmd: menu, spec: this.specRoot.newCharSettings.hide[functionName](), }); return result; }, ''); const th = utils.buildHTML('th', 'Hide Settings', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToNewCharOptions(); } } class SavesMenu extends ConfigMenu { getMenu() { const saves = 'newCharSettings.houserules.saves'; const menu = 'savesMenu'; const optionRows = this.makeToggleSetting({ path: `${saves}.savingThrowsHalfProf`, title: 'Half Proficiency Saves', menuCmd: menu, }) + this.makeToggleSetting({ path: `${saves}.useCustomSaves`, title: 'Use Custom Saves', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.saves.useCustomSaves(), }) + this.makeToggleSetting({ path: `${saves}.useAverageOfAbilities`, title: 'Use Average of Highest Abils', menuCmd: menu, spec: this.specRoot.newCharSettings.houserules.saves.useAverageOfAbilities(), }) + this.makeOptionRow({ title: 'Fortitude', path: 'fortitudeMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Reflex', path: 'reflexMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }) + this.makeOptionRow({ title: 'Will', path: 'willMenu', command: '', linkText: 'view --&gt;', buttonColor: '#02baf2', }); const th = utils.buildHTML('th', 'Houserule Settings', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToHouseRuleOptions(); } } class CustomSaveTypeMenu extends ConfigMenu { constructor(config, specRoot, saveName) { super(config, specRoot); this.saveName = saveName; } getMenu() { const saves = `newCharSettings.houserules.saves.${this.saveName}`; const menu = `${this.saveName}Menu`; const spec = this.specRoot.newCharSettings.houserules.saves[this.saveName]; const optionRows = ['Strength', 'Dexterity', 'Constitution', 'Intelligence', 'Wisdom', 'Charisma'] .reduce((result, attr) => { const propName = `${this.saveName}${attr}`; result += this.makeToggleSetting({ path: `${saves}.${propName}`, title: attr, menuCmd: menu, spec: spec[propName](), }); return result; }, ''); const th = utils.buildHTML('th', `${this.saveName} Saves`, { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToSavesOptions(); } } class NewCharacterTextSizeMenu extends ConfigMenu { getMenu() { const textSizes = 'newCharSettings.textSizes'; const menu = 'textMenu'; const optionRows = this.makeQuerySetting({ path: `${textSizes}.spellsTextSize`, title: 'Spells', menuCmd: menu, spec: this.specRoot.newCharSettings.textSizes.spellsTextSize(), }) + this.makeQuerySetting({ path: `${textSizes}.abilityChecksTextSize`, title: 'Ability Checks', menuCmd: menu, spec: this.specRoot.newCharSettings.textSizes.abilityChecksTextSize(), }) + this.makeQuerySetting({ path: `${textSizes}.savingThrowsTextSize`, title: 'Saving Throws', menuCmd: menu, spec: this.specRoot.newCharSettings.textSizes.savingThrowsTextSize(), }); const th = utils.buildHTML('th', 'Text sizes', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToNewCharOptions(); } } class VariantsMenu extends ConfigMenu { getMenu() { const root = 'variants'; const menu = 'varsMenu'; const optionRows = this.makeToggleSetting({ path: `${root}.rests.longNoHpFullHd`, title: 'Long Rest: No HP, full HD', menuCmd: menu, }); const th = utils.buildHTML('th', 'Houserules & Variants', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class SheetEnhancementsMenu extends ConfigMenu { getMenu() { const root = 'sheetEnhancements'; const menu = 'seMenu'; const optionRows = this.makeToggleSetting({ path: `${root}.rollHPOnDrop`, title: 'Roll HP On Drop', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.autoHD`, title: 'Process HD Automatically', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.autoSpellSlots`, title: 'Process Spell Slots Automatically', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.autoTraits`, title: 'Process Traits automatically', menuCmd: menu, }); const th = utils.buildHTML('th', 'Character Sheet Enhancements', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } class TokenActionsMenu extends ConfigMenu { getMenu() { const root = 'newCharSettings.tokenActions'; const menu = 'taMenu'; const spec = this.specRoot.newCharSettings.tokenActions; const optionRows = this.makeQuerySetting({ path: `${root}.advantageTracker`, title: 'Advantage Tracker', menuCmd: menu, spec: spec.advantageTracker(), }) + this.makeToggleSetting({ path: `${root}.initiative`, title: 'Initiative', menuCmd: menu, }) + this.makeQuerySetting({ path: `${root}.abilityChecks`, title: 'Ability Checks', menuCmd: menu, spec: spec.abilityChecks(), }) + this.makeQuerySetting({ path: `${root}.savingThrows`, title: 'Saves', menuCmd: menu, spec: spec.savingThrows(), }) + this.makeToggleSetting({ path: `${root}.rests`, title: 'Rests', menuCmd: menu, }) + this.makeQuerySetting({ path: `${root}.attacks`, title: 'Attacks', menuCmd: menu, spec: spec.attacks(), }) + this.makeToggleSetting({ path: `${root}.spells`, title: 'Spells', menuCmd: menu, }) + this.makeToggleSetting({ path: `${root}.statblock`, title: 'Statblock', menuCmd: menu, }) + this.makeQuerySetting({ path: `${root}.traits`, title: 'Traits', menuCmd: menu, spec: spec.traits(), }) + this.makeQuerySetting({ path: `${root}.actions`, title: 'Actions', menuCmd: menu, spec: spec.actions(), }) + this.makeQuerySetting({ path: `${root}.reactions`, title: 'Reactions', menuCmd: menu, spec: spec.reactions(), }) + this.makeQuerySetting({ path: `${root}.legendaryActions`, title: 'Legendary Actions', menuCmd: menu, spec: spec.legendaryActions(), }) + this.makeQuerySetting({ path: `${root}.lairActions`, title: 'Lair Actions', menuCmd: menu, spec: spec.lairActions(), }) + this.makeQuerySetting({ path: `${root}.regionalEffects`, title: 'Regional Effects', menuCmd: menu, spec: spec.regionalEffects(), }); const th = utils.buildHTML('th', 'Default Token Actions', { colspan: '2' }); const tr = utils.buildHTML('tr', th, { style: 'margin-top: 5px;' }); const table = utils.buildHTML('table', tr + optionRows, { style: 'width: 100%; font-size: 0.9em;' }); return table + this.backToMainMenuButton(); } } /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const utils = __webpack_require__(7); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); const rollOptions = { normal: { rollSetting: '{{ignore=[[0', message: 'normally', rollInfo: '', shaped_d20: '', }, advantage: { rollSetting: 'adv {{ignore=[[0', message: 'with advantage', rollInfo: '{{advantage=1}}', shaped_d20: '2d20@{d20_mod}kh1', }, disadvantage: { rollSetting: 'dis {{ignore=[[0', message: 'with disadvantage', rollInfo: '{{disadvantage=1}}', shaped_d20: '2d20@{d20_mod}kl1', }, roll2: { rollSetting: '{{roll2=[[d20@{d20_mod}', message: 'two dice', rollInfo: '', shaped_d20: '', }, }; class AdvantageTracker extends ShapedModule { addCommands(commandProcessor) { return commandProcessor.addCommand('at', this.process.bind(this), false) .option('advantage', ShapedConfig.booleanValidator) .option('disadvantage', ShapedConfig.booleanValidator) .option('normal', ShapedConfig.booleanValidator) .option('revert', ShapedConfig.booleanValidator) .option('persist', ShapedConfig.booleanValidator) .option('id', ShapedConfig.getCharacterValidator(this.roll20), false) .withSelection({ character: { min: 0, max: Infinity, }, }); } process(options) { let type = undefined; // const at = new AdvantageTracker(this.logger, this.myState, this.roll20); if (!_.isUndefined(options.id)) { // if an ID is passed, overwrite any selection, and only process for the passed charId options.selected.character = [options.id]; } if (_.isEmpty(options.selected.character)) { this.reportError('Advantage Tracker was called, but no token was selected, and no character id was passed.'); } else { if (options.normal) { type = 'normal'; } else if (options.advantage) { type = 'advantage'; } else if (options.disadvantage) { type = 'disadvantage'; } if (!_.isUndefined(type)) { this.setRollOption(type, options.selected.character); } if (options.revert) { this.setAutoRevert(true, options.selected.character); } else if (options.persist) { this.setAutoRevert(false, options.selected.character); } } } handleRollOptionChange(msg) { const char = []; char.push(msg.get('_characterid')); const br = this.buildResources(_.uniq(_.union(char))); if (!_.isEmpty(br)) { this.setStatusMarkers(br[0].tokens, msg.get('current') === rollOptions.advantage.rollSetting, msg.get('current') === rollOptions.disadvantage.rollSetting); switch (msg.get('current')) { case rollOptions.normal.rollSetting: this.sendChatNotification(br[0], 'normal'); break; case rollOptions.advantage.rollSetting: this.sendChatNotification(br[0], 'advantage'); break; case rollOptions.disadvantage.rollSetting: this.sendChatNotification(br[0], 'disadvantage'); break; default: break; } } } handleTokenChange(token) { this.logger.debug('AT: Updating New Token'); if (this.shouldShowMarkers() && token.get('represents') !== '') { const character = this.roll20.getObj('character', token.get('represents')); const setting = this.roll20.getAttrByName(character.id, 'roll_setting'); if (this.shouldIgnoreNpcs()) { if (this.roll20.getAttrByName(character.id, 'is_npc') === '1') { return; } } token.set(`status_${this.disadvantageMarker()}`, setting === rollOptions.disadvantage.rollSetting); token.set(`status_${this.advantageMarker()}`, setting === rollOptions.advantage.rollSetting); } } buildResources(characterIds) { let res = _.chain(characterIds) .map((charId) => this.roll20.getObj('character', charId)) .reject(_.isUndefined) .map((char) => ({ character: char, tokens: this.roll20.filterObjs((obj) => obj.get('_type') === 'graphic' && char.id === obj.get('represents')), })) .value(); if (this.shouldIgnoreNpcs()) { res = _.chain(res) .filter((c) => { const isNpc = this.roll20.getAttrByName(c.character.id, 'is_npc'); return isNpc && parseInt(isNpc, 10) === 0; }) .value(); } return res; } setStatusMarkers(tokens, showAdvantage, showDisadvantage) { if (this.shouldShowMarkers()) { _.each(tokens, (token) => { token.set(`status_${this.advantageMarker()}`, showAdvantage); token.set(`status_${this.disadvantageMarker()}`, showDisadvantage); }); } } setAutoRevert(value, selectedChars) { const resources = this.buildResources(_.chain(selectedChars).map(c => c.get('_id')).value()); _.each(resources, (resource) => { const charId = resource.character.get('_id'); this.roll20.setAttrByName(charId, 'auto_revert_advantage', value ? 'on' : 0); }); } setRollOption(type, selectedChars) { const resources = this.buildResources(_.chain(selectedChars).map(c => c.get('_id')).value()); _.each(resources, (resource) => { const charId = resource.character.get('_id'); this.setStatusMarkers(resource.tokens, type === 'advantage', type === 'disadvantage'); if (this.roll20.getAttrByName(charId, 'roll_setting') === rollOptions[type].rollSetting) { return; } this.roll20.setAttrByName(charId, 'roll_setting', rollOptions[type].rollSetting); this.roll20.setAttrByName(charId, 'roll_info', rollOptions[type].rollInfo); this.roll20.setAttrByName(charId, 'shaped_d20', rollOptions[type].shaped_d20); this.sendChatNotification(resource, type); }); } sendChatNotification(resource, type) { if (this.outputOption() !== 'silent') { let msg = ` &{template:5e-shaped} {{character_name=${resource.character.get('name')}}} ` + `@{${resource.character.get('name')}|show_character_name} {{title=${utils.toTitleCase(type)}}} ` + `{{text_top=${resource.character.get('name')} is rolling ${rollOptions[type].message}!}}`; if (this.outputOption() === 'whisper') { msg = `/w gm ${msg}`; } this.roll20.sendChat('Shaped AdvantageTracker', msg); } } outputOption() { return this.myState.config.advTrackerSettings.output; } shouldShowMarkers() { return this.myState.config.advTrackerSettings.showMarkers; } shouldIgnoreNpcs() { return this.myState.config.advTrackerSettings.ignoreNpcs; } advantageMarker() { return this.myState.config.advTrackerSettings.advantageMarker; } disadvantageMarker() { return this.myState.config.advTrackerSettings.disadvantageMarker; } } module.exports = AdvantageTracker; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const ShapedModule = __webpack_require__(13); const ShapedConfig = __webpack_require__(15); class RestManager extends ShapedModule { addCommands(commandProcessor) { return commandProcessor.addCommand('rest', this.handleRest.bind(this), false) .option('long', ShapedConfig.booleanValidator) .option('short', ShapedConfig.booleanValidator) .option('id', ShapedConfig.getCharacterValidator(this.roll20), false) .withSelection({ character: { min: 0, max: Infinity, }, }); } handleRest(options) { let chars = options.selected.character; if (!_.isUndefined(options.id)) { // if an ID is passed, overwrite any selection, and only process for the passed charId // NB this id will have been hydrated into a character object by the option processing so it's // already an object. The name should really change but it's baked into the sheet now so it's // too much hassle to change. chars = [options.id]; } if (options.long) { // handle long rest this.doLongRest(chars); } else if (options.short) { // handle short rest this.doShortRest(chars); } else { this.reportError('please specify long (!shaped-rest --long) or short (!shaped-rest --short) rest'); } } /** * Performs all of the short rest actions for the specified character * @param {Object[]} selectedChars - The characters to perform short rest actions on */ doShortRest(selectedChars) { _.each(selectedChars, (currentChar) => { const charId = currentChar.id; const charName = currentChar.get('name'); this.logger.debug(`Processing short rest for ${charName}:`); const traits = this.rechargeTraits(charId, 'short'); const msg = this.buildRestMessage('Short Rest', charName, charId, traits); this.roll20.sendChat(`character|${charId}`, msg); }); } /** * Performs all of the long rest actions for the specified character - including short rest actions * @param {Object[]} selectedChars - The characters to perform long rest actions on */ doLongRest(selectedChars) { _.each(selectedChars, (currentChar) => { const charId = currentChar.id; const charName = currentChar.get('name'); let healed = 0; this.logger.debug(`Processing long rest for ${charName}:`); let traits = this.rechargeTraits(charId, 'short'); traits = traits.concat(this.rechargeTraits(charId, 'long')); if (!this.myState.config.variants.rests.longNoHpFullHd) { healed = this.resetHP(currentChar); } const hd = this.regainHitDie(charId); const slots = this.regainSpellSlots(charId); const exhaus = this.reduceExhaustion(charId); const msg = this.buildRestMessage('Long Rest', charName, charId, traits, healed, hd, slots, exhaus); this.roll20.sendChat(`character|${charId}`, msg); }); } /** * Builds the rest message using the sheet's roll template to report the results of a rest * @param {string} restType - The type of rest performed; either 'Long Rest' or 'Short Rest' * @param {string} charName - The name of the character * @param {string} charId - The Roll20 character ID * @param {Object[]} traitNames - An array of the trait names that have been recharged * @param {int} healed - The number of HP healed * @param {Object[]} hdRegained - Array of objects each representing a die type and the number regained * @param {boolean} spellSlots - Whether or not spell slots were recharged * @param {boolean} exhaustion - Whether or not a level of exhaustoin was removed */ buildRestMessage(restType, charName, charId, traitNames, healed, hdRegained, spellSlots, exhaustion) { let msg = `&{template:5e-shaped} {{title=${restType}}} {{character_name=${charName}}}`; if (this.roll20.getAttrByName(charId, 'show_character_name') === '@{show_character_name_yes}') { msg += '{{show_character_name=1}}'; } if (hdRegained) { _.each(hdRegained, hd => { if (hd.quant > 0) { msg += `{{Hit Die Regained (${hd.die})=${hd.quant}}}`; } }); } if (traitNames) { msg += `{{Traits Recharged=${traitNames.join(', ')}}}`; } if (healed > 0) { msg += `{{heal=[[${healed}]]}}`; } if (spellSlots) { msg += '{{text_center=Spell Slots Regained}}'; } if (exhaustion) { msg += '{{text_top=Removed 1 Level Of Exhaustion}}'; } return msg; } /** * Recharges all of the repeating 'traits' section items that have a 'recharge' defined * @param {string} charId - the Roll20 character ID * @param {string} restType - the type of rest being performed; either 'Short Rest' or 'Long Rest' * @returns {Array} - An array of the trait names that were recharged */ rechargeTraits(charId, restType) { const traitNames = []; _.chain(this.roll20.findObjs({ type: 'attribute', characterid: charId })) .map(attribute => (attribute.get('name').match(/^repeating_trait_([^_]+)_recharge$/) || [])[1]) .reject(_.isUndefined) .uniq() .each(attId => { const traitPre = `repeating_trait_${attId}`; const rechargeAtt = this.roll20.getAttrByName(charId, `${traitPre}_recharge`); if (rechargeAtt.toLowerCase().indexOf(restType) !== -1) { const attName = this.roll20.getAttrByName(charId, `${traitPre}_name`); this.logger.debug(`Recharging '${attName}'`); traitNames.push(attName); const max = this.roll20.getAttrByName(charId, `${traitPre}_uses`, 'max'); if (max === undefined) { this.logger.error(`Tried to recharge the trait '${attName}' for character with id ${charId}, ` + 'but there were no uses defined.'); } else { this.roll20.setAttrByName(charId, `${traitPre}_uses`, max); } } }); return traitNames; } /** * Resets the HP of the specified character to its maximum value * @param {Object} character - the Roll20 character * @returns {int} - the number of HP that were healed */ resetHP(character) { const charId = character.id; this.logger.debug('Resetting HP to max'); const max = parseInt(this.roll20.getAttrByName(charId, 'HP', 'max'), 10); if (_.isNaN(max)) { this.reportError(`Can't recharge HP for character ${character.get('name')} because max HP is not set`); return 0; } const current = parseInt(this.roll20.getAttrByName(charId, 'HP', 'current') || 0, 10); this.roll20.setAttrByName(charId, 'HP', max); return max - current; } /** * Adds Hit die to the specified character based on PHB rules * @param {string} charId - the Roll20 character ID * @returns {Array} - Array of objects each representing a die type and the number regained */ regainHitDie(charId) { const hitDieRegained = []; this.logger.debug('Regaining Hit Die'); _.chain(this.roll20.findObjs({ type: 'attribute', characterid: charId })) .filter(attribute => (attribute.get('name').match(/^hd_d\d{1,2}$/))) .uniq() .each(hdAttr => { const max = parseInt(hdAttr.get('max'), 10); if (max > 0) { const oldCurrent = parseInt(hdAttr.get('current') || 0, 10); let newCurrent = oldCurrent; let regained = max === 1 ? 1 : Math.floor(max / 2); if (this.myState.config.variants.rests.longNoHpFullHd) { regained = max - oldCurrent; } newCurrent += regained; newCurrent = newCurrent > max ? max : newCurrent; this.roll20.setAttrByName(charId, hdAttr.get('name'), newCurrent); hitDieRegained.push({ die: hdAttr.get('name').replace(/hd_/, ''), quant: newCurrent - oldCurrent, }); } }); return hitDieRegained; } /** * Resets all (non warlock) spell slots of the specified character to their maximum values * @param {string} charId - the Roll20 character ID * @returns {boolean} - true if any spell slots were recharged; false otherwise */ regainSpellSlots(charId) { let slotsFound = false; this.logger.debug('Regaining Spell Slots'); _.chain(this.roll20.findObjs({ type: 'attribute', characterid: charId })) .filter(attribute => (attribute.get('name').match(/^spell_slots_l\d$/))) .uniq() .each(slotAttr => { const max = parseInt(slotAttr.get('max'), 10); if (max > 0) { this.roll20.setAttrByName(charId, slotAttr.get('name'), max); slotsFound = true; } }); return slotsFound; } /** * Reduces the specified character's level of exhaustion by 1 * @param {string} charId - the Roll20 character ID * @returns {boolean} - true if a level of exhaustion was reduced; false otherwise */ reduceExhaustion(charId) { this.logger.debug('Reducing Exhaustion'); const currentLevel = parseInt(this.roll20.getAttrByName(charId, 'exhaustion_level'), 10); if (currentLevel > 0) { this.roll20.setAttrByName(charId, 'exhaustion_level', currentLevel - 1); return true; } return false; } } module.exports = RestManager; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const ShapedModule = __webpack_require__(13); class TraitManager extends ShapedModule { addCommands(commandProcessor) { // no commands for this module return commandProcessor; } /** * Handles the click event of a trait when 'autoTraits' is true * Consumes one use of the clicked trait * @param {object} options - The message options */ handleTraitClick(options) { const traitId = _.chain(this.roll20.findObjs({ type: 'attribute', characterid: options.character.id })) .map(attribute => (attribute.get('name').match(/^repeating_trait_([^_]+)_name$/) || [])[1]) .reject(_.isUndefined) .uniq() .find(attId => this.roll20.getAttrByName(options.character.id, `repeating_trait_${attId}_name`) === options.title) .value(); const usesAttr = this.roll20.getAttrObjectByName(options.character.id, `repeating_trait_${traitId}_uses`); if (usesAttr) { if (usesAttr.get('current') > 0) { usesAttr.set('current', parseInt(usesAttr.get('current'), 10) - 1); } else { this.reportPublic('Trait Police', `${options.characterName} can't use ${options.title} because ` + 'they don\'t have any uses left.'); } } } } module.exports = TraitManager; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const ShapedModule = __webpack_require__(13); class AmmoManager extends ShapedModule { addCommands(commandProcessor) { return commandProcessor; } consumeAmmo(options, msg) { const ammoAttr = _.chain(this.roll20.findObjs({ type: 'attribute', characterid: options.character.id })) .filter(attribute => attribute.get('name').indexOf('repeating_ammo') === 0) .groupBy(attribute => attribute.get('name').replace(/(repeating_ammo_[^_]+).*/, '$1')) .find(attributeList => _.find(attributeList, attribute => attribute.get('name').match(/.*name$/) && attribute.get('current') === options.ammoName) ) .find(attribute => attribute.get('name').match(/.*qty$/)) .value(); if (!ammoAttr) { this.logger.error('No ammo attribute found corresponding to name $$$', options.ammoName); return; } let ammoUsed = 1; if (options.ammo) { const rollRef = options.ammo.match(/\$\[\[(\d+)\]\]/); if (rollRef) { const rollExpr = msg.inlinerolls[rollRef[1]].expression; const match = rollExpr.match(/\d+-(\d+)/); if (match) { ammoUsed = match[1]; } } } const val = parseInt(ammoAttr.get('current'), 10) || 0; ammoAttr.set('current', Math.max(0, val - ammoUsed)); } } module.exports = AmmoManager; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); function getRenameMapper(newName, upperCaseValue) { return function renameMapper(key, value, output) { output[newName] = upperCaseValue && value ? value.toUpperCase() : value; }; } function upperCaseMapper(key, value, output) { output[key] = value ? value.toUpperCase() : value; } function identityMapper(key, value, output) { output[key] = value; } function booleanMapper(key, value, output) { if (value) { output[key] = 'Yes'; } } function durationMapper(key, value, output, spellObj) { let newDuration = spellObj.concentration ? 'CONCENTRATION_' : ''; newDuration += value.toUpperCase().replace(/\s/g, '_'); output[key] = newDuration; } function spellLevelMapper(key, value, output) { let spellLevel; if (value === 0) { spellLevel = 'CANTRIP'; } else { switch (value % 10) { case 1: spellLevel = `${value}ST_LEVEL`; break; case 2: spellLevel = `${value}ND_LEVEL`; break; case 3: spellLevel = `${value}RD_LEVEL`; break; default: spellLevel = `${value}TH_LEVEL`; break; } } output.spell_level = spellLevel; } function camelCaseFixMapper(key, value, output) { const newKey = key.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`); output[newKey] = value; } function castingStatMapper(key, value, output) { if (value) { output.add_casting_modifier = 'Yes'; } } function castingTimeMapper(key, value, output) { output.casting_time = value && value.toUpperCase().replace(/\s/g, '_'); } function secondaryCastingStatMapper(key, value, output) { if (value) { output.add_second_casting_modifier = 'Yes'; } } function componentMapper(key, value, output) { const components = _.chain(value) .omit('materialCost') .map((propValue, propName) => { if (propName !== 'materialMaterial') { return propName.toUpperCase().slice(0, 1); } output.materials = propValue; return null; }) .compact() .value() .join('_'); if (components) { output.components = `COMPONENTS_${components}`; } } const saveAttackMappings = { ability: getRenameMapper('saving_throw_vs_ability', true), type: identityMapper, damage: identityMapper, damageBonus: camelCaseFixMapper, damageType: camelCaseFixMapper, saveSuccess: getRenameMapper('saving_throw_success'), saveFailure: getRenameMapper('saving_throw_failure'), higherLevelDice: camelCaseFixMapper, higherLevelDie: camelCaseFixMapper, secondaryDamage: getRenameMapper('second_damage'), secondaryDamageBonus: getRenameMapper('second_damage_bonus'), secondaryDamageType: getRenameMapper('second_damage_type'), higherLevelSecondaryDice: getRenameMapper('second_higher_level_dice'), higherLevelSecondaryDie: getRenameMapper('second_higher_level_die'), condition: getRenameMapper('saving_throw_condition'), castingStat: castingStatMapper, secondaryCastingStat: secondaryCastingStatMapper, }; function getObjectMapper(mappings) { return function objectMapper(key, value, output) { _.each(value, (propVal, propName) => { const mapper = mappings[propName]; if (!mapper) { throw new Error('Unrecognised property when attempting to convert to srd format: ' + `[${propName}] ${JSON.stringify(output)}`); } mapper(propName, propVal, output, value); }); }; } const spellMapper = getObjectMapper({ name: identityMapper, duration: durationMapper, level: spellLevelMapper, school: upperCaseMapper, emote: identityMapper, range: identityMapper, castingTime: castingTimeMapper, target: identityMapper, description(key, value, output) { output.content = value + (output.content ? `\n${output.content}` : ''); }, higherLevel(key, value, output) { output.content = output.content ? `${output.content}\n` : ''; output.content += value; }, ritual: booleanMapper, concentration: booleanMapper, save: getObjectMapper(saveAttackMappings), attack: getObjectMapper(saveAttackMappings), damage: getObjectMapper(saveAttackMappings), heal: getObjectMapper({ amount: getRenameMapper('heal'), castingStat: castingStatMapper, higherLevelDice: camelCaseFixMapper, higherLevelDie: camelCaseFixMapper, higherLevelAmount: getRenameMapper('higher_level_heal'), bonus: getRenameMapper('heal_bonus'), }), components: componentMapper, prepared(key, value, output) { if (value) { output.is_prepared = 'on'; } }, classes: _.noop, aoe: _.noop, source: _.noop, effects: _.noop, domains: _.noop, oaths: _.noop, circles: _.noop, patrons: _.noop, }); const monsterMapper = getObjectMapper({ name: getRenameMapper('character_name'), size: identityMapper, type: identityMapper, alignment: identityMapper, AC: getRenameMapper('ac_srd'), HP: getRenameMapper('hp_srd'), speed: getRenameMapper('npc_speed'), strength: identityMapper, dexterity: identityMapper, constitution: identityMapper, intelligence: identityMapper, wisdom: identityMapper, charisma: identityMapper, skills: getRenameMapper('skills_srd'), spells(key, value, output) { const splitSpells = _.partition(value, _.isObject); if (!_.isEmpty(splitSpells[1])) { output.spells_srd = splitSpells[1].join(', '); } if (!_.isEmpty(splitSpells[0])) { output.spells = splitSpells[0]; _.each(output.spells, spell => (spell.prepared = true)); } }, savingThrows: getRenameMapper('saving_throws_srd'), damageResistances: getRenameMapper('damage_resistances'), damageImmunities: getRenameMapper('damage_immunities'), conditionImmunities: getRenameMapper('condition_immunities'), damageVulnerabilities: getRenameMapper('damage_vulnerabilities'), senses: identityMapper, languages: identityMapper, challenge: identityMapper, traits: identityMapper, actions: identityMapper, reactions: identityMapper, regionalEffects: identityMapper, regionalEffectsFade: identityMapper, legendaryPoints: identityMapper, legendaryActions: identityMapper, lairActions: identityMapper, }); const pronounTokens = { '{{GENDER_PRONOUN_HE_SHE}}': 'nominative', '{{GENDER_PRONOUN_HIM_HER}}': 'accusative', '{{GENDER_PRONOUN_HIS_HER}}': 'possessive', '{{GENDER_PRONOUN_HIMSELF_HERSELF}}': 'reflexive', }; module.exports = { convertMonster(npcObject) { const output = {}; monsterMapper(null, npcObject, output); const actionTraitTemplate = _.template('**<%=data.name%>' + '<% if(data.recharge) { print(" (" + data.recharge + ")") } %>**: <%=data.text%>', { variable: 'data' }); const legendaryTemplate = _.template('**<%=data.name%>' + '<% if(data.cost && data.cost > 1){ print(" (Costs " + data.cost + " actions)") }%>**: <%=data.text%>', { variable: 'data' }); function lairRegionalTemplate(item) { return `**${item}`; } const simpleSectionTemplate = _.template('<%=data.title%>\n<% print(data.items.join("\\n")); %>', { variable: 'data' }); const legendarySectionTemplate = _.template('<%=data.title%>\n' + 'The <%=data.name%> can take <%=data.legendaryPoints%> legendary actions, choosing from the options below. ' + 'It can take only one legendary action at a time and only at the end of another creature\'s turn. ' + 'The <%=data.name%> regains spent legendary actions at the start of its turn.\n' + '<% print(data.items.join("\\n")) %>', { variable: 'data' }); const regionalSectionTemplate = _.template('<%=data.title%>\n<% print(data.items.join("\\n")); %>\n' + '**<%=data.regionalEffectsFade%>', { variable: 'data' }); const srdContentSections = [ { prop: 'traits', itemTemplate: actionTraitTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'actions', itemTemplate: actionTraitTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'reactions', itemTemplate: actionTraitTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'legendaryActions', itemTemplate: legendaryTemplate, sectionTemplate: legendarySectionTemplate }, { prop: 'lairActions', itemTemplate: lairRegionalTemplate, sectionTemplate: simpleSectionTemplate }, { prop: 'regionalEffects', itemTemplate: lairRegionalTemplate, sectionTemplate: regionalSectionTemplate }, ]; function makeDataObject(propertyName, itemList) { return { title: propertyName.replace(/([A-Z])/g, ' $1').replace(/^[a-z]/, letter => letter.toUpperCase()), name: output.character_name, legendaryPoints: output.legendaryPoints, regionalEffectsFade: output.regionalEffectsFade, items: itemList, }; } output.is_npc = 1; output.edit_mode = 'off'; output.content_srd = _.chain(srdContentSections) .map(sectionSpec => { const items = output[sectionSpec.prop]; delete output[sectionSpec.prop]; return _.map(items, sectionSpec.itemTemplate); }) .map((sectionItems, sectionIndex) => { const sectionSpec = srdContentSections[sectionIndex]; if (!_.isEmpty(sectionItems)) { return sectionSpec.sectionTemplate(makeDataObject(sectionSpec.prop, sectionItems)); } return null; }) .compact() .value() .join('\n'); delete output.legendaryPoints; return output; }, convertSpells(spellObjects, pronounInfo) { return _.map(spellObjects, spellObject => { const converted = {}; spellMapper(null, spellObject, converted); converted.toggle_details = 0; if (converted.emote) { _.each(pronounTokens, (pronounType, token) => { const replacement = pronounInfo[pronounType]; converted.emote = converted.emote.replace(new RegExp(token, 'g'), replacement); }); } return converted; }); }, }; /***/ }, /* 23 */ /***/ function(module, exports) { function sanitise(statblock, logger) { 'use strict'; logger.debug('Pre-sanitise: $$$', statblock); statblock = statblock .replace(/\s+([\.,;:])/g, '$1') .replace(/\n+/g, '#') .replace(/–/g, '-') .replace(/−/g, '-') // Watch out: this and the line above containing funny unicode versions of '-' .replace(/<br[^>]*>/g, '#') .replace(/#+/g, '#') .replace(/\s*#\s*/g, '#') .replace(/(<([^>]+)>)/gi, '') .replace(/legendary actions/gi, 'Legendary Actions') .replace(/(\S)\sACTIONS/, '$1#ACTIONS') .replace(/#(?=[a-z]|DC)/g, ' ') .replace(/\s+/g, ' ') .replace(/#Hit:/gi, 'Hit:') .replace(/Hit:#/gi, 'Hit: ') .replace(/#Each /gi, 'Each ') .replace(/#On a successful save/gi, 'On a successful save') .replace(/DC#(\d+)/g, 'DC $1') .replace('LanguagesChallenge', 'Languages -\nChallenge') .replace('\' Speed', 'Speed') .replace(/(\w+) s([\s\.,])/g, '$1s$2') .replace(/#Medium or/gi, ' Medium or') .replace(/take#(\d+)/gi, 'take $1') .replace(/#/g, '\n') .replace(/&gt;/g, '>') .replace(/&lt;/g, '<') .replace(/&amp;/g, '&'); logger.debug('First stage cleaned statblock: $$$', statblock); // Sometimes the texts ends up like 'P a r a l y z i n g T o u c h . M e l e e S p e l l A t t a c k : + 1 t o h i t // In this case we can fix the title case stuff, because we can find the word boundaries. That will at least meaning // that the core statblock parsing will work. If this happens inside the lowercase body text, however, there's nothing // we can do about it because you need to understand the natural language to reinsert the word breaks properly. statblock = statblock.replace(/([A-Z])(\s[a-z]){2,}/g, (match, p1) => p1 + match.slice(1).replace(/\s([a-z])/g, '$1') ); // Conversely, sometimes words get mushed together. Again, we can only fix this for title case things, but that's // better than nothing statblock = statblock.replace(/([A-Z][a-z]+)(?=[A-Z])/g, '$1 '); // This covers abilites that end up as 'C O N' or similar statblock = statblock.replace(/^[A-Z]\s?[A-Z]\s?[A-Z](?=\s|$)/mg, match => match.replace(/\s/g, '')); statblock = statblock.replace(/^[A-Z ]+$/m, match => match.replace(/([A-Z])([A-Z]+)(?=\s|$)/g, (innerMatch, p1, p2) => p1 + p2.toLowerCase()) ); statblock = statblock.replace(/(\d+)\s*?plus\s*?((?:\d+d\d+)|(?:\d+))/gi, '$2 + $1'); /* eslint-disable quote-props */ const replaceObj = { 'Jly': 'fly', ',1\'': ',*', 'jday': '/day', 'abol eth': 'aboleth', 'ACT IONS': 'ACTIONS', 'Afrightened': 'A frightened', 'Alesser': 'A lesser', 'Athl etics': 'Athletics', 'blindn ess': 'blindness', 'blind sight': 'blindsight', 'bofh': 'both', 'brea stplate': 'breastplate', 'Can trips': 'Cantrips', 'choos in g': 'choosing', 'com muni cate': 'communicate', 'Constituti on': 'Constitution', 'creatu re': 'creature', 'darkvi sion': 'darkvision', 'dea ls': 'deals', 'di sease': 'disease', 'di stance': 'distance', 'fa lls': 'falls', 'fe et': 'feet', 'exha les': 'exhales', 'ex istence': 'existence', 'lfthe': 'If the', 'Ifthe': 'If the', 'ifthe': 'if the', 'lnt': 'Int', 'magica lly': 'magically', 'Med icine': 'Medicine', 'minlilte': 'minute', 'natura l': 'natural', 'ofeach': 'of each', 'ofthe': 'of the', 'on\'e': 'one', 'on ly': 'only', '0n': 'on', 'pass ive': 'passive', 'Perce ption': 'Perception', 'radi us': 'radius', 'ra nge': 'range', 'rega ins': 'regains', 'rest.oration': 'restoration', 'savin g': 'saving', 'si lvery': 'silvery', 's lashing': 'slashing', 'slas hing': 'slashing', 'slash in g': 'slashing', 'slash ing': 'slashing', 'Spel/casting': 'Spellcasting', 'successfu l': 'successful', 'ta rget': 'target', ' Th e ': ' The ', 't_urns': 'turns', 'unti l': 'until', 'withi n': 'within', 'tohit': 'to hit', 'At wi ll': 'At will', 'per-son': 'person', 'ab ility': 'ability', 'spe ll': 'spell', }; /* eslint-enable quote-props */ const re = new RegExp(Object.keys(replaceObj).join('|'), 'g'); statblock = statblock.replace(re, (matched) => replaceObj[matched]); statblock = statblock .replace(/,\./gi, ',') .replace(/:\./g, ':') .replace(/(\W)l(\W)/g, '$11$2') .replace(/\.([\w])/g, '. $1') .replace(/1</g, '*') .replace(/(\w)ii/g, '$1ll') .replace(/([a-z\/])1/g, '$1l') .replace(/([a-z])\/([a-z])/g, '$1l$2') .replace(/(^| )l /gm, '$11 ') .replace(/ft\s\./gi, 'ft.') .replace(/ft\.\s,/gi, 'ft') .replace(/ft\./gi, 'ft') .replace(/(\d+) ft\/(\d+) ft/gi, '$1/$2 ft') .replace(/lOd/g, '10d') .replace(/dl0/gi, 'd10') .replace(/dlO/gi, 'd10') .replace(/dl2/gi, 'd12') .replace(/S(\d+)d(\d+)/gi, '5$1d$2') .replace(/l(\d+)d(\d+)/gi, '1$1d$2') .replace(/ld(\d+)/gi, '1d$1') .replace(/l(\d+)d\s+(\d+)/gi, '1$1d$2') .replace(/(\d+)d\s+(\d+)/gi, '$1d$2') .replace(/(\d+)\s+d(\d+)/gi, '$1d$2') .replace(/(\d+)\s+d(\d+)/gi, '$1d$2') .replace(/(\d+)d(\d)\s(\d)/gi, '$1d$2$3') .replace(/(\d+)j(?:Day|day)/gi, '$1/Day') .replace(/(\d+)f(?:Day|day)/gi, '$1/Day') .replace(/(\d+)j(\d+)/gi, '$1/$2') .replace(/(\d+)f(\d+)/gi, '$1/$2') .replace(/{/gi, '(') .replace(/}/gi, ')') .replace(/(\d+)\((\d+) ft/gi, '$1/$2 ft') .replace(/• /gi, '') .replace(/’/gi, '\''); logger.debug('Final stage cleaned statblock: $$$', statblock); return statblock; } module.exports = sanitise; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; const _ = __webpack_require__(2); const levelStrings = ['Cantrips ', '1st level ', '2nd level ', '3rd level ']; _.each(_.range(4, 10), level => (levelStrings[level] = `${level}th level `)); const spellcastingHandler = { splitRegex: /(Cantrips|(?:1st|2nd|3rd|[4-9]th)\s*level)\.?\s*\(([^\)]+)\)\s*:/i, makeLevelDetailsObject(match) { const levelMatch = match[1].match(/\d/); return { level: levelMatch ? parseInt(levelMatch[0], 10) : 0, slots: match[2], }; }, setLevelDetailsString(levelDetails) { levelDetails.newText = `${levelStrings[levelDetails.level]}(${levelDetails.slots}): `; levelDetails.newText += levelDetails.spells.join(', '); }, }; const innateHandler = { splitRegex: /(At\s?will|\d\s?\/\s?day)(?:\s?each)?\s?:/i, makeLevelDetailsObject(match) { const usesMatch = match[1].match(/\d/); return { uses: usesMatch ? parseInt(usesMatch[0], 10) : 0, slots: match[2], }; }, setLevelDetailsString(levelDetails) { levelDetails.newText = levelDetails.uses === 0 ? 'At will' : `${levelDetails.uses}/day`; if (levelDetails.spells.length > 1) { levelDetails.newText += ' each'; } levelDetails.newText += ': '; levelDetails.newText += levelDetails.spells.join(', '); }, }; function processSpellcastingTrait(monster, traitName, traitHandler, entityLookup) { const trait = _.findWhere(monster.traits, { name: traitName }); if (trait) { let spellList = trait.text.substring(trait.text.indexOf(':') + 1).replace('\n', ' '); const castingDetails = trait.text.substring(0, trait.text.indexOf(':')); const levelDetails = []; let match; while ((match = traitHandler.splitRegex.exec(spellList)) !== null) { if (_.last(levelDetails)) { _.last(levelDetails).spells = spellList.slice(0, match.index); } levelDetails.push(traitHandler.makeLevelDetailsObject(match)); spellList = spellList.slice(match.index + match[0].length); } if (_.last(levelDetails)) { _.last(levelDetails).spells = spellList; } let hasCastBeforeCombat = false; const spellDetailsByLevel = _.chain(levelDetails) .each(perLevelDetails => { perLevelDetails.spells = _.chain(perLevelDetails.spells.replace(',*', '*,').split(',')) .map(_.partial(_.result, _, 'trim')) .map(spellName => { const spellNameMatch = spellName.match(/([^\(\*]+)(?:\(([^\)]+)\))?(\*)?/); hasCastBeforeCombat = hasCastBeforeCombat || !!spellNameMatch[3]; return { name: spellNameMatch[1].trim(), restriction: spellNameMatch[2], castBeforeCombat: !!spellNameMatch[3], toString() { return this.name + (this.restriction ? ` (${this.restriction})` : '') + (this.castBeforeCombat ? '*' : ''); }, toSpellArrayItem() { return this.name; }, }; }) .each(spell => { spell.object = entityLookup.findEntity('spells', spell.name, true); if (spell.object) { spell.name = spell.object.name; spell.toSpellArrayItem = function toSpellArrayItem() { return this.object; }; } }) .value(); }) .each(traitHandler.setLevelDetailsString) .value(); trait.text = `${castingDetails}:\n${_.pluck(spellDetailsByLevel, 'newText').join('\n')}`; if (hasCastBeforeCombat) { trait.text += `\n* The ${monster.name.toLowerCase()} casts these spells on itself before combat.`; } const spells = _.chain(spellDetailsByLevel) .pluck('spells') .flatten() .map(_.partial(_.result, _, 'toSpellArrayItem')) .union(monster.spells ? monster.spells : []) .sortBy('name') .sortBy('level') .value(); if (!_.isEmpty(spells)) { monster.spells = spells; } } return []; } module.exports = function mpp(monsters, entityLookup) { _.each(monsters, monster => { processSpellcastingTrait(monster, 'Spellcasting', spellcastingHandler, entityLookup); processSpellcastingTrait(monster, 'Innate Spellcasting', innateHandler, entityLookup); }); }; /***/ } /******/ ]);
ajax/libs/yui/3.8.0pr1/event-custom-base/event-custom-base-coverage.js
ljharb/cdnjs
if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/event-custom-base/event-custom-base.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/event-custom-base/event-custom-base.js", code: [] }; _yuitest_coverage["build/event-custom-base/event-custom-base.js"].code=["YUI.add('event-custom-base', function (Y, NAME) {","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," */","","Y.Env.evt = {"," handles: {},"," plugins: {}","};","","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * Allows for the insertion of methods that are executed before or after"," * a specified method"," * @class Do"," * @static"," */","","var DO_BEFORE = 0,"," DO_AFTER = 1,","","DO = {",""," /**"," * Cache of objects touched by the utility"," * @property objs"," * @static"," * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object "," * replaces the role of this property, but is considered to be private, and "," * is only mentioned to provide a migration path."," * "," * If you have a use case which warrants migration to the _yuiaop property, "," * please file a ticket to let us know what it's used for and we can see if "," * we need to expose hooks for that functionality more formally."," */"," objs: null,",""," /**"," * <p>Execute the supplied method before the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt>"," * <dd>Replace the arguments that the original function will be"," * called with.</dd>"," * <dt></code>Y.Do.Prevent(message)</code></dt>"," * <dd>Don't execute the wrapped function. Other before phase"," * wrappers will be executed.</dd>"," * </dl>"," *"," * @method before"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {string} handle for the subscription"," * @static"," */"," before: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_BEFORE, f, obj, sFn);"," },",""," /**"," * <p>Execute the supplied method after the specified function. Wrapping"," * function may optionally return an instance of the following classes to"," * further alter runtime behavior:</p>"," * <dl>"," * <dt></code>Y.Do.Halt(message, returnValue)</code></dt>"," * <dd>Immediatly stop execution and return"," * <code>returnValue</code>. No other wrapping functions will be"," * executed.</dd>"," * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt>"," * <dd>Return <code>returnValue</code> instead of the wrapped"," * method's original return value. This can be further altered by"," * other after phase wrappers.</dd>"," * </dl>"," *"," * <p>The static properties <code>Y.Do.originalRetVal</code> and"," * <code>Y.Do.currentRetVal</code> will be populated for reference.</p>"," *"," * @method after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @param arg* {mixed} 0..n additional arguments to supply to the subscriber"," * @return {string} handle for the subscription"," * @static"," */"," after: function(fn, obj, sFn, c) {"," var f = fn, a;"," if (c) {"," a = [fn, c].concat(Y.Array(arguments, 4, true));"," f = Y.rbind.apply(Y, a);"," }",""," return this._inject(DO_AFTER, f, obj, sFn);"," },",""," /**"," * Execute the supplied method before or after the specified function."," * Used by <code>before</code> and <code>after</code>."," *"," * @method _inject"," * @param when {string} before or after"," * @param fn {Function} the function to execute"," * @param obj the object hosting the method to displace"," * @param sFn {string} the name of the method to displace"," * @param c The execution context for fn"," * @return {string} handle for the subscription"," * @private"," * @static"," */"," _inject: function(when, fn, obj, sFn) {"," // object id"," var id = Y.stamp(obj), o, sid;",""," if (!obj._yuiaop) {"," // create a map entry for the obj if it doesn't exist, to hold overridden methods"," obj._yuiaop = {};"," }",""," o = obj._yuiaop;",""," if (!o[sFn]) {"," // create a map entry for the method if it doesn't exist"," o[sFn] = new Y.Do.Method(obj, sFn);",""," // re-route the method to our wrapper"," obj[sFn] = function() {"," return o[sFn].exec.apply(o[sFn], arguments);"," };"," }",""," // subscriber id"," sid = id + Y.stamp(fn) + sFn;",""," // register the callback"," o[sFn].register(sid, fn, when);",""," return new Y.EventHandle(o[sFn], sid);"," },",""," /**"," * Detach a before or after subscription."," *"," * @method detach"," * @param handle {string} the subscription handle"," * @static"," */"," detach: function(handle) {"," if (handle.detach) {"," handle.detach();"," }"," },",""," _unload: function(e, me) {"," }","};","","Y.Do = DO;","","//////////////////////////////////////////////////////////////////////////","","/**"," * Contains the return value from the wrapped method, accessible"," * by 'after' event listeners."," *"," * @property originalRetVal"," * @static"," * @since 3.2.0"," */","","/**"," * Contains the current state of the return value, consumable by"," * 'after' event listeners, and updated if an after subscriber"," * changes the return value generated by the wrapped function."," *"," * @property currentRetVal"," * @static"," * @since 3.2.0"," */","","//////////////////////////////////////////////////////////////////////////","","/**"," * Wrapper for a displaced method with aop enabled"," * @class Do.Method"," * @constructor"," * @param obj The object to operate on"," * @param sFn The name of the method to displace"," */","DO.Method = function(obj, sFn) {"," this.obj = obj;"," this.methodName = sFn;"," this.method = obj[sFn];"," this.before = {};"," this.after = {};","};","","/**"," * Register a aop subscriber"," * @method register"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype.register = function (sid, fn, when) {"," if (when) {"," this.after[sid] = fn;"," } else {"," this.before[sid] = fn;"," }","};","","/**"," * Unregister a aop subscriber"," * @method delete"," * @param sid {string} the subscriber id"," * @param fn {Function} the function to execute"," * @param when {string} when to execute the function"," */","DO.Method.prototype._delete = function (sid) {"," delete this.before[sid];"," delete this.after[sid];","};","","/**"," * <p>Execute the wrapped method. All arguments are passed into the wrapping"," * functions. If any of the before wrappers return an instance of"," * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped"," * function nor any after phase subscribers will be executed.</p>"," *"," * <p>The return value will be the return value of the wrapped function or one"," * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or"," * <code>Y.Do.AlterReturn</code>."," *"," * @method exec"," * @param arg* {any} Arguments are passed to the wrapping and wrapped functions"," * @return {any} Return value of wrapped function unless overwritten (see above)"," */","DO.Method.prototype.exec = function () {",""," var args = Y.Array(arguments, 0, true),"," i, ret, newRet,"," bf = this.before,"," af = this.after,"," prevented = false;",""," // execute before"," for (i in bf) {"," if (bf.hasOwnProperty(i)) {"," ret = bf[i].apply(this.obj, args);"," if (ret) {"," switch (ret.constructor) {"," case DO.Halt:"," return ret.retVal;"," case DO.AlterArgs:"," args = ret.newArgs;"," break;"," case DO.Prevent:"," prevented = true;"," break;"," default:"," }"," }"," }"," }",""," // execute method"," if (!prevented) {"," ret = this.method.apply(this.obj, args);"," }",""," DO.originalRetVal = ret;"," DO.currentRetVal = ret;",""," // execute after methods."," for (i in af) {"," if (af.hasOwnProperty(i)) {"," newRet = af[i].apply(this.obj, args);"," // Stop processing if a Halt object is returned"," if (newRet && newRet.constructor == DO.Halt) {"," return newRet.retVal;"," // Check for a new return value"," } else if (newRet && newRet.constructor == DO.AlterReturn) {"," ret = newRet.newRetVal;"," // Update the static retval state"," DO.currentRetVal = ret;"," }"," }"," }",""," return ret;","};","","//////////////////////////////////////////////////////////////////////////","","/**"," * Return an AlterArgs object when you want to change the arguments that"," * were passed into the function. Useful for Do.before subscribers. An"," * example would be a service that scrubs out illegal characters prior to"," * executing the core business logic."," * @class Do.AlterArgs"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param newArgs {Array} Call parameters to be used for the original method"," * instead of the arguments originally passed in."," */","DO.AlterArgs = function(msg, newArgs) {"," this.msg = msg;"," this.newArgs = newArgs;","};","","/**"," * Return an AlterReturn object when you want to change the result returned"," * from the core method to the caller. Useful for Do.after subscribers."," * @class Do.AlterReturn"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param newRetVal {any} Return value passed to code that invoked the wrapped"," * function."," */","DO.AlterReturn = function(msg, newRetVal) {"," this.msg = msg;"," this.newRetVal = newRetVal;","};","","/**"," * Return a Halt object when you want to terminate the execution"," * of all subsequent subscribers as well as the wrapped method"," * if it has not exectued yet. Useful for Do.before subscribers."," * @class Do.Halt"," * @constructor"," * @param msg {String} (optional) Explanation of why the termination was done"," * @param retVal {any} Return value passed to code that invoked the wrapped"," * function."," */","DO.Halt = function(msg, retVal) {"," this.msg = msg;"," this.retVal = retVal;","};","","/**"," * Return a Prevent object when you want to prevent the wrapped function"," * from executing, but want the remaining listeners to execute. Useful"," * for Do.before subscribers."," * @class Do.Prevent"," * @constructor"," * @param msg {String} (optional) Explanation of why the termination was done"," */","DO.Prevent = function(msg) {"," this.msg = msg;","};","","/**"," * Return an Error object when you want to terminate the execution"," * of all subsequent method calls."," * @class Do.Error"," * @constructor"," * @param msg {String} (optional) Explanation of the altered return value"," * @param retVal {any} Return value passed to code that invoked the wrapped"," * function."," * @deprecated use Y.Do.Halt or Y.Do.Prevent"," */","DO.Error = DO.Halt;","","","//////////////////////////////////////////////////////////////////////////","","// Y[\"Event\"] && Y.Event.addListener(window, \"unload\", Y.Do._unload, Y.Do);","","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","","// var onsubscribeType = \"_event:onsub\",","var YArray = Y.Array,",""," AFTER = 'after',"," CONFIGS = ["," 'broadcast',"," 'monitored',"," 'bubbles',"," 'context',"," 'contextFn',"," 'currentTarget',"," 'defaultFn',"," 'defaultTargetOnly',"," 'details',"," 'emitFacade',"," 'fireOnce',"," 'async',"," 'host',"," 'preventable',"," 'preventedFn',"," 'queuable',"," 'silent',"," 'stoppedFn',"," 'target',"," 'type'"," ],",""," CONFIGS_HASH = YArray.hash(CONFIGS),",""," nativeSlice = Array.prototype.slice, ",""," YUI3_SIGNATURE = 9,"," YUI_LOG = 'yui:log',",""," mixConfigs = function(r, s, ov) {"," var p;",""," for (p in s) {"," if (CONFIGS_HASH[p] && (ov || !(p in r))) { "," r[p] = s[p];"," }"," }",""," return r;"," };","","/**"," * The CustomEvent class lets you define events for your application"," * that can be subscribed to by one or more independent component."," *"," * @param {String} type The type of event, which is passed to the callback"," * when the event fires."," * @param {object} o configuration object."," * @class CustomEvent"," * @constructor"," */","Y.CustomEvent = function(type, o) {",""," this._kds = Y.CustomEvent.keepDeprecatedSubs;",""," o = o || {};",""," this.id = Y.stamp(this);",""," /**"," * The type of event, returned to subscribers when the event fires"," * @property type"," * @type string"," */"," this.type = type;",""," /**"," * The context the the event will fire from by default. Defaults to the YUI"," * instance."," * @property context"," * @type object"," */"," this.context = Y;",""," /**"," * Monitor when an event is attached or detached."," *"," * @property monitored"," * @type boolean"," */"," // this.monitored = false;",""," this.logSystem = (type == YUI_LOG);",""," /**"," * If 0, this event does not broadcast. If 1, the YUI instance is notified"," * every time this event fires. If 2, the YUI instance and the YUI global"," * (if event is enabled on the global) are notified every time this event"," * fires."," * @property broadcast"," * @type int"," */"," // this.broadcast = 0;",""," /**"," * By default all custom events are logged in the debug build, set silent"," * to true to disable debug outpu for this event."," * @property silent"," * @type boolean"," */"," this.silent = this.logSystem;",""," /**"," * Specifies whether this event should be queued when the host is actively"," * processing an event. This will effect exectution order of the callbacks"," * for the various events."," * @property queuable"," * @type boolean"," * @default false"," */"," // this.queuable = false;",""," /**"," * The subscribers to this event"," * @property subscribers"," * @type Subscriber {}"," * @deprecated"," */"," if (this._kds) {"," this.subscribers = {};"," }",""," /**"," * The subscribers to this event"," * @property _subscribers"," * @type Subscriber []"," * @private"," */"," this._subscribers = [];",""," /**"," * 'After' subscribers"," * @property afters"," * @type Subscriber {}"," */"," if (this._kds) {"," this.afters = {};"," }",""," /**"," * 'After' subscribers"," * @property _afters"," * @type Subscriber []"," * @private"," */"," this._afters = [];",""," /**"," * This event has fired if true"," *"," * @property fired"," * @type boolean"," * @default false;"," */"," // this.fired = false;",""," /**"," * An array containing the arguments the custom event"," * was last fired with."," * @property firedWith"," * @type Array"," */"," // this.firedWith;",""," /**"," * This event should only fire one time if true, and if"," * it has fired, any new subscribers should be notified"," * immediately."," *"," * @property fireOnce"," * @type boolean"," * @default false;"," */"," // this.fireOnce = false;",""," /**"," * fireOnce listeners will fire syncronously unless async"," * is set to true"," * @property async"," * @type boolean"," * @default false"," */"," //this.async = false;",""," /**"," * Flag for stopPropagation that is modified during fire()"," * 1 means to stop propagation to bubble targets. 2 means"," * to also stop additional subscribers on this target."," * @property stopped"," * @type int"," */"," // this.stopped = 0;",""," /**"," * Flag for preventDefault that is modified during fire()."," * if it is not 0, the default behavior for this event"," * @property prevented"," * @type int"," */"," // this.prevented = 0;",""," /**"," * Specifies the host for this custom event. This is used"," * to enable event bubbling"," * @property host"," * @type EventTarget"," */"," // this.host = null;",""," /**"," * The default function to execute after event listeners"," * have fire, but only if the default action was not"," * prevented."," * @property defaultFn"," * @type Function"," */"," // this.defaultFn = null;",""," /**"," * The function to execute if a subscriber calls"," * stopPropagation or stopImmediatePropagation"," * @property stoppedFn"," * @type Function"," */"," // this.stoppedFn = null;",""," /**"," * The function to execute if a subscriber calls"," * preventDefault"," * @property preventedFn"," * @type Function"," */"," // this.preventedFn = null;",""," /**"," * Specifies whether or not this event's default function"," * can be cancelled by a subscriber by executing preventDefault()"," * on the event facade"," * @property preventable"," * @type boolean"," * @default true"," */"," this.preventable = true;",""," /**"," * Specifies whether or not a subscriber can stop the event propagation"," * via stopPropagation(), stopImmediatePropagation(), or halt()"," *"," * Events can only bubble if emitFacade is true."," *"," * @property bubbles"," * @type boolean"," * @default true"," */"," this.bubbles = true;",""," /**"," * Supports multiple options for listener signatures in order to"," * port YUI 2 apps."," * @property signature"," * @type int"," * @default 9"," */"," this.signature = YUI3_SIGNATURE;",""," // this.subCount = 0;"," // this.afterCount = 0;",""," // this.hasSubscribers = false;"," // this.hasAfters = false;",""," /**"," * If set to true, the custom event will deliver an EventFacade object"," * that is similar to a DOM event object."," * @property emitFacade"," * @type boolean"," * @default false"," */"," // this.emitFacade = false;",""," this.applyConfig(o, true);","","","};","","/**"," * Static flag to enable population of the <a href=\"#property_subscribers\">`subscribers`</a>"," * and <a href=\"#property_subscribers\">`afters`</a> properties held on a `CustomEvent` instance."," * "," * These properties were changed to private properties (`_subscribers` and `_afters`), and "," * converted from objects to arrays for performance reasons. "," *"," * Setting this property to true will populate the deprecated `subscribers` and `afters` "," * properties for people who may be using them (which is expected to be rare). There will"," * be a performance hit, compared to the new array based implementation."," *"," * If you are using these deprecated properties for a use case which the public API"," * does not support, please file an enhancement request, and we can provide an alternate "," * public implementation which doesn't have the performance cost required to maintiain the"," * properties as objects."," *"," * @property keepDeprecatedSubs"," * @static"," * @for CustomEvent"," * @type boolean"," * @default false"," * @deprecated"," */","Y.CustomEvent.keepDeprecatedSubs = false;","","Y.CustomEvent.mixConfigs = mixConfigs;","","Y.CustomEvent.prototype = {",""," constructor: Y.CustomEvent,",""," /**"," * Returns the number of subscribers for this event as the sum of the on()"," * subscribers and after() subscribers."," *"," * @method hasSubs"," * @return Number"," */"," hasSubs: function(when) {"," var s = this._subscribers.length, a = this._afters.length, sib = this.sibling;",""," if (sib) {"," s += sib._subscribers.length;"," a += sib._afters.length;"," }",""," if (when) {"," return (when == 'after') ? a : s;"," }",""," return (s + a);"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('detach', 'attach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," this.monitored = true;"," var type = this.id + '|' + this.type + '_' + what,"," args = nativeSlice.call(arguments, 0);"," args[0] = type;"," return this.host.on.apply(this.host, args);"," },",""," /**"," * Get all of the subscribers to this event and any sibling event"," * @method getSubs"," * @return {Array} first item is the on subscribers, second the after."," */"," getSubs: function() {"," var s = this._subscribers, a = this._afters, sib = this.sibling;",""," s = (sib) ? s.concat(sib._subscribers) : s.concat();"," a = (sib) ? a.concat(sib._afters) : a.concat();",""," return [s, a];"," },",""," /**"," * Apply configuration properties. Only applies the CONFIG whitelist"," * @method applyConfig"," * @param o hash of properties to apply."," * @param force {boolean} if true, properties that exist on the event"," * will be overwritten."," */"," applyConfig: function(o, force) {"," mixConfigs(this, o, force);"," },",""," /**"," * Create the Subscription for subscribing function, context, and bound"," * arguments. If this is a fireOnce event, the subscriber is immediately "," * notified."," *"," * @method _on"," * @param fn {Function} Subscription callback"," * @param [context] {Object} Override `this` in the callback"," * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire()"," * @param [when] {String} \"after\" to slot into after subscribers"," * @return {EventHandle}"," * @protected"," */"," _on: function(fn, context, args, when) {","",""," var s = new Y.Subscriber(fn, context, args, when);",""," if (this.fireOnce && this.fired) {"," if (this.async) {"," setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0);"," } else {"," this._notify(s, this.firedWith);"," }"," }",""," if (when == AFTER) {"," this._afters.push(s);"," } else {"," this._subscribers.push(s);"," }",""," if (this._kds) {"," if (when == AFTER) {"," this.afters[s.id] = s;"," } else {"," this.subscribers[s.id] = s;"," }"," }",""," return new Y.EventHandle(this, s);"," },",""," /**"," * Listen for this event"," * @method subscribe"," * @param {Function} fn The function to execute."," * @return {EventHandle} Unsubscribe handle."," * @deprecated use on."," */"," subscribe: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, true);"," },"," "," /**"," * Listen for this event"," * @method on"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} An object with a detach method to detch the handler(s)."," */"," on: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;",""," if (this.monitored && this.host) {"," this.host._monitor('attach', this, {"," args: arguments"," });"," }"," return this._on(fn, context, a, true);"," },",""," /**"," * Listen for this event after the normal subscribers have been notified and"," * the default behavior has been applied. If a normal subscriber prevents the"," * default behavior, it also prevents after listeners from firing."," * @method after"," * @param {Function} fn The function to execute."," * @param {object} context optional execution context."," * @param {mixed} arg* 0..n additional arguments to supply to the subscriber"," * when the event fires."," * @return {EventHandle} handle Unsubscribe handle."," */"," after: function(fn, context) {"," var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null;"," return this._on(fn, context, a, AFTER);"," },",""," /**"," * Detach listeners."," * @method detach"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int} returns the number of subscribers unsubscribed."," */"," detach: function(fn, context) {"," // unsubscribe handle"," if (fn && fn.detach) {"," return fn.detach();"," }"," "," var i, s,"," found = 0,"," subs = this._subscribers,"," afters = this._afters;",""," for (i = subs.length; i >= 0; i--) {"," s = subs[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, subs, i);"," found++;"," }"," }",""," for (i = afters.length; i >= 0; i--) {"," s = afters[i];"," if (s && (!fn || fn === s.fn)) {"," this._delete(s, afters, i);"," found++;"," }"," }",""," return found;"," },",""," /**"," * Detach listeners."," * @method unsubscribe"," * @param {Function} fn The subscribed function to remove, if not supplied"," * all will be removed."," * @param {Object} context The context object passed to subscribe."," * @return {int|undefined} returns the number of subscribers unsubscribed."," * @deprecated use detach."," */"," unsubscribe: function() {"," return this.detach.apply(this, arguments);"," },",""," /**"," * Notify a single subscriber"," * @method _notify"," * @param {Subscriber} s the subscriber."," * @param {Array} args the arguments array to apply to the listener."," * @protected"," */"," _notify: function(s, args, ef) {","",""," var ret;",""," ret = s.notify(args, this);",""," if (false === ret || this.stopped > 1) {"," return false;"," }",""," return true;"," },",""," /**"," * Logger abstraction to centralize the application of the silent flag"," * @method log"," * @param {string} msg message to log."," * @param {string} cat log category."," */"," log: function(msg, cat) {"," },",""," /**"," * Notifies the subscribers. The callback functions will be executed"," * from the context specified when the event was created, and with the"," * following parameters:"," * <ul>"," * <li>The type of event</li>"," * <li>All of the arguments fire() was executed with as an array</li>"," * <li>The custom object (if any) that was passed into the subscribe()"," * method</li>"," * </ul>"," * @method fire"," * @param {Object*} arguments an arbitrary set of parameters to pass to"," * the handler."," * @return {boolean} false if one of the subscribers returned false,"," * true otherwise."," *"," */"," fire: function() {"," if (this.fireOnce && this.fired) {"," return true;"," } else {",""," var args = nativeSlice.call(arguments, 0);",""," // this doesn't happen if the event isn't published"," // this.host._monitor('fire', this.type, args);",""," this.fired = true;",""," if (this.fireOnce) {"," this.firedWith = args;"," }",""," if (this.emitFacade) {"," return this.fireComplex(args);"," } else {"," return this.fireSimple(args);"," }"," }"," },",""," /**"," * Set up for notifying subscribers of non-emitFacade events."," *"," * @method fireSimple"," * @param args {Array} Arguments passed to fire()"," * @return Boolean false if a subscriber returned false"," * @protected"," */"," fireSimple: function(args) {"," this.stopped = 0;"," this.prevented = 0;"," if (this.hasSubs()) {"," var subs = this.getSubs();"," this._procSubs(subs[0], args);"," this._procSubs(subs[1], args);"," }"," this._broadcast(args);"," return this.stopped ? false : true;"," },",""," // Requires the event-custom-complex module for full funcitonality."," fireComplex: function(args) {"," args[0] = args[0] || {};"," return this.fireSimple(args);"," },",""," /**"," * Notifies a list of subscribers."," *"," * @method _procSubs"," * @param subs {Array} List of subscribers"," * @param args {Array} Arguments passed to fire()"," * @param ef {}"," * @return Boolean false if a subscriber returns false or stops the event"," * propagation via e.stopPropagation(),"," * e.stopImmediatePropagation(), or e.halt()"," * @private"," */"," _procSubs: function(subs, args, ef) {"," var s, i, l;",""," for (i = 0, l = subs.length; i < l; i++) {"," s = subs[i];"," if (s && s.fn) {"," if (false === this._notify(s, args, ef)) {"," this.stopped = 2;"," }"," if (this.stopped == 2) {"," return false;"," }"," }"," }",""," return true;"," },",""," /**"," * Notifies the YUI instance if the event is configured with broadcast = 1,"," * and both the YUI instance and Y.Global if configured with broadcast = 2."," *"," * @method _broadcast"," * @param args {Array} Arguments sent to fire()"," * @private"," */"," _broadcast: function(args) {"," if (!this.stopped && this.broadcast) {",""," var a = args.concat();"," a.unshift(this.type);",""," if (this.host !== Y) {"," Y.fire.apply(Y, a);"," }",""," if (this.broadcast == 2) {"," Y.Global.fire.apply(Y.Global, a);"," }"," }"," },",""," /**"," * Removes all listeners"," * @method unsubscribeAll"," * @return {int} The number of listeners unsubscribed."," * @deprecated use detachAll."," */"," unsubscribeAll: function() {"," return this.detachAll.apply(this, arguments);"," },",""," /**"," * Removes all listeners"," * @method detachAll"," * @return {int} The number of listeners unsubscribed."," */"," detachAll: function() {"," return this.detach();"," },",""," /**"," * Deletes the subscriber from the internal store of on() and after()"," * subscribers."," *"," * @method _delete"," * @param s subscriber object."," * @param subs (optional) on or after subscriber array"," * @param index (optional) The index found."," * @private"," */"," _delete: function(s, subs, i) {"," var when = s._when;",""," if (!subs) {"," subs = (when === AFTER) ? this._afters : this._subscribers; "," i = YArray.indexOf(subs, s, 0);"," }",""," if (s && subs[i] === s) {"," subs.splice(i, 1);"," }",""," if (this._kds) {"," if (when === AFTER) {"," delete this.afters[s.id];"," } else {"," delete this.subscribers[s.id];"," }"," }",""," if (this.monitored && this.host) {"," this.host._monitor('detach', this, {"," ce: this,"," sub: s"," });"," }",""," if (s) {"," s.deleted = true;"," }"," }","};","/**"," * Stores the subscriber information to be used when the event fires."," * @param {Function} fn The wrapped function to execute."," * @param {Object} context The value of the keyword 'this' in the listener."," * @param {Array} args* 0..n additional arguments to supply the listener."," *"," * @class Subscriber"," * @constructor"," */","Y.Subscriber = function(fn, context, args, when) {",""," /**"," * The callback that will be execute when the event fires"," * This is wrapped by Y.rbind if obj was supplied."," * @property fn"," * @type Function"," */"," this.fn = fn;",""," /**"," * Optional 'this' keyword for the listener"," * @property context"," * @type Object"," */"," this.context = context;",""," /**"," * Unique subscriber id"," * @property id"," * @type String"," */"," this.id = Y.stamp(this);",""," /**"," * Additional arguments to propagate to the subscriber"," * @property args"," * @type Array"," */"," this.args = args;",""," this._when = when;",""," /**"," * Custom events for a given fire transaction."," * @property events"," * @type {EventTarget}"," */"," // this.events = null;",""," /**"," * This listener only reacts to the event once"," * @property once"," */"," // this.once = false;","","};","","Y.Subscriber.prototype = {"," constructor: Y.Subscriber,",""," _notify: function(c, args, ce) {"," if (this.deleted && !this.postponed) {"," if (this.postponed) {"," delete this.fn;"," delete this.context;"," } else {"," delete this.postponed;"," return null;"," }"," }"," var a = this.args, ret;"," switch (ce.signature) {"," case 0:"," ret = this.fn.call(c, ce.type, args, c);"," break;"," case 1:"," ret = this.fn.call(c, args[0] || null, c);"," break;"," default:"," if (a || args) {"," args = args || [];"," a = (a) ? args.concat(a) : args;"," ret = this.fn.apply(c, a);"," } else {"," ret = this.fn.call(c);"," }"," }",""," if (this.once) {"," ce._delete(this);"," }",""," return ret;"," },",""," /**"," * Executes the subscriber."," * @method notify"," * @param args {Array} Arguments array for the subscriber."," * @param ce {CustomEvent} The custom event that sent the notification."," */"," notify: function(args, ce) {"," var c = this.context,"," ret = true;",""," if (!c) {"," c = (ce.contextFn) ? ce.contextFn() : ce.context;"," }",""," // only catch errors if we will not re-throw them."," if (Y.config && Y.config.throwFail) {"," ret = this._notify(c, args, ce);"," } else {"," try {"," ret = this._notify(c, args, ce);"," } catch (e) {"," Y.error(this + ' failed: ' + e.message, e);"," }"," }",""," return ret;"," },",""," /**"," * Returns true if the fn and obj match this objects properties."," * Used by the unsubscribe method to match the right subscriber."," *"," * @method contains"," * @param {Function} fn the function to execute."," * @param {Object} context optional 'this' keyword for the listener."," * @return {boolean} true if the supplied arguments match this"," * subscriber's signature."," */"," contains: function(fn, context) {"," if (context) {"," return ((this.fn == fn) && this.context == context);"," } else {"," return (this.fn == fn);"," }"," },"," "," valueOf : function() {"," return this.id;"," }","","};","/**"," * Return value from all subscribe operations"," * @class EventHandle"," * @constructor"," * @param {CustomEvent} evt the custom event."," * @param {Subscriber} sub the subscriber."," */","Y.EventHandle = function(evt, sub) {",""," /**"," * The custom event"," *"," * @property evt"," * @type CustomEvent"," */"," this.evt = evt;",""," /**"," * The subscriber object"," *"," * @property sub"," * @type Subscriber"," */"," this.sub = sub;","};","","Y.EventHandle.prototype = {"," batch: function(f, c) {"," f.call(c || this, this);"," if (Y.Lang.isArray(this.evt)) {"," Y.Array.each(this.evt, function(h) {"," h.batch.call(c || h, f);"," });"," }"," },",""," /**"," * Detaches this subscriber"," * @method detach"," * @return {int} the number of detached listeners"," */"," detach: function() {"," var evt = this.evt, detached = 0, i;"," if (evt) {"," if (Y.Lang.isArray(evt)) {"," for (i = 0; i < evt.length; i++) {"," detached += evt[i].detach();"," }"," } else {"," evt._delete(this.sub);"," detached = 1;"," }",""," }",""," return detached;"," },",""," /**"," * Monitor the event state for the subscribed event. The first parameter"," * is what should be monitored, the rest are the normal parameters when"," * subscribing to an event."," * @method monitor"," * @param what {string} what to monitor ('attach', 'detach', 'publish')."," * @return {EventHandle} return value from the monitor event subscription."," */"," monitor: function(what) {"," return this.evt.monitor.apply(this.evt, arguments);"," }","};","","/**"," * Custom event engine, DOM event listener abstraction layer, synthetic DOM"," * events."," * @module event-custom"," * @submodule event-custom-base"," */","","/**"," * EventTarget provides the implementation for any object to"," * publish, subscribe and fire to custom events, and also"," * alows other EventTargets to target the object with events"," * sourced from the other object."," * EventTarget is designed to be used with Y.augment to wrap"," * EventCustom in an interface that allows events to be listened to"," * and fired by name. This makes it possible for implementing code to"," * subscribe to an event that either has not been created yet, or will"," * not be created at all."," * @class EventTarget"," * @param opts a configuration object"," * @config emitFacade {boolean} if true, all events will emit event"," * facade payloads by default (default false)"," * @config prefix {String} the prefix to apply to non-prefixed event names"," */","","var L = Y.Lang,"," PREFIX_DELIMITER = ':',"," CATEGORY_DELIMITER = '|',"," AFTER_PREFIX = '~AFTER~',"," WILD_TYPE_RE = /(.*?)(:)(.*?)/,",""," _wildType = Y.cached(function(type) {"," return type.replace(WILD_TYPE_RE, \"*$2$3\");"," }),",""," /**"," * If the instance has a prefix attribute and the"," * event type is not prefixed, the instance prefix is"," * applied to the supplied type."," * @method _getType"," * @private"," */"," _getType = Y.cached(function(type, pre) {",""," if (!pre || (typeof type !== \"string\") || type.indexOf(PREFIX_DELIMITER) > -1) {"," return type;"," }",""," return pre + PREFIX_DELIMITER + type;"," }),",""," /**"," * Returns an array with the detach key (if provided),"," * and the prefixed event name from _getType"," * Y.on('detachcategory| menu:click', fn)"," * @method _parseType"," * @private"," */"," _parseType = Y.cached(function(type, pre) {",""," var t = type, detachcategory, after, i;",""," if (!L.isString(t)) {"," return t;"," }",""," i = t.indexOf(AFTER_PREFIX);",""," if (i > -1) {"," after = true;"," t = t.substr(AFTER_PREFIX.length);"," }",""," i = t.indexOf(CATEGORY_DELIMITER);",""," if (i > -1) {"," detachcategory = t.substr(0, (i));"," t = t.substr(i+1);"," if (t == '*') {"," t = null;"," }"," }",""," // detach category, full type with instance prefix, is this an after listener, short type"," return [detachcategory, (pre) ? _getType(t, pre) : t, after, t];"," }),",""," ET = function(opts) {","",""," var o = (L.isObject(opts)) ? opts : {};",""," this._yuievt = this._yuievt || {",""," id: Y.guid(),",""," events: {},",""," targets: {},",""," config: o,",""," chain: ('chain' in o) ? o.chain : Y.config.chain,",""," bubbling: false,",""," defaults: {"," context: o.context || this,"," host: this,"," emitFacade: o.emitFacade,"," fireOnce: o.fireOnce,"," queuable: o.queuable,"," monitored: o.monitored,"," broadcast: o.broadcast,"," defaultTargetOnly: o.defaultTargetOnly,"," bubbles: ('bubbles' in o) ? o.bubbles : true"," }"," };"," };","","","ET.prototype = {"," constructor: ET,",""," /**"," * Listen to a custom event hosted by this object one time."," * This is the equivalent to <code>on</code> except the"," * listener is immediatelly detached when it is executed."," * @method once"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," once: function() {"," var handle = this.on.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Listen to a custom event hosted by this object one time."," * This is the equivalent to <code>after</code> except the"," * listener is immediatelly detached when it is executed."," * @method onceAfter"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," onceAfter: function() {"," var handle = this.after.apply(this, arguments);"," handle.batch(function(hand) {"," if (hand.sub) {"," hand.sub.once = true;"," }"," });"," return handle;"," },",""," /**"," * Takes the type parameter passed to 'on' and parses out the"," * various pieces that could be included in the type. If the"," * event type is passed without a prefix, it will be expanded"," * to include the prefix one is supplied or the event target"," * is configured with a default prefix."," * @method parseType"," * @param {String} type the type"," * @param {String} [pre=this._yuievt.config.prefix] the prefix"," * @since 3.3.0"," * @return {Array} an array containing:"," * * the detach category, if supplied,"," * * the prefixed event type,"," * * whether or not this is an after listener,"," * * the supplied event type"," */"," parseType: function(type, pre) {"," return _parseType(type, pre || this._yuievt.config.prefix);"," },",""," /**"," * Subscribe a callback function to a custom event fired by this object or"," * from an object that bubbles its events to this object."," *"," * Callback functions for events published with `emitFacade = true` will"," * receive an `EventFacade` as the first argument (typically named \"e\")."," * These callbacks can then call `e.preventDefault()` to disable the"," * behavior published to that event's `defaultFn`. See the `EventFacade`"," * API for all available properties and methods. Subscribers to"," * non-`emitFacade` events will receive the arguments passed to `fire()`"," * after the event name."," *"," * To subscribe to multiple events at once, pass an object as the first"," * argument, where the key:value pairs correspond to the eventName:callback,"," * or pass an array of event names as the first argument to subscribe to"," * all listed events with the same callback."," *"," * Returning `false` from a callback is supported as an alternative to"," * calling `e.preventDefault(); e.stopPropagation();`. However, it is"," * recommended to use the event methods whenever possible."," *"," * @method on"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching that"," * subscription"," */"," on: function(type, fn, context) {",""," var yuievt = this._yuievt,"," parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce,"," detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype,"," Node = Y.Node, n, domevent, isArr;",""," // full name, args, detachcategory, after"," this._monitor('attach', parts[1], {"," args: arguments,"," category: parts[0],"," after: parts[2]"," });",""," if (L.isObject(type)) {",""," if (L.isFunction(type)) {"," return Y.Do.before.apply(Y.Do, arguments);"," }",""," f = fn;"," c = context;"," args = nativeSlice.call(arguments, 0);"," ret = [];",""," if (L.isArray(type)) {"," isArr = true;"," }",""," after = type._after;"," delete type._after;",""," Y.each(type, function(v, k) {",""," if (L.isObject(v)) {"," f = v.fn || ((L.isFunction(v)) ? v : f);"," c = v.context || c;"," }",""," var nv = (after) ? AFTER_PREFIX : '';",""," args[0] = nv + ((isArr) ? v : k);"," args[1] = f;"," args[2] = c;",""," ret.push(this.on.apply(this, args));",""," }, this);",""," return (yuievt.chain) ? this : new Y.EventHandle(ret);"," }",""," detachcategory = parts[0];"," after = parts[2];"," shorttype = parts[3];",""," // extra redirection so we catch adaptor events too. take a look at this."," if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) {"," args = nativeSlice.call(arguments, 0);"," args.splice(2, 0, Node.getDOMNode(this));"," return Y.on.apply(Y, args);"," }",""," type = parts[1];",""," if (Y.instanceOf(this, YUI)) {",""," adapt = Y.Env.evt.plugins[type];"," args = nativeSlice.call(arguments, 0);"," args[0] = shorttype;",""," if (Node) {"," n = args[2];",""," if (Y.instanceOf(n, Y.NodeList)) {"," n = Y.NodeList.getDOMNodes(n);"," } else if (Y.instanceOf(n, Node)) {"," n = Node.getDOMNode(n);"," }",""," domevent = (shorttype in Node.DOM_EVENTS);",""," // Captures both DOM events and event plugins."," if (domevent) {"," args[2] = n;"," }"," }",""," // check for the existance of an event adaptor"," if (adapt) {"," handle = adapt.on.apply(Y, args);"," } else if ((!type) || domevent) {"," handle = Y.Event._attach(args);"," }",""," }",""," if (!handle) {"," ce = yuievt.events[type] || this.publish(type);"," handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true);"," }",""," if (detachcategory) {"," store[detachcategory] = store[detachcategory] || {};"," store[detachcategory][type] = store[detachcategory][type] || [];"," store[detachcategory][type].push(handle);"," }",""," return (yuievt.chain) ? this : handle;",""," },",""," /**"," * subscribe to an event"," * @method subscribe"," * @deprecated use on"," */"," subscribe: function() {"," return this.on.apply(this, arguments);"," },",""," /**"," * Detach one or more listeners the from the specified event"," * @method detach"," * @param type {string|Object} Either the handle to the subscriber or the"," * type of event. If the type"," * is not specified, it will attempt to remove"," * the listener from all hosted events."," * @param fn {Function} The subscribed function to unsubscribe, if not"," * supplied, all subscribers will be removed."," * @param context {Object} The custom object passed to subscribe. This is"," * optional, but if supplied will be used to"," * disambiguate multiple listeners that are the same"," * (e.g., you subscribe many object using a function"," * that lives on the prototype)"," * @return {EventTarget} the host"," */"," detach: function(type, fn, context) {"," var evts = this._yuievt.events, i,"," Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node));",""," // detachAll disabled on the Y instance."," if (!type && (this !== Y)) {"," for (i in evts) {"," if (evts.hasOwnProperty(i)) {"," evts[i].detach(fn, context);"," }"," }"," if (isNode) {"," Y.Event.purgeElement(Node.getDOMNode(this));"," }",""," return this;"," }",""," var parts = _parseType(type, this._yuievt.config.prefix),"," detachcategory = L.isArray(parts) ? parts[0] : null,"," shorttype = (parts) ? parts[3] : null,"," adapt, store = Y.Env.evt.handles, detachhost, cat, args,"," ce,",""," keyDetacher = function(lcat, ltype, host) {"," var handles = lcat[ltype], ce, i;"," if (handles) {"," for (i = handles.length - 1; i >= 0; --i) {"," ce = handles[i].evt;"," if (ce.host === host || ce.el === host) {"," handles[i].detach();"," }"," }"," }"," };",""," if (detachcategory) {",""," cat = store[detachcategory];"," type = parts[1];"," detachhost = (isNode) ? Y.Node.getDOMNode(this) : this;",""," if (cat) {"," if (type) {"," keyDetacher(cat, type, detachhost);"," } else {"," for (i in cat) {"," if (cat.hasOwnProperty(i)) {"," keyDetacher(cat, i, detachhost);"," }"," }"," }",""," return this;"," }",""," // If this is an event handle, use it to detach"," } else if (L.isObject(type) && type.detach) {"," type.detach();"," return this;"," // extra redirection so we catch adaptor events too. take a look at this."," } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) {"," args = nativeSlice.call(arguments, 0);"," args[2] = Node.getDOMNode(this);"," Y.detach.apply(Y, args);"," return this;"," }",""," adapt = Y.Env.evt.plugins[shorttype];",""," // The YUI instance handles DOM events and adaptors"," if (Y.instanceOf(this, YUI)) {"," args = nativeSlice.call(arguments, 0);"," // use the adaptor specific detach code if"," if (adapt && adapt.detach) {"," adapt.detach.apply(Y, args);"," return this;"," // DOM event fork"," } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) {"," args[0] = type;"," Y.Event.detach.apply(Y.Event, args);"," return this;"," }"," }",""," // ce = evts[type];"," ce = evts[parts[1]];"," if (ce) {"," ce.detach(fn, context);"," }",""," return this;"," },",""," /**"," * detach a listener"," * @method unsubscribe"," * @deprecated use detach"," */"," unsubscribe: function() {"," return this.detach.apply(this, arguments);"," },",""," /**"," * Removes all listeners from the specified event. If the event type"," * is not specified, all listeners from all hosted custom events will"," * be removed."," * @method detachAll"," * @param type {String} The type, or name of the event"," */"," detachAll: function(type) {"," return this.detach(type);"," },",""," /**"," * Removes all listeners from the specified event. If the event type"," * is not specified, all listeners from all hosted custom events will"," * be removed."," * @method unsubscribeAll"," * @param type {String} The type, or name of the event"," * @deprecated use detachAll"," */"," unsubscribeAll: function() {"," return this.detachAll.apply(this, arguments);"," },",""," /**"," * Creates a new custom event of the specified type. If a custom event"," * by that name already exists, it will not be re-created. In either"," * case the custom event is returned."," *"," * @method publish"," *"," * @param type {String} the type, or name of the event"," * @param opts {object} optional config params. Valid properties are:"," *"," * <ul>"," * <li>"," * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false)"," * </li>"," * <li>"," * 'bubbles': whether or not this event bubbles (true)"," * Events can only bubble if emitFacade is true."," * </li>"," * <li>"," * 'context': the default execution context for the listeners (this)"," * </li>"," * <li>"," * 'defaultFn': the default function to execute when this event fires if preventDefault was not called"," * </li>"," * <li>"," * 'emitFacade': whether or not this event emits a facade (false)"," * </li>"," * <li>"," * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click'"," * </li>"," * <li>"," * 'fireOnce': if an event is configured to fire once, new subscribers after"," * the fire will be notified immediately."," * </li>"," * <li>"," * 'async': fireOnce event listeners will fire synchronously if the event has already"," * fired unless async is true."," * </li>"," * <li>"," * 'preventable': whether or not preventDefault() has an effect (true)"," * </li>"," * <li>"," * 'preventedFn': a function that is executed when preventDefault is called"," * </li>"," * <li>"," * 'queuable': whether or not this event can be queued during bubbling (false)"," * </li>"," * <li>"," * 'silent': if silent is true, debug messages are not provided for this event."," * </li>"," * <li>"," * 'stoppedFn': a function that is executed when stopPropagation is called"," * </li>"," *"," * <li>"," * 'monitored': specifies whether or not this event should send notifications about"," * when the event has been attached, detached, or published."," * </li>"," * <li>"," * 'type': the event type (valid option if not provided as the first parameter to publish)"," * </li>"," * </ul>"," *"," * @return {CustomEvent} the custom event"," *"," */"," publish: function(type, opts) {"," var events, ce, ret, defaults,"," edata = this._yuievt,"," pre = edata.config.prefix;",""," if (L.isObject(type)) {"," ret = {};"," Y.each(type, function(v, k) {"," ret[k] = this.publish(k, v || opts);"," }, this);",""," return ret;"," }",""," type = (pre) ? _getType(type, pre) : type;",""," events = edata.events;"," ce = events[type];",""," this._monitor('publish', type, {"," args: arguments"," });",""," if (ce) {"," // ce.log(\"publish applying new config to published event: '\"+type+\"' exists\", 'info', 'event');"," if (opts) {"," ce.applyConfig(opts, true);"," }"," } else {"," // TODO: Lazy publish goes here."," defaults = edata.defaults;",""," // apply defaults"," ce = new Y.CustomEvent(type, defaults);"," if (opts) {"," ce.applyConfig(opts, true);"," }",""," events[type] = ce;"," }",""," // make sure we turn the broadcast flag off if this"," // event was published as a result of bubbling"," // if (opts instanceof Y.CustomEvent) {"," // events[type].broadcast = false;"," // }",""," return events[type];"," },",""," /**"," * This is the entry point for the event monitoring system."," * You can monitor 'attach', 'detach', 'fire', and 'publish'."," * When configured, these events generate an event. click ->"," * click_attach, click_detach, click_publish -- these can"," * be subscribed to like other events to monitor the event"," * system. Inividual published events can have monitoring"," * turned on or off (publish can't be turned off before it"," * it published) by setting the events 'monitor' config."," *"," * @method _monitor"," * @param what {String} 'attach', 'detach', 'fire', or 'publish'"," * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object."," * @param o {Object} Information about the event interaction, such as"," * fire() args, subscription category, publish config"," * @private"," */"," _monitor: function(what, eventType, o) {"," var monitorevt, ce, type;",""," if (eventType) {"," if (typeof eventType === \"string\") {"," type = eventType;"," ce = this.getEvent(eventType, true);"," } else {"," ce = eventType;"," type = eventType.type;"," }",""," if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) {"," monitorevt = type + '_' + what;"," o.monitored = what;"," this.fire.call(this, monitorevt, o);"," }"," }"," },",""," /**"," * Fire a custom event by name. The callback functions will be executed"," * from the context specified when the event was created, and with the"," * following parameters."," *"," * If the custom event object hasn't been created, then the event hasn't"," * been published and it has no subscribers. For performance sake, we"," * immediate exit in this case. This means the event won't bubble, so"," * if the intention is that a bubble target be notified, the event must"," * be published on this object first."," *"," * The first argument is the event type, and any additional arguments are"," * passed to the listeners as parameters. If the first of these is an"," * object literal, and the event is configured to emit an event facade,"," * that object is mixed into the event facade and the facade is provided"," * in place of the original object."," *"," * @method fire"," * @param type {String|Object} The type of the event, or an object that contains"," * a 'type' property."," * @param arguments {Object*} an arbitrary set of parameters to pass to"," * the handler. If the first of these is an object literal and the event is"," * configured to emit an event facade, the event facade will replace that"," * parameter after the properties the object literal contains are copied to"," * the event facade."," * @return {EventTarget} the event host"," */"," fire: function(type) {",""," var typeIncluded = L.isString(type),"," t = (typeIncluded) ? type : (type && type.type),"," yuievt = this._yuievt,"," pre = yuievt.config.prefix, "," ce, ret, "," ce2,"," args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments;",""," t = (pre) ? _getType(t, pre) : t;",""," ce = this.getEvent(t, true);"," ce2 = this.getSibling(t, ce);",""," if (ce2 && !ce) {"," ce = this.publish(t);"," }",""," this._monitor('fire', (ce || t), {"," args: args"," });",""," // this event has not been published or subscribed to"," if (!ce) {"," if (yuievt.hasTargets) {"," return this.bubble({ type: t }, args, this);"," }",""," // otherwise there is nothing to be done"," ret = true;"," } else {"," ce.sibling = ce2;"," ret = ce.fire.apply(ce, args);"," }",""," return (yuievt.chain) ? this : ret;"," },",""," getSibling: function(type, ce) {"," var ce2;"," // delegate to *:type events if there are subscribers"," if (type.indexOf(PREFIX_DELIMITER) > -1) {"," type = _wildType(type);"," // console.log(type);"," ce2 = this.getEvent(type, true);"," if (ce2) {"," // console.log(\"GOT ONE: \" + type);"," ce2.applyConfig(ce);"," ce2.bubbles = false;"," ce2.broadcast = 0;"," // ret = ce2.fire.apply(ce2, a);"," }"," }",""," return ce2;"," },",""," /**"," * Returns the custom event of the provided type has been created, a"," * falsy value otherwise"," * @method getEvent"," * @param type {String} the type, or name of the event"," * @param prefixed {String} if true, the type is prefixed already"," * @return {CustomEvent} the custom event or null"," */"," getEvent: function(type, prefixed) {"," var pre, e;"," if (!prefixed) {"," pre = this._yuievt.config.prefix;"," type = (pre) ? _getType(type, pre) : type;"," }"," e = this._yuievt.events;"," return e[type] || null;"," },",""," /**"," * Subscribe to a custom event hosted by this object. The"," * supplied callback will execute after any listeners add"," * via the subscribe method, and after the default function,"," * if configured for the event, has executed."," *"," * @method after"," * @param {String} type The name of the event"," * @param {Function} fn The callback to execute in response to the event"," * @param {Object} [context] Override `this` object in callback"," * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber"," * @return {EventHandle} A subscription handle capable of detaching the"," * subscription"," */"," after: function(type, fn) {",""," var a = nativeSlice.call(arguments, 0);",""," switch (L.type(type)) {"," case 'function':"," return Y.Do.after.apply(Y.Do, arguments);"," case 'array':"," // YArray.each(a[0], function(v) {"," // v = AFTER_PREFIX + v;"," // });"," // break;"," case 'object':"," a[0]._after = true;"," break;"," default:"," a[0] = AFTER_PREFIX + type;"," }",""," return this.on.apply(this, a);",""," },",""," /**"," * Executes the callback before a DOM event, custom event"," * or method. If the first argument is a function, it"," * is assumed the target is a method. For DOM and custom"," * events, this is an alias for Y.on."," *"," * For DOM and custom events:"," * type, callback, context, 0-n arguments"," *"," * For methods:"," * callback, object (method host), methodName, context, 0-n arguments"," *"," * @method before"," * @return detach handle"," */"," before: function() {"," return this.on.apply(this, arguments);"," }","","};","","Y.EventTarget = ET;","","// make Y an event target","Y.mix(Y, ET.prototype);","ET.call(Y, { bubbles: false });","","YUI.Env.globalEvents = YUI.Env.globalEvents || new ET();","","/**"," * Hosts YUI page level events. This is where events bubble to"," * when the broadcast config is set to 2. This property is"," * only available if the custom event module is loaded."," * @property Global"," * @type EventTarget"," * @for YUI"," */","Y.Global = YUI.Env.globalEvents;","","// @TODO implement a global namespace function on Y.Global?","","/**","`Y.on()` can do many things:","","<ul>"," <li>Subscribe to custom events `publish`ed and `fire`d from Y</li>"," <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and"," `fire`d from any object in the YUI instance sandbox</li>"," <li>Subscribe to DOM events</li>"," <li>Subscribe to the execution of a method on any object, effectively"," treating that method as an event</li>","</ul>","","For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument.",""," Y.on('io:complete', function () {"," Y.MyApp.updateStatus('Transaction complete');"," });","","To subscribe to DOM events, pass the name of a DOM event as the first argument","and a CSS selector string as the third argument after the callback function.","Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`,","array, or simply omitted (the default is the `window` object).",""," Y.on('click', function (e) {"," e.preventDefault();",""," // proceed with ajax form submission"," var url = this.get('action');"," ..."," }, '#my-form');","","The `this` object in DOM event callbacks will be the `Node` targeted by the CSS","selector or other identifier.","","`on()` subscribers for DOM events or custom events `publish`ed with a","`defaultFn` can prevent the default behavior with `e.preventDefault()` from the","event object passed as the first parameter to the subscription callback.","","To subscribe to the execution of an object method, pass arguments corresponding to the call signature for ","<a href=\"../classes/Do.html#methods_before\">`Y.Do.before(...)`</a>.","","NOTE: The formal parameter list below is for events, not for function","injection. See `Y.Do.before` for that signature.","","@method on","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@see Do.before","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `on()`, except that","the listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see on","@method once","@param {String} type DOM or custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Listen for an event one time. Equivalent to `once()`, except, like `after()`,","the subscription callback executes after all `on()` subscribers and the event's","`defaultFn` (if configured) have executed. Like `after()` if any `on()` phase","subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()`","subscribers will execute.","","The listener is immediately detached when executed.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","@see once","@method onceAfter","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [arg*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","/**","Like `on()`, this method creates a subscription to a custom event or to the","execution of a method on an object.","","For events, `after()` subscribers are executed after the event's","`defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber.","","See the <a href=\"#methods_on\">`on()` method</a> for additional subscription","options.","","NOTE: The subscription signature shown is for events, not for function","injection. See <a href=\"../classes/Do.html#methods_after\">`Y.Do.after`</a>","for that signature.","","@see on","@see Do.after","@method after","@param {String} type The custom event name","@param {Function} fn The callback to execute in response to the event","@param {Object} [context] Override `this` object in callback","@param {Any} [args*] 0..n additional arguments to supply to the subscriber","@return {EventHandle} A subscription handle capable of detaching the"," subscription","@for YUI","**/","","","}, '@VERSION@', {\"requires\": [\"oop\"]});"]; _yuitest_coverage["build/event-custom-base/event-custom-base.js"].lines = {"1":0,"9":0,"29":0,"76":0,"77":0,"78":0,"79":0,"82":0,"113":0,"114":0,"115":0,"116":0,"119":0,"138":0,"140":0,"142":0,"145":0,"147":0,"149":0,"152":0,"153":0,"158":0,"161":0,"163":0,"174":0,"175":0,"183":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"230":0,"231":0,"232":0,"234":0,"245":0,"246":0,"247":0,"264":0,"266":0,"273":0,"274":0,"275":0,"276":0,"277":0,"279":0,"281":0,"282":0,"284":0,"285":0,"293":0,"294":0,"297":0,"298":0,"301":0,"302":0,"303":0,"305":0,"306":0,"308":0,"309":0,"311":0,"316":0,"332":0,"333":0,"334":0,"346":0,"347":0,"348":0,"361":0,"362":0,"363":0,"374":0,"375":0,"388":0,"405":0,"439":0,"441":0,"442":0,"443":0,"447":0,"460":0,"462":0,"464":0,"466":0,"473":0,"481":0,"491":0,"509":0,"527":0,"528":0,"537":0,"544":0,"545":0,"554":0,"651":0,"663":0,"672":0,"689":0,"717":0,"719":0,"721":0,"733":0,"735":0,"736":0,"737":0,"740":0,"741":0,"744":0,"756":0,"757":0,"759":0,"760":0,"769":0,"771":0,"772":0,"774":0,"785":0,"804":0,"806":0,"807":0,"808":0,"810":0,"814":0,"815":0,"817":0,"820":0,"821":0,"822":0,"824":0,"828":0,"839":0,"840":0,"853":0,"855":0,"856":0,"860":0,"875":0,"876":0,"889":0,"890":0,"893":0,"898":0,"899":0,"900":0,"901":0,"902":0,"906":0,"907":0,"908":0,"909":0,"910":0,"914":0,"927":0,"940":0,"942":0,"944":0,"945":0,"948":0,"978":0,"979":0,"982":0,"987":0,"989":0,"990":0,"993":0,"994":0,"996":0,"1010":0,"1011":0,"1012":0,"1013":0,"1014":0,"1015":0,"1017":0,"1018":0,"1023":0,"1024":0,"1040":0,"1042":0,"1043":0,"1044":0,"1045":0,"1046":0,"1048":0,"1049":0,"1054":0,"1066":0,"1068":0,"1069":0,"1071":0,"1072":0,"1075":0,"1076":0,"1088":0,"1097":0,"1111":0,"1113":0,"1114":0,"1115":0,"1118":0,"1119":0,"1122":0,"1123":0,"1124":0,"1126":0,"1130":0,"1131":0,"1137":0,"1138":0,"1151":0,"1159":0,"1166":0,"1173":0,"1180":0,"1182":0,"1199":0,"1203":0,"1204":0,"1205":0,"1206":0,"1208":0,"1209":0,"1212":0,"1213":0,"1215":0,"1216":0,"1218":0,"1219":0,"1221":0,"1222":0,"1223":0,"1224":0,"1226":0,"1230":0,"1231":0,"1234":0,"1244":0,"1247":0,"1248":0,"1252":0,"1253":0,"1255":0,"1256":0,"1258":0,"1262":0,"1276":0,"1277":0,"1279":0,"1284":0,"1295":0,"1303":0,"1311":0,"1314":0,"1316":0,"1317":0,"1318":0,"1319":0,"1330":0,"1331":0,"1332":0,"1333":0,"1334":0,"1337":0,"1338":0,"1343":0,"1355":0,"1383":0,"1390":0,"1402":0,"1403":0,"1406":0,"1418":0,"1420":0,"1421":0,"1424":0,"1426":0,"1427":0,"1428":0,"1431":0,"1433":0,"1434":0,"1435":0,"1436":0,"1437":0,"1442":0,"1448":0,"1450":0,"1479":0,"1495":0,"1496":0,"1497":0,"1498":0,"1501":0,"1517":0,"1518":0,"1519":0,"1520":0,"1523":0,"1543":0,"1577":0,"1583":0,"1589":0,"1591":0,"1592":0,"1595":0,"1596":0,"1597":0,"1598":0,"1600":0,"1601":0,"1604":0,"1605":0,"1607":0,"1609":0,"1610":0,"1611":0,"1614":0,"1616":0,"1617":0,"1618":0,"1620":0,"1624":0,"1627":0,"1628":0,"1629":0,"1632":0,"1633":0,"1634":0,"1635":0,"1638":0,"1640":0,"1642":0,"1643":0,"1644":0,"1646":0,"1647":0,"1649":0,"1650":0,"1651":0,"1652":0,"1655":0,"1658":0,"1659":0,"1664":0,"1665":0,"1666":0,"1667":0,"1672":0,"1673":0,"1674":0,"1677":0,"1678":0,"1679":0,"1680":0,"1683":0,"1693":0,"1713":0,"1717":0,"1718":0,"1719":0,"1720":0,"1723":0,"1724":0,"1727":0,"1730":0,"1737":0,"1738":0,"1739":0,"1740":0,"1741":0,"1742":0,"1748":0,"1750":0,"1751":0,"1752":0,"1754":0,"1755":0,"1756":0,"1758":0,"1759":0,"1760":0,"1765":0,"1769":0,"1770":0,"1771":0,"1773":0,"1774":0,"1775":0,"1776":0,"1777":0,"1780":0,"1783":0,"1784":0,"1786":0,"1787":0,"1788":0,"1790":0,"1791":0,"1792":0,"1793":0,"1798":0,"1799":0,"1800":0,"1803":0,"1812":0,"1823":0,"1835":0,"1905":0,"1909":0,"1910":0,"1911":0,"1912":0,"1915":0,"1918":0,"1920":0,"1921":0,"1923":0,"1927":0,"1929":0,"1930":0,"1934":0,"1937":0,"1938":0,"1939":0,"1942":0,"1951":0,"1972":0,"1974":0,"1975":0,"1976":0,"1977":0,"1979":0,"1980":0,"1983":0,"1984":0,"1985":0,"1986":0,"2020":0,"2028":0,"2030":0,"2031":0,"2033":0,"2034":0,"2037":0,"2042":0,"2043":0,"2044":0,"2048":0,"2050":0,"2051":0,"2054":0,"2058":0,"2060":0,"2061":0,"2063":0,"2064":0,"2066":0,"2067":0,"2068":0,"2073":0,"2085":0,"2086":0,"2087":0,"2088":0,"2090":0,"2091":0,"2110":0,"2112":0,"2114":0,"2121":0,"2122":0,"2124":0,"2127":0,"2147":0,"2152":0,"2155":0,"2156":0,"2158":0,"2168":0}; _yuitest_coverage["build/event-custom-base/event-custom-base.js"].functions = {"before:75":0,"after:112":0,"]:152":0,"_inject:136":0,"detach:173":0,"Method:215":0,"register:230":0,"_delete:245":0,"exec:264":0,"AlterArgs:332":0,"AlterReturn:346":0,"Halt:361":0,"Prevent:374":0,"mixConfigs:438":0,"CustomEvent:460":0,"hasSubs:732":0,"monitor:755":0,"getSubs:768":0,"applyConfig:784":0,"_on:801":0,"subscribe:838":0,"on:852":0,"after:874":0,"detach:887":0,"unsubscribe:926":0,"_notify:937":0,"fire:977":0,"fireSimple:1009":0,"fireComplex:1022":0,"_procSubs:1039":0,"_broadcast:1065":0,"unsubscribeAll:1087":0,"detachAll:1096":0,"_delete:1110":0,"Subscriber:1151":0,"_notify:1202":0,"notify:1243":0,"contains:1275":0,"valueOf:1283":0,"EventHandle:1295":0,"(anonymous 2):1318":0,"batch:1315":0,"detach:1329":0,"monitor:1354":0,"(anonymous 3):1389":0,"(anonymous 4):1400":0,"(anonymous 5):1416":0,"ET:1445":0,"(anonymous 6):1496":0,"once:1494":0,"(anonymous 7):1518":0,"onceAfter:1516":0,"parseType:1542":0,"(anonymous 8):1607":0,"on:1575":0,"subscribe:1692":0,"keyDetacher:1736":0,"detach:1712":0,"unsubscribe:1811":0,"detachAll:1822":0,"unsubscribeAll:1834":0,"(anonymous 9):1911":0,"publish:1904":0,"_monitor:1971":0,"fire:2018":0,"getSibling:2057":0,"getEvent:2084":0,"after:2108":0,"before:2146":0,"(anonymous 1):1":0}; _yuitest_coverage["build/event-custom-base/event-custom-base.js"].coveredLines = 482; _yuitest_coverage["build/event-custom-base/event-custom-base.js"].coveredFunctions = 70; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 1)", 1); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 9); Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 29); var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "before", 75); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 76); var f = fn, a; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 77); if (c) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 78); a = [fn, c].concat(Y.Array(arguments, 4, true)); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 79); f = Y.rbind.apply(Y, a); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 82); return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "after", 112); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 113); var f = fn, a; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 114); if (c) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 115); a = [fn, c].concat(Y.Array(arguments, 4, true)); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 116); f = Y.rbind.apply(Y, a); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 119); return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_inject", 136); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 138); var id = Y.stamp(obj), o, sid; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 140); if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods _yuitest_coverline("build/event-custom-base/event-custom-base.js", 142); obj._yuiaop = {}; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 145); o = obj._yuiaop; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 147); if (!o[sFn]) { // create a map entry for the method if it doesn't exist _yuitest_coverline("build/event-custom-base/event-custom-base.js", 149); o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper _yuitest_coverline("build/event-custom-base/event-custom-base.js", 152); obj[sFn] = function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "]", 152); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 153); return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id _yuitest_coverline("build/event-custom-base/event-custom-base.js", 158); sid = id + Y.stamp(fn) + sFn; // register the callback _yuitest_coverline("build/event-custom-base/event-custom-base.js", 161); o[sFn].register(sid, fn, when); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 163); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 173); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 174); if (handle.detach) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 175); handle.detach(); } }, _unload: function(e, me) { } }; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 183); Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 215); DO.Method = function(obj, sFn) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Method", 215); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 216); this.obj = obj; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 217); this.methodName = sFn; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 218); this.method = obj[sFn]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 219); this.before = {}; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 220); this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 230); DO.Method.prototype.register = function (sid, fn, when) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "register", 230); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 231); if (when) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 232); this.after[sid] = fn; } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 234); this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 245); DO.Method.prototype._delete = function (sid) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_delete", 245); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 246); delete this.before[sid]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 247); delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 264); DO.Method.prototype.exec = function () { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "exec", 264); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 266); var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before _yuitest_coverline("build/event-custom-base/event-custom-base.js", 273); for (i in bf) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 274); if (bf.hasOwnProperty(i)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 275); ret = bf[i].apply(this.obj, args); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 276); if (ret) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 277); switch (ret.constructor) { case DO.Halt: _yuitest_coverline("build/event-custom-base/event-custom-base.js", 279); return ret.retVal; case DO.AlterArgs: _yuitest_coverline("build/event-custom-base/event-custom-base.js", 281); args = ret.newArgs; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 282); break; case DO.Prevent: _yuitest_coverline("build/event-custom-base/event-custom-base.js", 284); prevented = true; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 285); break; default: } } } } // execute method _yuitest_coverline("build/event-custom-base/event-custom-base.js", 293); if (!prevented) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 294); ret = this.method.apply(this.obj, args); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 297); DO.originalRetVal = ret; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 298); DO.currentRetVal = ret; // execute after methods. _yuitest_coverline("build/event-custom-base/event-custom-base.js", 301); for (i in af) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 302); if (af.hasOwnProperty(i)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 303); newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned _yuitest_coverline("build/event-custom-base/event-custom-base.js", 305); if (newRet && newRet.constructor == DO.Halt) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 306); return newRet.retVal; // Check for a new return value } else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 308); if (newRet && newRet.constructor == DO.AlterReturn) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 309); ret = newRet.newRetVal; // Update the static retval state _yuitest_coverline("build/event-custom-base/event-custom-base.js", 311); DO.currentRetVal = ret; }} } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 316); return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 332); DO.AlterArgs = function(msg, newArgs) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "AlterArgs", 332); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 333); this.msg = msg; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 334); this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 346); DO.AlterReturn = function(msg, newRetVal) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "AlterReturn", 346); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 347); this.msg = msg; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 348); this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 361); DO.Halt = function(msg, retVal) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Halt", 361); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 362); this.msg = msg; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 363); this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 374); DO.Prevent = function(msg) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Prevent", 374); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 375); this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 388); DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", _yuitest_coverline("build/event-custom-base/event-custom-base.js", 405); var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "mixConfigs", 438); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 439); var p; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 441); for (p in s) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 442); if (CONFIGS_HASH[p] && (ov || !(p in r))) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 443); r[p] = s[p]; } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 447); return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 460); Y.CustomEvent = function(type, o) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "CustomEvent", 460); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 462); this._kds = Y.CustomEvent.keepDeprecatedSubs; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 464); o = o || {}; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 466); this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 473); this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 481); this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 491); this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 509); this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 527); if (this._kds) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 528); this.subscribers = {}; } /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 537); this._subscribers = []; /** * 'After' subscribers * @property afters * @type Subscriber {} */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 544); if (this._kds) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 545); this.afters = {}; } /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 554); this._afters = []; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 651); this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 663); this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 672); this.signature = YUI3_SIGNATURE; // this.subCount = 0; // this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 689); this.applyConfig(o, true); }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 717); Y.CustomEvent.keepDeprecatedSubs = false; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 719); Y.CustomEvent.mixConfigs = mixConfigs; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 721); Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "hasSubs", 732); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 733); var s = this._subscribers.length, a = this._afters.length, sib = this.sibling; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 735); if (sib) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 736); s += sib._subscribers.length; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 737); a += sib._afters.length; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 740); if (when) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 741); return (when == 'after') ? a : s; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 744); return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "monitor", 755); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 756); this.monitored = true; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 757); var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 759); args[0] = type; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 760); return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "getSubs", 768); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 769); var s = this._subscribers, a = this._afters, sib = this.sibling; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 771); s = (sib) ? s.concat(sib._subscribers) : s.concat(); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 772); a = (sib) ? a.concat(sib._afters) : a.concat(); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 774); return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "applyConfig", 784); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 785); mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_on", 801); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 804); var s = new Y.Subscriber(fn, context, args, when); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 806); if (this.fireOnce && this.fired) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 807); if (this.async) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 808); setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 810); this._notify(s, this.firedWith); } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 814); if (when == AFTER) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 815); this._afters.push(s); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 817); this._subscribers.push(s); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 820); if (this._kds) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 821); if (when == AFTER) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 822); this.afters[s.id] = s; } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 824); this.subscribers[s.id] = s; } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 828); return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "subscribe", 838); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 839); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 840); return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "on", 852); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 853); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 855); if (this.monitored && this.host) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 856); this.host._monitor('attach', this, { args: arguments }); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 860); return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "after", 874); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 875); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 876); return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 887); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 889); if (fn && fn.detach) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 890); return fn.detach(); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 893); var i, s, found = 0, subs = this._subscribers, afters = this._afters; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 898); for (i = subs.length; i >= 0; i--) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 899); s = subs[i]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 900); if (s && (!fn || fn === s.fn)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 901); this._delete(s, subs, i); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 902); found++; } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 906); for (i = afters.length; i >= 0; i--) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 907); s = afters[i]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 908); if (s && (!fn || fn === s.fn)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 909); this._delete(s, afters, i); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 910); found++; } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 914); return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribe", 926); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 927); return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_notify", 937); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 940); var ret; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 942); ret = s.notify(args, this); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 944); if (false === ret || this.stopped > 1) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 945); return false; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 948); return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fire", 977); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 978); if (this.fireOnce && this.fired) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 979); return true; } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 982); var args = nativeSlice.call(arguments, 0); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 987); this.fired = true; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 989); if (this.fireOnce) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 990); this.firedWith = args; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 993); if (this.emitFacade) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 994); return this.fireComplex(args); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 996); return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fireSimple", 1009); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1010); this.stopped = 0; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1011); this.prevented = 0; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1012); if (this.hasSubs()) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1013); var subs = this.getSubs(); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1014); this._procSubs(subs[0], args); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1015); this._procSubs(subs[1], args); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1017); this._broadcast(args); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1018); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fireComplex", 1022); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1023); args[0] = args[0] || {}; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1024); return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_procSubs", 1039); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1040); var s, i, l; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1042); for (i = 0, l = subs.length; i < l; i++) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1043); s = subs[i]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1044); if (s && s.fn) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1045); if (false === this._notify(s, args, ef)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1046); this.stopped = 2; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1048); if (this.stopped == 2) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1049); return false; } } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1054); return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_broadcast", 1065); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1066); if (!this.stopped && this.broadcast) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1068); var a = args.concat(); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1069); a.unshift(this.type); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1071); if (this.host !== Y) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1072); Y.fire.apply(Y, a); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1075); if (this.broadcast == 2) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1076); Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribeAll", 1087); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1088); return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detachAll", 1096); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1097); return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_delete", 1110); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1111); var when = s._when; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1113); if (!subs) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1114); subs = (when === AFTER) ? this._afters : this._subscribers; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1115); i = YArray.indexOf(subs, s, 0); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1118); if (s && subs[i] === s) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1119); subs.splice(i, 1); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1122); if (this._kds) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1123); if (when === AFTER) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1124); delete this.afters[s.id]; } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1126); delete this.subscribers[s.id]; } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1130); if (this.monitored && this.host) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1131); this.host._monitor('detach', this, { ce: this, sub: s }); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1137); if (s) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1138); s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1151); Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "Subscriber", 1151); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1159); this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1166); this.context = context; /** * Unique subscriber id * @property id * @type String */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1173); this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1180); this.args = args; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1182); this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1199); Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_notify", 1202); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1203); if (this.deleted && !this.postponed) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1204); if (this.postponed) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1205); delete this.fn; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1206); delete this.context; } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1208); delete this.postponed; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1209); return null; } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1212); var a = this.args, ret; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1213); switch (ce.signature) { case 0: _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1215); ret = this.fn.call(c, ce.type, args, c); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1216); break; case 1: _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1218); ret = this.fn.call(c, args[0] || null, c); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1219); break; default: _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1221); if (a || args) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1222); args = args || []; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1223); a = (a) ? args.concat(a) : args; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1224); ret = this.fn.apply(c, a); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1226); ret = this.fn.call(c); } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1230); if (this.once) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1231); ce._delete(this); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1234); return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "notify", 1243); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1244); var c = this.context, ret = true; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1247); if (!c) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1248); c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1252); if (Y.config && Y.config.throwFail) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1253); ret = this._notify(c, args, ce); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1255); try { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1256); ret = this._notify(c, args, ce); } catch (e) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1258); Y.error(this + ' failed: ' + e.message, e); } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1262); return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "contains", 1275); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1276); if (context) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1277); return ((this.fn == fn) && this.context == context); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1279); return (this.fn == fn); } }, valueOf : function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "valueOf", 1283); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1284); return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1295); Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "EventHandle", 1295); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1303); this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1311); this.sub = sub; }; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1314); Y.EventHandle.prototype = { batch: function(f, c) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "batch", 1315); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1316); f.call(c || this, this); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1317); if (Y.Lang.isArray(this.evt)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1318); Y.Array.each(this.evt, function(h) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 2)", 1318); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1319); h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 1329); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1330); var evt = this.evt, detached = 0, i; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1331); if (evt) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1332); if (Y.Lang.isArray(evt)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1333); for (i = 0; i < evt.length; i++) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1334); detached += evt[i].detach(); } } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1337); evt._delete(this.sub); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1338); detached = 1; } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1343); return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "monitor", 1354); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1355); return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1383); var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 3)", 1389); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1390); return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 4)", 1400); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1402); if (!pre || (typeof type !== "string") || type.indexOf(PREFIX_DELIMITER) > -1) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1403); return type; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1406); return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 5)", 1416); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1418); var t = type, detachcategory, after, i; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1420); if (!L.isString(t)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1421); return t; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1424); i = t.indexOf(AFTER_PREFIX); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1426); if (i > -1) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1427); after = true; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1428); t = t.substr(AFTER_PREFIX.length); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1431); i = t.indexOf(CATEGORY_DELIMITER); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1433); if (i > -1) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1434); detachcategory = t.substr(0, (i)); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1435); t = t.substr(i+1); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1436); if (t == '*') { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1437); t = null; } } // detach category, full type with instance prefix, is this an after listener, short type _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1442); return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "ET", 1445); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1448); var o = (L.isObject(opts)) ? opts : {}; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1450); this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1479); ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "once", 1494); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1495); var handle = this.on.apply(this, arguments); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1496); handle.batch(function(hand) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 6)", 1496); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1497); if (hand.sub) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1498); hand.sub.once = true; } }); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1501); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "onceAfter", 1516); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1517); var handle = this.after.apply(this, arguments); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1518); handle.batch(function(hand) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 7)", 1518); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1519); if (hand.sub) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1520); hand.sub.once = true; } }); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1523); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "parseType", 1542); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1543); return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "on", 1575); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1577); var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1583); this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1589); if (L.isObject(type)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1591); if (L.isFunction(type)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1592); return Y.Do.before.apply(Y.Do, arguments); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1595); f = fn; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1596); c = context; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1597); args = nativeSlice.call(arguments, 0); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1598); ret = []; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1600); if (L.isArray(type)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1601); isArr = true; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1604); after = type._after; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1605); delete type._after; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1607); Y.each(type, function(v, k) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 8)", 1607); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1609); if (L.isObject(v)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1610); f = v.fn || ((L.isFunction(v)) ? v : f); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1611); c = v.context || c; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1614); var nv = (after) ? AFTER_PREFIX : ''; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1616); args[0] = nv + ((isArr) ? v : k); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1617); args[1] = f; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1618); args[2] = c; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1620); ret.push(this.on.apply(this, args)); }, this); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1624); return (yuievt.chain) ? this : new Y.EventHandle(ret); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1627); detachcategory = parts[0]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1628); after = parts[2]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1629); shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1632); if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1633); args = nativeSlice.call(arguments, 0); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1634); args.splice(2, 0, Node.getDOMNode(this)); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1635); return Y.on.apply(Y, args); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1638); type = parts[1]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1640); if (Y.instanceOf(this, YUI)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1642); adapt = Y.Env.evt.plugins[type]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1643); args = nativeSlice.call(arguments, 0); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1644); args[0] = shorttype; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1646); if (Node) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1647); n = args[2]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1649); if (Y.instanceOf(n, Y.NodeList)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1650); n = Y.NodeList.getDOMNodes(n); } else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1651); if (Y.instanceOf(n, Node)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1652); n = Node.getDOMNode(n); }} _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1655); domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1658); if (domevent) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1659); args[2] = n; } } // check for the existance of an event adaptor _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1664); if (adapt) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1665); handle = adapt.on.apply(Y, args); } else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1666); if ((!type) || domevent) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1667); handle = Y.Event._attach(args); }} } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1672); if (!handle) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1673); ce = yuievt.events[type] || this.publish(type); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1674); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1677); if (detachcategory) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1678); store[detachcategory] = store[detachcategory] || {}; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1679); store[detachcategory][type] = store[detachcategory][type] || []; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1680); store[detachcategory][type].push(handle); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1683); return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "subscribe", 1692); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1693); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detach", 1712); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1713); var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1717); if (!type && (this !== Y)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1718); for (i in evts) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1719); if (evts.hasOwnProperty(i)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1720); evts[i].detach(fn, context); } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1723); if (isNode) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1724); Y.Event.purgeElement(Node.getDOMNode(this)); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1727); return this; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1730); var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "keyDetacher", 1736); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1737); var handles = lcat[ltype], ce, i; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1738); if (handles) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1739); for (i = handles.length - 1; i >= 0; --i) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1740); ce = handles[i].evt; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1741); if (ce.host === host || ce.el === host) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1742); handles[i].detach(); } } } }; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1748); if (detachcategory) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1750); cat = store[detachcategory]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1751); type = parts[1]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1752); detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1754); if (cat) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1755); if (type) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1756); keyDetacher(cat, type, detachhost); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1758); for (i in cat) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1759); if (cat.hasOwnProperty(i)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1760); keyDetacher(cat, i, detachhost); } } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1765); return this; } // If this is an event handle, use it to detach } else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1769); if (L.isObject(type) && type.detach) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1770); type.detach(); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1771); return this; // extra redirection so we catch adaptor events too. take a look at this. } else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1773); if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1774); args = nativeSlice.call(arguments, 0); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1775); args[2] = Node.getDOMNode(this); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1776); Y.detach.apply(Y, args); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1777); return this; }}} _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1780); adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1783); if (Y.instanceOf(this, YUI)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1784); args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1786); if (adapt && adapt.detach) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1787); adapt.detach.apply(Y, args); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1788); return this; // DOM event fork } else {_yuitest_coverline("build/event-custom-base/event-custom-base.js", 1790); if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1791); args[0] = type; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1792); Y.Event.detach.apply(Y.Event, args); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1793); return this; }} } // ce = evts[type]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1798); ce = evts[parts[1]]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1799); if (ce) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1800); ce.detach(fn, context); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1803); return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribe", 1811); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1812); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "detachAll", 1822); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1823); return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "unsubscribeAll", 1834); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1835); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "publish", 1904); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1905); var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1909); if (L.isObject(type)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1910); ret = {}; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1911); Y.each(type, function(v, k) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "(anonymous 9)", 1911); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1912); ret[k] = this.publish(k, v || opts); }, this); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1915); return ret; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1918); type = (pre) ? _getType(type, pre) : type; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1920); events = edata.events; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1921); ce = events[type]; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1923); this._monitor('publish', type, { args: arguments }); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1927); if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1929); if (opts) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1930); ce.applyConfig(opts, true); } } else { // TODO: Lazy publish goes here. _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1934); defaults = edata.defaults; // apply defaults _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1937); ce = new Y.CustomEvent(type, defaults); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1938); if (opts) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1939); ce.applyConfig(opts, true); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1942); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1951); return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "_monitor", 1971); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1972); var monitorevt, ce, type; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1974); if (eventType) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1975); if (typeof eventType === "string") { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1976); type = eventType; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1977); ce = this.getEvent(eventType, true); } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1979); ce = eventType; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1980); type = eventType.type; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1983); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1984); monitorevt = type + '_' + what; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1985); o.monitored = what; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 1986); this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "fire", 2018); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2020); var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), yuievt = this._yuievt, pre = yuievt.config.prefix, ce, ret, ce2, args = (typeIncluded) ? nativeSlice.call(arguments, 1) : arguments; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2028); t = (pre) ? _getType(t, pre) : t; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2030); ce = this.getEvent(t, true); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2031); ce2 = this.getSibling(t, ce); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2033); if (ce2 && !ce) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2034); ce = this.publish(t); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2037); this._monitor('fire', (ce || t), { args: args }); // this event has not been published or subscribed to _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2042); if (!ce) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2043); if (yuievt.hasTargets) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2044); return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2048); ret = true; } else { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2050); ce.sibling = ce2; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2051); ret = ce.fire.apply(ce, args); } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2054); return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "getSibling", 2057); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2058); var ce2; // delegate to *:type events if there are subscribers _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2060); if (type.indexOf(PREFIX_DELIMITER) > -1) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2061); type = _wildType(type); // console.log(type); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2063); ce2 = this.getEvent(type, true); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2064); if (ce2) { // console.log("GOT ONE: " + type); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2066); ce2.applyConfig(ce); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2067); ce2.bubbles = false; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2068); ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2073); return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "getEvent", 2084); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2085); var pre, e; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2086); if (!prefixed) { _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2087); pre = this._yuievt.config.prefix; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2088); type = (pre) ? _getType(type, pre) : type; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2090); e = this._yuievt.events; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2091); return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "after", 2108); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2110); var a = nativeSlice.call(arguments, 0); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2112); switch (L.type(type)) { case 'function': _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2114); return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2121); a[0]._after = true; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2122); break; default: _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2124); a[0] = AFTER_PREFIX + type; } _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2127); return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { _yuitest_coverfunc("build/event-custom-base/event-custom-base.js", "before", 2146); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2147); return this.on.apply(this, arguments); } }; _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2152); Y.EventTarget = ET; // make Y an event target _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2155); Y.mix(Y, ET.prototype); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2156); ET.call(Y, { bubbles: false }); _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2158); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ _yuitest_coverline("build/event-custom-base/event-custom-base.js", 2168); Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]});
app/routes/home/__tests__/home.component.spec.js
dleszcz/ladder
import React from 'react'; import { expect } from 'chai'; import { shallow } from 'enzyme'; import { spy } from 'sinon'; import { FormattedMessage } from 'react-intl'; import Helmet from 'react-helmet'; import { Home } from '../home.component'; import messages from '../home.messages'; import { MaintainerList } from '../maintainerList/maintainerList.component'; import { LanguageSelector } from '../languageSelector/languageSelector.component'; describe('Home: Component', () => { const defaultProps = { fetchMaintainers: () => {}, items: [1, 2, 3], language: 'en', setLanguage: () => {}, router: {}, }; const component = (props) => ( <Home {...defaultProps} {...props} /> ); it('should render Home root', () => { const wrapper = shallow(component({})); expect(wrapper.find('.home')).to.have.length(1); }); it('should render <Helmet/>', () => { const wrapper = shallow(component({})); expect(wrapper.find(Helmet)).to.have.length(1); }); it('should pass title prop to <Helmet/>', () => { const wrapper = shallow(component({})); const helmetProps = wrapper.find(Helmet).props(); expect(helmetProps.title).to.be.a('string'); }); it('should render .home__title', () => { const wrapper = shallow(component({})); expect(wrapper.find('.home__title')).to.have.length(1); }); it('should render welcome message inside .home__title', () => { const wrapper = shallow(component({})); expect(wrapper.find('.home__title').find(FormattedMessage).prop('id')).to.equal(messages.welcome.id); }); it('should render <MaintainerList />', () => { const wrapper = shallow(component({})); expect(wrapper.find(MaintainerList)).to.have.length(1); }); it('should pass items prop to <MaintainerList />', () => { const wrapper = shallow(component({})); expect(wrapper.find(MaintainerList).prop('items')).to.equal(defaultProps.items); }); it('should render <LanguageSelector />', () => { const wrapper = shallow(component({})); expect(wrapper.find(LanguageSelector)).to.have.length(1); }); it('should pass props to <LanguageSelector />', () => { const setLanguage = spy(); const wrapper = shallow(component({ setLanguage })); const languageSelectorProps = wrapper.find(LanguageSelector).props(); expect(languageSelectorProps.language).to.equal(defaultProps.language); expect(languageSelectorProps.router).to.equal(defaultProps.router); languageSelectorProps.setLanguage(); expect(setLanguage.calledOnce).to.be.true; }); it('should dispatch fetchMaintainers action on mount', () => { const fetchMaintainers = spy(); shallow(component({ fetchMaintainers })); expect(fetchMaintainers.firstCall.args[0]).to.equal(defaultProps.language); }); it('should dispatch fetchMaintainers action on language change', () => { const fetchMaintainers = spy(); const newLanguage = 'de'; const wrapper = shallow(component({ fetchMaintainers, language: 'en' })); fetchMaintainers.reset(); wrapper.setProps({ language: newLanguage }); expect(fetchMaintainers.firstCall.args[0]).to.equal(newLanguage); }); });
src/svg-icons/hardware/scanner.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareScanner = (props) => ( <SvgIcon {...props}> <path d="M19.8 10.7L4.2 5l-.7 1.9L17.6 12H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-5.5c0-.8-.5-1.6-1.2-1.8zM7 17H5v-2h2v2zm12 0H9v-2h10v2z"/> </SvgIcon> ); HardwareScanner = pure(HardwareScanner); HardwareScanner.displayName = 'HardwareScanner'; HardwareScanner.muiName = 'SvgIcon'; export default HardwareScanner;
src/containers/__tests__/views/card-view-test.js
shojil/bifapp
/** * Test to check if the component renders correctly */ /* global it expect */ import 'react-native'; import React from 'react'; import renderer from 'react-test-renderer'; import CardView from '@containers/recipes/Card/CardView'; it('CardView renders correctly', () => { const tree = renderer.create( <CardView image={'http://placehold.it/300x100'} title={'A Cake'} content={'It\'s so delicious!'} />, ).toJSON(); expect(tree).toMatchSnapshot(); });
ajax/libs/material-ui/5.0.0-alpha.14/modern/internal/svg-icons/ArrowDropDown.min.js
cdnjs/cdnjs
import*as React from"react";import createSvgIcon from"../../utils/createSvgIcon";export default createSvgIcon(React.createElement("path",{d:"M7 10l5 5 5-5z"}),"ArrowDropDown");
ReactNativeLIFE/Pages/JYMine.js
YotrolZ/React-Native-LIFE
/** * Sample React Native App * https://github.com/facebook/react-native * @flow * * 我的页面 * */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, ScrollView } from 'react-native'; export default class Mine extends Component { render() { return ( <View style={styles.container}> <Text> 自我页面 </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, });
src/svg-icons/device/access-alarm.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAccessAlarm = (props) => ( <SvgIcon {...props}> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </SvgIcon> ); DeviceAccessAlarm = pure(DeviceAccessAlarm); DeviceAccessAlarm.displayName = 'DeviceAccessAlarm'; DeviceAccessAlarm.muiName = 'SvgIcon'; export default DeviceAccessAlarm;
src/js/pages/Root.js
ilken/ChosenPokemons
import React from 'react'; import Layout from '../components/Layout.js'; import { Provider } from 'react-redux'; export default class Root extends React.Component { render () { const { store } = this.props; return ( <Provider store={store}> <Layout/> </Provider> ); } }
src/js/components/App.js
nikdelig/react-redux-sass-starter-kit
import React from 'react'; const App = () => ( <div> <p>Its working!</p> </div> ); export default App;
ajax/libs/knockout-validation/2.0.1/knockout.validation.js
NMastracchio/cdnjs
/*============================================================================= Author: Eric M. Barnard - @ericmbarnard License: MIT (http://opensource.org/licenses/mit-license.php) Description: Validation Library for KnockoutJS Version: 2.0.1 =============================================================================== */ /*globals require: false, exports: false, define: false, ko: false */ (function (factory) { // Module systems magic dance. if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { // CommonJS or Node: hard-coded dependency on "knockout" factory(require("knockout"), exports); } else if (typeof define === "function" && define["amd"]) { // AMD anonymous module with hard-coded dependency on "knockout" define(["knockout", "exports"], factory); } else { // <script> tag: use the global `ko` object, attaching a `mapping` property factory(ko, ko.validation = {}); } }(function ( ko, exports ) { if (typeof (ko) === 'undefined') { throw new Error('Knockout is required, please ensure it is loaded before loading this validation plug-in'); } // create our namespace object ko.validation = exports; var kv = ko.validation, koUtils = ko.utils, unwrap = koUtils.unwrapObservable, forEach = koUtils.arrayForEach, extend = koUtils.extend; ;/*global ko: false*/ var defaults = { registerExtenders: true, messagesOnModified: true, errorsAsTitle: true, // enables/disables showing of errors as title attribute of the target element. errorsAsTitleOnModified: false, // shows the error when hovering the input field (decorateElement must be true) messageTemplate: null, insertMessages: true, // automatically inserts validation messages as <span></span> parseInputAttributes: false, // parses the HTML5 validation attribute from a form element and adds that to the object writeInputAttributes: false, // adds HTML5 input validation attributes to form elements that ko observable's are bound to decorateInputElement: false, // false to keep backward compatibility decorateElementOnModified: true,// true to keep backward compatibility errorClass: null, // single class for error message and element errorElementClass: 'validationElement', // class to decorate error element errorMessageClass: 'validationMessage', // class to decorate error message allowHtmlMessages: false, // allows HTML in validation messages grouping: { deep: false, //by default grouping is shallow observable: true, //and using observables live: false //react to changes to observableArrays if observable === true }, validate: { // throttle: 10 } }; // make a copy so we can use 'reset' later var configuration = extend({}, defaults); configuration.html5Attributes = ['required', 'pattern', 'min', 'max', 'step']; configuration.html5InputTypes = ['email', 'number', 'date']; configuration.reset = function () { extend(configuration, defaults); }; kv.configuration = configuration; ;kv.utils = (function () { var seedId = new Date().getTime(); var domData = {}; //hash of data objects that we reference from dom elements var domDataKey = '__ko_validation__'; return { isArray: function (o) { return o.isArray || Object.prototype.toString.call(o) === '[object Array]'; }, isObject: function (o) { return o !== null && typeof o === 'object'; }, isNumber: function(o) { return !isNaN(o); }, isObservableArray: function(instance) { return !!instance && typeof instance["remove"] === "function" && typeof instance["removeAll"] === "function" && typeof instance["destroy"] === "function" && typeof instance["destroyAll"] === "function" && typeof instance["indexOf"] === "function" && typeof instance["replace"] === "function"; }, values: function (o) { var r = []; for (var i in o) { if (o.hasOwnProperty(i)) { r.push(o[i]); } } return r; }, getValue: function (o) { return (typeof o === 'function' ? o() : o); }, hasAttribute: function (node, attr) { return node.getAttribute(attr) !== null; }, getAttribute: function (element, attr) { return element.getAttribute(attr); }, setAttribute: function (element, attr, value) { return element.setAttribute(attr, value); }, isValidatable: function (o) { return !!(o && o.rules && o.isValid && o.isModified); }, insertAfter: function (node, newNode) { node.parentNode.insertBefore(newNode, node.nextSibling); }, newId: function () { return seedId += 1; }, getConfigOptions: function (element) { var options = kv.utils.contextFor(element); return options || kv.configuration; }, setDomData: function (node, data) { var key = node[domDataKey]; if (!key) { node[domDataKey] = key = kv.utils.newId(); } domData[key] = data; }, getDomData: function (node) { var key = node[domDataKey]; if (!key) { return undefined; } return domData[key]; }, contextFor: function (node) { switch (node.nodeType) { case 1: case 8: var context = kv.utils.getDomData(node); if (context) { return context; } if (node.parentNode) { return kv.utils.contextFor(node.parentNode); } break; } return undefined; }, isEmptyVal: function (val) { if (val === undefined) { return true; } if (val === null) { return true; } if (val === "") { return true; } }, getOriginalElementTitle: function (element) { var savedOriginalTitle = kv.utils.getAttribute(element, 'data-orig-title'), currentTitle = element.title, hasSavedOriginalTitle = kv.utils.hasAttribute(element, 'data-orig-title'); return hasSavedOriginalTitle ? savedOriginalTitle : currentTitle; }, async: function (expr) { if (window.setImmediate) { window.setImmediate(expr); } else { window.setTimeout(expr, 0); } }, forEach: function (object, callback) { if (kv.utils.isArray(object)) { return forEach(object, callback); } for (var prop in object) { if (object.hasOwnProperty(prop)) { callback(object[prop], prop); } } } }; }());;var api = (function () { var isInitialized = 0, configuration = kv.configuration, utils = kv.utils; function cleanUpSubscriptions(context) { forEach(context.subscriptions, function (subscription) { subscription.dispose(); }); context.subscriptions = []; } function dispose(context) { if (context.options.deep) { forEach(context.flagged, function (obj) { delete obj.__kv_traversed; }); context.flagged.length = 0; } if (!context.options.live) { cleanUpSubscriptions(context); } } function runTraversal(obj, context) { context.validatables = []; cleanUpSubscriptions(context); traverseGraph(obj, context); dispose(context); } function traverseGraph(obj, context, level) { var objValues = [], val = obj.peek ? obj.peek() : obj; if (obj.__kv_traversed === true) { return; } if (context.options.deep) { obj.__kv_traversed = true; context.flagged.push(obj); } //default level value depends on deep option. level = (level !== undefined ? level : context.options.deep ? 1 : -1); // if object is observable then add it to the list if (ko.isObservable(obj)) { // ensure it's validatable but don't extend validatedObservable because it // would overwrite isValid property. if (!obj.errors && !utils.isValidatable(obj)) { obj.extend({ validatable: true }); } context.validatables.push(obj); if (context.options.live && utils.isObservableArray(obj)) { context.subscriptions.push(obj.subscribe(function () { context.graphMonitor.valueHasMutated(); })); } } //get list of values either from array or object but ignore non-objects // and destroyed objects if (val && !val._destroy) { if (utils.isArray(val)) { objValues = val; } else if (utils.isObject(val)) { objValues = utils.values(val); } } //process recursively if it is deep grouping if (level !== 0) { utils.forEach(objValues, function (observable) { //but not falsy things and not HTML Elements if (observable && !observable.nodeType && (!ko.isComputed(observable) || observable.rules)) { traverseGraph(observable, context, level + 1); } }); } } function collectErrors(array) { var errors = []; forEach(array, function (observable) { // Do not collect validatedObservable errors if (utils.isValidatable(observable) && !observable.isValid()) { // Use peek because we don't want a dependency for 'error' property because it // changes before 'isValid' does. (Issue #99) errors.push(observable.error.peek()); } }); return errors; } return { //Call this on startup //any config can be overridden with the passed in options init: function (options, force) { //done run this multiple times if we don't really want to if (isInitialized > 0 && !force) { return; } //because we will be accessing options properties it has to be an object at least options = options || {}; //if specific error classes are not provided then apply generic errorClass //it has to be done on option so that options.errorClass can override default //errorElementClass and errorMessage class but not those provided in options options.errorElementClass = options.errorElementClass || options.errorClass || configuration.errorElementClass; options.errorMessageClass = options.errorMessageClass || options.errorClass || configuration.errorMessageClass; extend(configuration, options); if (configuration.registerExtenders) { kv.registerExtenders(); } isInitialized = 1; }, // resets the config back to its original state reset: kv.configuration.reset, // recursively walks a viewModel and creates an object that // provides validation information for the entire viewModel // obj -> the viewModel to walk // options -> { // deep: false, // if true, will walk past the first level of viewModel properties // observable: false // if true, returns a computed observable indicating if the viewModel is valid // } group: function group(obj, options) { // array of observables or viewModel options = extend(extend({}, configuration.grouping), options); var context = { options: options, graphMonitor: ko.observable(), flagged: [], subscriptions: [], validatables: [] }; var result = null; //if using observables then traverse structure once and add observables if (options.observable) { result = ko.computed(function () { context.graphMonitor(); //register dependency runTraversal(obj, context); return collectErrors(context.validatables); }); } else { //if not using observables then every call to error() should traverse the structure result = function () { runTraversal(obj, context); return collectErrors(context.validatables); }; } result.showAllMessages = function (show) { // thanks @heliosPortal if (show === undefined) {//default to true show = true; } result.forEach(function (observable) { if (utils.isValidatable(observable)) { observable.isModified(show); } }); }; result.isAnyMessageShown = function () { var invalidAndModifiedPresent; invalidAndModifiedPresent = !!result.find(function (observable) { return utils.isValidatable(observable) && !observable.isValid() && observable.isModified(); }); return invalidAndModifiedPresent; }; result.filter = function(predicate) { predicate = predicate || function () { return true; }; // ensure we have latest changes result(); return koUtils.arrayFilter(context.validatables, predicate); }; result.find = function(predicate) { predicate = predicate || function () { return true; }; // ensure we have latest changes result(); return koUtils.arrayFirst(context.validatables, predicate); }; result.forEach = function(callback) { callback = callback || function () { }; // ensure we have latest changes result(); forEach(context.validatables, callback); }; result.map = function(mapping) { mapping = mapping || function (item) { return item; }; // ensure we have latest changes result(); return koUtils.arrayMap(context.validatables, mapping); }; /** * @private You should not rely on this method being here. * It's a private method and it may change in the future. * * @description Updates the validated object and collects errors from it. */ result._updateState = function(newValue) { if (!utils.isObject(newValue)) { throw new Error('An object is required.'); } obj = newValue; if (options.observable) { context.graphMonitor.valueHasMutated(); } else { runTraversal(newValue, context); return collectErrors(context.validatables); } }; return result; }, formatMessage: function (message, params, observable) { if (utils.isObject(params) && params.typeAttr) { params = params.value; } if (typeof (message) === 'function') { return message(params, observable); } var replacements = unwrap(params) || []; if (!utils.isArray(replacements)) { replacements = [replacements]; } return message.replace(/{(\d+)}/gi, function(match, index) { if (typeof replacements[index] !== 'undefined') { return replacements[index]; } return match; }); }, // addRule: // This takes in a ko.observable and a Rule Context - which is just a rule name and params to supply to the validator // ie: kv.addRule(myObservable, { // rule: 'required', // params: true // }); // addRule: function (observable, rule) { observable.extend({ validatable: true }); var hasRule = !!koUtils.arrayFirst(observable.rules(), function(item) { return item.rule && item.rule === rule.rule; }); if (!hasRule) { //push a Rule Context to the observables local array of Rule Contexts observable.rules.push(rule); } return observable; }, // addAnonymousRule: // Anonymous Rules essentially have all the properties of a Rule, but are only specific for a certain property // and developers typically are wanting to add them on the fly or not register a rule with the 'kv.rules' object // // Example: // var test = ko.observable('something').extend{( // validation: { // validator: function(val, someOtherVal){ // return true; // }, // message: "Something must be really wrong!', // params: true // } // )}; addAnonymousRule: function (observable, ruleObj) { if (ruleObj['message'] === undefined) { ruleObj['message'] = 'Error'; } //make sure onlyIf is honoured if (ruleObj.onlyIf) { ruleObj.condition = ruleObj.onlyIf; } //add the anonymous rule to the observable kv.addRule(observable, ruleObj); }, addExtender: function (ruleName) { ko.extenders[ruleName] = function (observable, params) { //params can come in a few flavors // 1. Just the params to be passed to the validator // 2. An object containing the Message to be used and the Params to pass to the validator // 3. A condition when the validation rule to be applied // // Example: // var test = ko.observable(3).extend({ // max: { // message: 'This special field has a Max of {0}', // params: 2, // onlyIf: function() { // return specialField.IsVisible(); // } // } // )}; // if (params && (params.message || params.onlyIf)) { //if it has a message or condition object, then its an object literal to use return kv.addRule(observable, { rule: ruleName, message: params.message, params: utils.isEmptyVal(params.params) ? true : params.params, condition: params.onlyIf }); } else { return kv.addRule(observable, { rule: ruleName, params: params }); } }; }, // loops through all kv.rules and adds them as extenders to // ko.extenders registerExtenders: function () { // root extenders optional, use 'validation' extender if would cause conflicts if (configuration.registerExtenders) { for (var ruleName in kv.rules) { if (kv.rules.hasOwnProperty(ruleName)) { if (!ko.extenders[ruleName]) { kv.addExtender(ruleName); } } } } }, //creates a span next to the @element with the specified error class insertValidationMessage: function (element) { var span = document.createElement('SPAN'); span.className = utils.getConfigOptions(element).errorMessageClass; utils.insertAfter(element, span); return span; }, // if html-5 validation attributes have been specified, this parses // the attributes on @element parseInputValidationAttributes: function (element, valueAccessor) { forEach(kv.configuration.html5Attributes, function (attr) { if (utils.hasAttribute(element, attr)) { var params = element.getAttribute(attr) || true; if (attr === 'min' || attr === 'max') { // If we're validating based on the min and max attributes, we'll // need to know what the 'type' attribute is set to var typeAttr = element.getAttribute('type'); if (typeof typeAttr === "undefined" || !typeAttr) { // From http://www.w3.org/TR/html-markup/input: // An input element with no type attribute specified represents the // same thing as an input element with its type attribute set to "text". typeAttr = "text"; } params = {typeAttr: typeAttr, value: params}; } kv.addRule(valueAccessor(), { rule: attr, params: params }); } }); var currentType = element.getAttribute('type'); forEach(kv.configuration.html5InputTypes, function (type) { if (type === currentType) { kv.addRule(valueAccessor(), { rule: (type === 'date') ? 'dateISO' : type, params: true }); } }); }, // writes html5 validation attributes on the element passed in writeInputValidationAttributes: function (element, valueAccessor) { var observable = valueAccessor(); if (!observable || !observable.rules) { return; } var contexts = observable.rules(); // observable array // loop through the attributes and add the information needed forEach(kv.configuration.html5Attributes, function (attr) { var ctx = koUtils.arrayFirst(contexts, function (ctx) { return ctx.rule && ctx.rule.toLowerCase() === attr.toLowerCase(); }); if (!ctx) { return; } // we have a rule matching a validation attribute at this point // so lets add it to the element along with the params ko.computed({ read: function() { var params = ko.unwrap(ctx.params); // we have to do some special things for the pattern validation if (ctx.rule === "pattern" && params instanceof RegExp) { // we need the pure string representation of the RegExpr without the //gi stuff params = params.source; } element.setAttribute(attr, params); }, disposeWhenNodeIsRemoved: element }); }); contexts = null; }, //take an existing binding handler and make it cause automatic validations makeBindingHandlerValidatable: function (handlerName) { var init = ko.bindingHandlers[handlerName].init; ko.bindingHandlers[handlerName].init = function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); return ko.bindingHandlers['validationCore'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); }; }, // visit an objects properties and apply validation rules from a definition setRules: function (target, definition) { var setRules = function (target, definition) { if (!target || !definition) { return; } for (var prop in definition) { if (!definition.hasOwnProperty(prop)) { continue; } var ruleDefinitions = definition[prop]; //check the target property exists and has a value if (!target[prop]) { continue; } var targetValue = target[prop], unwrappedTargetValue = unwrap(targetValue), rules = {}, nonRules = {}; for (var rule in ruleDefinitions) { if (!ruleDefinitions.hasOwnProperty(rule)) { continue; } if (kv.rules[rule]) { rules[rule] = ruleDefinitions[rule]; } else { nonRules[rule] = ruleDefinitions[rule]; } } //apply rules if (ko.isObservable(targetValue)) { targetValue.extend(rules); } //then apply child rules //if it's an array, apply rules to all children if (unwrappedTargetValue && utils.isArray(unwrappedTargetValue)) { for (var i = 0; i < unwrappedTargetValue.length; i++) { setRules(unwrappedTargetValue[i], nonRules); } //otherwise, just apply to this property } else { setRules(unwrappedTargetValue, nonRules); } } }; setRules(target, definition); } }; }()); // expose api publicly extend(ko.validation, api); ;//Validation Rules: // You can view and override messages or rules via: // kv.rules[ruleName] // // To implement a custom Rule, simply use this template: // kv.rules['<custom rule name>'] = { // validator: function (val, param) { // <custom logic> // return <true or false>; // }, // message: '<custom validation message>' //optionally you can also use a '{0}' to denote a placeholder that will be replaced with your 'param' // }; // // Example: // kv.rules['mustEqual'] = { // validator: function( val, mustEqualVal ){ // return val === mustEqualVal; // }, // message: 'This field must equal {0}' // }; // kv.rules = {}; kv.rules['required'] = { validator: function (val, required) { var testVal; if (val === undefined || val === null) { return !required; } testVal = val; if (typeof (val) === 'string') { if (String.prototype.trim) { testVal = val.trim(); } else { testVal = val.replace(/^\s+|\s+$/g, ''); } } if (!required) {// if they passed: { required: false }, then don't require this return true; } return ((testVal + '').length > 0); }, message: 'This field is required.' }; function minMaxValidatorFactory(validatorName) { var isMaxValidation = validatorName === "max"; return function (val, options) { if (kv.utils.isEmptyVal(val)) { return true; } var comparisonValue, type; if (options.typeAttr === undefined) { // This validator is being called from javascript rather than // being bound from markup type = "text"; comparisonValue = options; } else { type = options.typeAttr; comparisonValue = options.value; } // From http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-min, // if the value is parseable to a number, then the minimum should be numeric if (!isNaN(comparisonValue) && !(comparisonValue instanceof Date)) { type = "number"; } var regex, valMatches, comparisonValueMatches; switch (type.toLowerCase()) { case "week": regex = /^(\d{4})-W(\d{2})$/; valMatches = val.match(regex); if (valMatches === null) { throw new Error("Invalid value for " + validatorName + " attribute for week input. Should look like " + "'2000-W33' http://www.w3.org/TR/html-markup/input.week.html#input.week.attrs.min"); } comparisonValueMatches = comparisonValue.match(regex); // If no regex matches were found, validation fails if (!comparisonValueMatches) { return false; } if (isMaxValidation) { return (valMatches[1] < comparisonValueMatches[1]) || // older year // same year, older week ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2])); } else { return (valMatches[1] > comparisonValueMatches[1]) || // newer year // same year, newer week ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2])); } break; case "month": regex = /^(\d{4})-(\d{2})$/; valMatches = val.match(regex); if (valMatches === null) { throw new Error("Invalid value for " + validatorName + " attribute for month input. Should look like " + "'2000-03' http://www.w3.org/TR/html-markup/input.month.html#input.month.attrs.min"); } comparisonValueMatches = comparisonValue.match(regex); // If no regex matches were found, validation fails if (!comparisonValueMatches) { return false; } if (isMaxValidation) { return ((valMatches[1] < comparisonValueMatches[1]) || // older year // same year, older month ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] <= comparisonValueMatches[2]))); } else { return (valMatches[1] > comparisonValueMatches[1]) || // newer year // same year, newer month ((valMatches[1] === comparisonValueMatches[1]) && (valMatches[2] >= comparisonValueMatches[2])); } break; case "number": case "range": if (isMaxValidation) { return (!isNaN(val) && parseFloat(val) <= parseFloat(comparisonValue)); } else { return (!isNaN(val) && parseFloat(val) >= parseFloat(comparisonValue)); } break; default: if (isMaxValidation) { return val <= comparisonValue; } else { return val >= comparisonValue; } } }; } kv.rules['min'] = { validator: minMaxValidatorFactory("min"), message: 'Please enter a value greater than or equal to {0}.' }; kv.rules['max'] = { validator: minMaxValidatorFactory("max"), message: 'Please enter a value less than or equal to {0}.' }; kv.rules['minLength'] = { validator: function (val, minLength) { if(kv.utils.isEmptyVal(val)) { return true; } var normalizedVal = kv.utils.isNumber(val) ? ('' + val) : val; return normalizedVal.length >= minLength; }, message: 'Please enter at least {0} characters.' }; kv.rules['maxLength'] = { validator: function (val, maxLength) { if(kv.utils.isEmptyVal(val)) { return true; } var normalizedVal = kv.utils.isNumber(val) ? ('' + val) : val; return normalizedVal.length <= maxLength; }, message: 'Please enter no more than {0} characters.' }; kv.rules['pattern'] = { validator: function (val, regex) { return kv.utils.isEmptyVal(val) || val.toString().match(regex) !== null; }, message: 'Please check this value.' }; kv.rules['step'] = { validator: function (val, step) { // in order to handle steps of .1 & .01 etc.. Modulus won't work // if the value is a decimal, so we have to correct for that if (kv.utils.isEmptyVal(val) || step === 'any') { return true; } var dif = (val * 100) % (step * 100); return Math.abs(dif) < 0.00001 || Math.abs(1 - dif) < 0.00001; }, message: 'The value must increment by {0}.' }; kv.rules['email'] = { validator: function (val, validate) { if (!validate) { return true; } //I think an empty email address is also a valid entry //if one want's to enforce entry it should be done with 'required: true' return kv.utils.isEmptyVal(val) || ( // jquery validate regex - thanks Scott Gonzalez validate && /^((([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.test(val) ); }, message: 'Please enter a proper email address.' }; kv.rules['date'] = { validator: function (value, validate) { if (!validate) { return true; } return kv.utils.isEmptyVal(value) || (validate && !/Invalid|NaN/.test(new Date(value))); }, message: 'Please enter a proper date.' }; kv.rules['dateISO'] = { validator: function (value, validate) { if (!validate) { return true; } return kv.utils.isEmptyVal(value) || (validate && /^\d{4}[-/](?:0?[1-9]|1[012])[-/](?:0?[1-9]|[12][0-9]|3[01])$/.test(value)); }, message: 'Please enter a proper date.' }; kv.rules['number'] = { validator: function (value, validate) { if (!validate) { return true; } return kv.utils.isEmptyVal(value) || (validate && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)); }, message: 'Please enter a number.' }; kv.rules['digit'] = { validator: function (value, validate) { if (!validate) { return true; } return kv.utils.isEmptyVal(value) || (validate && /^\d+$/.test(value)); }, message: 'Please enter a digit.' }; kv.rules['phoneUS'] = { validator: function (phoneNumber, validate) { if (!validate) { return true; } if (kv.utils.isEmptyVal(phoneNumber)) { return true; } // makes it optional, use 'required' rule if it should be required if (typeof (phoneNumber) !== 'string') { return false; } phoneNumber = phoneNumber.replace(/\s+/g, ""); return validate && phoneNumber.length > 9 && phoneNumber.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); }, message: 'Please specify a valid phone number.' }; kv.rules['equal'] = { validator: function (val, params) { var otherValue = params; return val === kv.utils.getValue(otherValue); }, message: 'Values must equal.' }; kv.rules['notEqual'] = { validator: function (val, params) { var otherValue = params; return val !== kv.utils.getValue(otherValue); }, message: 'Please choose another value.' }; //unique in collection // options are: // collection: array or function returning (observable) array // in which the value has to be unique // valueAccessor: function that returns value from an object stored in collection // if it is null the value is compared directly // external: set to true when object you are validating is automatically updating collection kv.rules['unique'] = { validator: function (val, options) { var c = kv.utils.getValue(options.collection), external = kv.utils.getValue(options.externalValue), counter = 0; if (!val || !c) { return true; } koUtils.arrayFilter(c, function (item) { if (val === (options.valueAccessor ? options.valueAccessor(item) : item)) { counter++; } }); // if value is external even 1 same value in collection means the value is not unique return counter < (!!external ? 1 : 2); }, message: 'Please make sure the value is unique.' }; //now register all of these! (function () { kv.registerExtenders(); }()); ;// The core binding handler // this allows us to setup any value binding that internally always // performs the same functionality ko.bindingHandlers['validationCore'] = (function () { return { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var config = kv.utils.getConfigOptions(element); var observable = valueAccessor(); // parse html5 input validation attributes, optional feature if (config.parseInputAttributes) { kv.utils.async(function () { kv.parseInputValidationAttributes(element, valueAccessor); }); } // if requested insert message element and apply bindings if (config.insertMessages && kv.utils.isValidatable(observable)) { // insert the <span></span> var validationMessageElement = kv.insertValidationMessage(element); // if we're told to use a template, make sure that gets rendered if (config.messageTemplate) { ko.renderTemplate(config.messageTemplate, { field: observable }, null, validationMessageElement, 'replaceNode'); } else { ko.applyBindingsToNode(validationMessageElement, { validationMessage: observable }); } } // write the html5 attributes if indicated by the config if (config.writeInputAttributes && kv.utils.isValidatable(observable)) { kv.writeInputValidationAttributes(element, valueAccessor); } // if requested, add binding to decorate element if (config.decorateInputElement && kv.utils.isValidatable(observable)) { ko.applyBindingsToNode(element, { validationElement: observable }); } } }; }()); // override for KO's default 'value', 'checked', 'textInput' and selectedOptions bindings kv.makeBindingHandlerValidatable("value"); kv.makeBindingHandlerValidatable("checked"); if (ko.bindingHandlers.textInput) { kv.makeBindingHandlerValidatable("textInput"); } kv.makeBindingHandlerValidatable("selectedOptions"); ko.bindingHandlers['validationMessage'] = { // individual error message, if modified or post binding update: function (element, valueAccessor) { var obsv = valueAccessor(), config = kv.utils.getConfigOptions(element), val = unwrap(obsv), msg = null, isModified = false, isValid = false; if (obsv === null || typeof obsv === 'undefined') { throw new Error('Cannot bind validationMessage to undefined value. data-bind expression: ' + element.getAttribute('data-bind')); } if (!obsv.isValid || !obsv.isModified) { throw new Error("Observable is not validatable"); } isModified = obsv.isModified(); isValid = obsv.isValid(); var error = null; if (!config.messagesOnModified || isModified) { error = isValid ? null : obsv.error; } var isVisible = !config.messagesOnModified || isModified ? !isValid : false; var isCurrentlyVisible = element.style.display !== "none"; if (config.allowHtmlMessages) { koUtils.setHtml(element, error); } else { ko.bindingHandlers.text.update(element, function () { return error; }); } if (isCurrentlyVisible && !isVisible) { element.style.display = 'none'; } else if (!isCurrentlyVisible && isVisible) { element.style.display = ''; } } }; ko.bindingHandlers['validationElement'] = { update: function (element, valueAccessor, allBindingsAccessor) { var obsv = valueAccessor(), config = kv.utils.getConfigOptions(element), val = unwrap(obsv), msg = null, isModified = false, isValid = false; if (obsv === null || typeof obsv === 'undefined') { throw new Error('Cannot bind validationElement to undefined value. data-bind expression: ' + element.getAttribute('data-bind')); } if (!obsv.isValid || !obsv.isModified) { throw new Error("Observable is not validatable"); } isModified = obsv.isModified(); isValid = obsv.isValid(); // create an evaluator function that will return something like: // css: { validationElement: true } var cssSettingsAccessor = function () { var css = {}; var shouldShow = ((!config.decorateElementOnModified || isModified) ? !isValid : false); // css: { validationElement: false } css[config.errorElementClass] = shouldShow; return css; }; //add or remove class on the element; ko.bindingHandlers.css.update(element, cssSettingsAccessor, allBindingsAccessor); if (!config.errorsAsTitle) { return; } ko.bindingHandlers.attr.update(element, function () { var hasModification = !config.errorsAsTitleOnModified || isModified, title = kv.utils.getOriginalElementTitle(element); if (hasModification && !isValid) { return { title: obsv.error, 'data-orig-title': title }; } else if (!hasModification || isValid) { return { title: title, 'data-orig-title': null }; } }); } }; // ValidationOptions: // This binding handler allows you to override the initial config by setting any of the options for a specific element or context of elements // // Example: // <div data-bind="validationOptions: { insertMessages: true, messageTemplate: 'customTemplate', errorMessageClass: 'mySpecialClass'}"> // <input type="text" data-bind="value: someValue"/> // <input type="text" data-bind="value: someValue2"/> // </div> ko.bindingHandlers['validationOptions'] = (function () { return { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var options = unwrap(valueAccessor()); if (options) { var newConfig = extend({}, kv.configuration); extend(newConfig, options); //store the validation options on the node so we can retrieve it later kv.utils.setDomData(element, newConfig); } } }; }()); ;// Validation Extender: // This is for creating custom validation logic on the fly // Example: // var test = ko.observable('something').extend{( // validation: { // validator: function(val, someOtherVal){ // return true; // }, // message: "Something must be really wrong!', // params: true // } // )}; ko.extenders['validation'] = function (observable, rules) { // allow single rule or array forEach(kv.utils.isArray(rules) ? rules : [rules], function (rule) { // the 'rule' being passed in here has no name to identify a core Rule, // so we add it as an anonymous rule // If the developer is wanting to use a core Rule, but use a different message see the 'addExtender' logic for examples kv.addAnonymousRule(observable, rule); }); return observable; }; //This is the extender that makes a Knockout Observable also 'Validatable' //examples include: // 1. var test = ko.observable('something').extend({validatable: true}); // this will ensure that the Observable object is setup properly to respond to rules // // 2. test.extend({validatable: false}); // this will remove the validation properties from the Observable object should you need to do that. ko.extenders['validatable'] = function (observable, options) { if (!kv.utils.isObject(options)) { options = { enable: options }; } if (!('enable' in options)) { options.enable = true; } if (options.enable && !kv.utils.isValidatable(observable)) { var config = kv.configuration.validate || {}; var validationOptions = { throttleEvaluation : options.throttle || config.throttle }; observable.error = ko.observable(null); // holds the error message, we only need one since we stop processing validators when one is invalid // observable.rules: // ObservableArray of Rule Contexts, where a Rule Context is simply the name of a rule and the params to supply to it // // Rule Context = { rule: '<rule name>', params: '<passed in params>', message: '<Override of default Message>' } observable.rules = ko.observableArray(); //holds the rule Contexts to use as part of validation //in case async validation is occurring observable.isValidating = ko.observable(false); //the true holder of whether the observable is valid or not observable.__valid__ = ko.observable(true); observable.isModified = ko.observable(false); // a semi-protected observable observable.isValid = ko.computed(observable.__valid__); //manually set error state observable.setError = function (error) { var previousError = observable.error.peek(); var previousIsValid = observable.__valid__.peek(); observable.error(error); observable.__valid__(false); if (previousError !== error && !previousIsValid) { // if the observable was not valid before then isValid will not mutate, // hence causing any grouping to not display the latest error. observable.isValid.notifySubscribers(); } }; //manually clear error state observable.clearError = function () { observable.error(null); observable.__valid__(true); return observable; }; //subscribe to changes in the observable var h_change = observable.subscribe(function () { observable.isModified(true); }); // we use a computed here to ensure that anytime a dependency changes, the // validation logic evaluates var h_obsValidationTrigger = ko.computed(extend({ read: function () { var obs = observable(), ruleContexts = observable.rules(); kv.validateObservable(observable); return true; } }, validationOptions)); extend(h_obsValidationTrigger, validationOptions); observable._disposeValidation = function () { //first dispose of the subscriptions observable.isValid.dispose(); observable.rules.removeAll(); if (observable.isModified.getSubscriptionsCount() > 0) { observable.isModified._subscriptions['change'] = []; } if (observable.isValidating.getSubscriptionsCount() > 0) { observable.isValidating._subscriptions['change'] = []; } if (observable.__valid__.getSubscriptionsCount() > 0) { observable.__valid__._subscriptions['change'] = []; } h_change.dispose(); h_obsValidationTrigger.dispose(); delete observable['rules']; delete observable['error']; delete observable['isValid']; delete observable['isValidating']; delete observable['__valid__']; delete observable['isModified']; }; } else if (options.enable === false && observable._disposeValidation) { observable._disposeValidation(); } return observable; }; function validateSync(observable, rule, ctx) { //Execute the validator and see if its valid if (!rule.validator(observable(), (ctx.params === undefined ? true : unwrap(ctx.params)))) { // default param is true, eg. required = true //not valid, so format the error message and stick it in the 'error' variable observable.setError(kv.formatMessage( ctx.message || rule.message, unwrap(ctx.params), observable)); return false; } else { return true; } } function validateAsync(observable, rule, ctx) { observable.isValidating(true); var callBack = function (valObj) { var isValid = false, msg = ''; if (!observable.__valid__()) { // since we're returning early, make sure we turn this off observable.isValidating(false); return; //if its already NOT valid, don't add to that } //we were handed back a complex object if (valObj['message']) { isValid = valObj.isValid; msg = valObj.message; } else { isValid = valObj; } if (!isValid) { //not valid, so format the error message and stick it in the 'error' variable observable.error(kv.formatMessage( msg || ctx.message || rule.message, unwrap(ctx.params), observable)); observable.__valid__(isValid); } // tell it that we're done observable.isValidating(false); }; //fire the validator and hand it the callback rule.validator(observable(), unwrap(ctx.params || true), callBack); } kv.validateObservable = function (observable) { var i = 0, rule, // the rule validator to execute ctx, // the current Rule Context for the loop ruleContexts = observable.rules(), //cache for iterator len = ruleContexts.length; //cache for iterator for (; i < len; i++) { //get the Rule Context info to give to the core Rule ctx = ruleContexts[i]; // checks an 'onlyIf' condition if (ctx.condition && !ctx.condition()) { continue; } //get the core Rule to use for validation rule = ctx.rule ? kv.rules[ctx.rule] : ctx; if (rule['async'] || ctx['async']) { //run async validation validateAsync(observable, rule, ctx); } else { //run normal sync validation if (!validateSync(observable, rule, ctx)) { return false; //break out of the loop } } } //finally if we got this far, make the observable valid again! observable.clearError(); return true; }; ; var _locales = {}; var _currentLocale; kv.defineLocale = function(name, values) { if (name && values) { _locales[name.toLowerCase()] = values; return values; } return null; }; kv.locale = function(name) { if (name) { name = name.toLowerCase(); if (_locales.hasOwnProperty(name)) { kv.localize(_locales[name]); _currentLocale = name; } else { throw new Error('Localization ' + name + ' has not been loaded.'); } } return _currentLocale; }; //quick function to override rule messages kv.localize = function (msgTranslations) { var rules = kv.rules; //loop the properties in the object and assign the msg to the rule for (var ruleName in msgTranslations) { if (rules.hasOwnProperty(ruleName)) { rules[ruleName].message = msgTranslations[ruleName]; } } }; // Populate default locale (this will make en-US.js somewhat redundant) (function() { var localeData = {}; var rules = kv.rules; for (var ruleName in rules) { if (rules.hasOwnProperty(ruleName)) { localeData[ruleName] = rules[ruleName].message; } } kv.defineLocale('en-us', localeData); })(); // No need to invoke locale because the messages are already defined along with the rules for en-US _currentLocale = 'en-us'; ;/** * Possible invocations: * applyBindingsWithValidation(viewModel) * applyBindingsWithValidation(viewModel, options) * applyBindingsWithValidation(viewModel, rootNode) * applyBindingsWithValidation(viewModel, rootNode, options) */ ko.applyBindingsWithValidation = function (viewModel, rootNode, options) { var node = document.body, config; if (rootNode && rootNode.nodeType) { node = rootNode; config = options; } else { config = rootNode; } kv.init(); if (config) { config = extend(extend({}, kv.configuration), config); kv.utils.setDomData(node, config); } ko.applyBindings(viewModel, node); }; //override the original applyBindings so that we can ensure all new rules and what not are correctly registered var origApplyBindings = ko.applyBindings; ko.applyBindings = function (viewModel, rootNode) { kv.init(); origApplyBindings(viewModel, rootNode); }; ko.validatedObservable = function (initialValue, options) { if (!options && !kv.utils.isObject(initialValue)) { return ko.observable(initialValue).extend({ validatable: true }); } var obsv = ko.observable(initialValue); obsv.errors = kv.group(kv.utils.isObject(initialValue) ? initialValue : {}, options); obsv.isValid = ko.observable(obsv.errors().length === 0); if (ko.isObservable(obsv.errors)) { obsv.errors.subscribe(function(errors) { obsv.isValid(errors.length === 0); }); } else { ko.computed(obsv.errors).subscribe(function (errors) { obsv.isValid(errors.length === 0); }); } obsv.subscribe(function(newValue) { if (!kv.utils.isObject(newValue)) { /* * The validation group works on objects. * Since the new value is a primitive (scalar, null or undefined) we need * to create an empty object to pass along. */ newValue = {}; } // Force the group to refresh obsv.errors._updateState(newValue); obsv.isValid(obsv.errors().length === 0); }); return obsv; }; ;}));
React_Router_tutorial/modules/Repo.js
luongthomas/React-Portfolio
import React from 'react'; export default React.createClass({ render() { const { userName, repoName } = this.props.params; return ( <div> <h2>{userName} / {repoName}</h2> </div> ); }, });
ajax/libs/antd/1.5.1/antd.min.js
CyrusSUEN/cdnjs
/*! * antd v1.5.1 * * Copyright 2015-present, Alipay, Inc. * All rights reserved. */ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","react-dom"],t):"object"==typeof exports?exports.antd=t(require("react"),require("react-dom")):e.antd=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var n=t.slice(1),r=e[t[0]];return function(e,t,o){r.apply(this,[e,t,o].concat(n))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,n){e.exports=n(254)},function(t,n){t.exports=e},function(e,t,n){var r,o;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var r=arguments[t];if(r){var o=typeof r;if("string"===o||"number"===o)e.push(r);else if(Array.isArray(r))e.push(n.apply(null,r));else if("object"===o)for(var i in r)a.call(r,i)&&r[i]&&e.push(i)}}return e.join(" ")}var a={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(r=[],o=function(){return n}.apply(t,r),!(void 0!==o&&(e.exports=o)))}()},function(e,t){},function(e,n){e.exports=t},function(e,t,n){"use strict";function r(e,t){t.every(function(e){return"string"==typeof e})&&h(e,t)}function o(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=1,o=t[0],a=t.length;if("function"==typeof o)return o.apply(null,t.slice(1));if("string"==typeof o){for(var i=String(o).replace(d,function(e){if("%%"===e)return"%";if(r>=a)return e;switch(e){case"%s":return String(t[r++]);case"%d":return Number(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch(n){return"[Circular]"}break;default:return e}}),s=t[r];r<a;s=t[++r])i+=" "+s;return i}return o}function a(e){return"string"===e||"url"===e||"hex"===e||"email"===e}function i(e,t){return void 0===e||null===e||(!("array"!==t||!Array.isArray(e)||e.length)||!(!a(t)||"string"!=typeof e||e))}function s(e){return 0===Object.keys(e).length}function l(e,t,n){function r(e){o.push.apply(o,e),a++,a===i&&n(o)}var o=[],a=0,i=e.length;e.forEach(function(e){t(e,r)})}function u(e,t,n){function r(i){if(i.length)return void n(i);var s=o;o+=1,s<a?t(e[s],r):n([])}var o=0,a=e.length;r([])}function c(e){var t=[];return Object.keys(e).forEach(function(n){t.push.apply(t,e[n])}),t}function p(e,t,n,r){if(t.first){var o=c(e);return u(o,n,r)}var a=t.firstFields||[];a===!0&&(a=Object.keys(e));var i=Object.keys(e),s=i.length,p=0,f=[],d=function(e){f.push.apply(f,e),p++,p===s&&r(f)};i.forEach(function(t){var r=e[t];a.indexOf(t)!==-1?u(r,n,d):l(r,n,d)})}function f(e){return function(t){return t&&t.message?(t.field=t.field||e.fullField,t):{message:t,field:t.field||e.fullField}}}Object.defineProperty(t,"__esModule",{value:!0}),t.warning=r,t.format=o,t.isEmptyValue=i,t.isEmptyObject=s,t.asyncMap=p,t.complementError=f;var d=/%[sdj%]/g,h=function(){}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),s=r(i);t["default"]=function(e){var t=e.type,n=e.className,r=void 0===n?"":n,i=o(e,["type","className"]);return r+=" anticon anticon-"+t,s["default"].createElement("i",a({className:r},i))},e.exports=t["default"]},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={required:n(51),whitespace:n(135),type:n(134),range:n(133),"enum":n(131),pattern:n(132)},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(285)},function(e,t,n){"use strict";function r(e){var t=e||p;this.locale=t,this.fields=[],this.time=void 0,this.timezoneOffset=t.timezoneOffset,this.firstDayOfWeek=t.firstDayOfWeek,this.minimalDaysInFirstWeek=t.minimalDaysInFirstWeek,this.fieldsComputed=!1}function o(e,t){return L(e)?S[t]:E[t]}function a(e){return L(e)?366:365}function i(e){var t=e.fields,n=t[h],r=t[y],a=o(n,r),i=t[v];i>a&&e.set(v,a)}function s(e,t){return e-A(e-t,7)}function l(e,t,n){var r=s(t+6,e.firstDayOfWeek),o=r-t;o>=e.minimalDaysInFirstWeek&&(r-=7);var a=n-r;return V(a/7)+1}var u=parseInt,c=n(268),p=n(83),f=n(82);c.mix(r,f),c.mix(r,{Utils:c,defaultLocale:p,isLeapYear:c.isLeapYear,YEAR:1,MONTH:2,DAY_OF_MONTH:3,HOUR_OF_DAY:4,MINUTES:5,SECONDS:6,MILLISECONDS:7,WEEK_OF_YEAR:8,WEEK_OF_MONTH:9,DAY_OF_YEAR:10,DAY_OF_WEEK:11,DAY_OF_WEEK_IN_MONTH:12,AM:0,PM:1});var d=["","Year","Month","DayOfMonth","HourOfDay","Minutes","Seconds","Milliseconds","WeekOfYear","WeekOfMonth","DayOfYear","DayOfWeek","DayOfWeekInMonth"],h=r.YEAR,y=r.MONTH,v=r.DAY_OF_MONTH,m=r.HOUR_OF_DAY,g=r.MINUTES,b=r.SECONDS,P=r.MILLISECONDS,O=r.DAY_OF_WEEK_IN_MONTH,C=r.DAY_OF_YEAR,T=r.DAY_OF_WEEK,w=r.WEEK_OF_MONTH,x=r.WEEK_OF_YEAR,E=[31,28,31,30,31,30,31,31,30,31,30,31],S=[31,29,31,30,31,30,31,31,30,31,30,31],k=1e3,j=60*k,_=60*j,N=24*_,M=7*N,D=719163,A=c.mod,L=c.isLeapYear,V=Math.floor,F=[void 0,1,r.JANUARY,1,0,0,0,0,1,void 0,1,r.SUNDAY,1],I=[void 0,292278994,r.DECEMBER,void 0,23,59,59,999,void 0,void 0,void 0,r.SATURDAY,void 0];r.prototype={constructor:r,isGregorianCalendar:1,isLeapYear:function(){return L(this.getYear())},getLocale:function(){return this.locale},getActualMinimum:function(e){if(void 0!==F[e])return F[e];if(e===w){var t=this.clone();return t.clear(),t.set(this.fields[h],this.fields[y],1),t.get(w)}throw new Error("minimum value not defined!")},getActualMaximum:function(e){if(void 0!==I[e])return I[e];var t=void 0,n=this.fields;switch(e){case v:t=o(n[h],n[y]);break;case x:var i=this.clone();i.clear(),i.set(n[h],r.DECEMBER,31),t=i.get(x),1===t&&(t=52);break;case w:var s=this.clone();s.clear(),s.set(n[h],n[y],o(n[h],n[y])),t=s.get(w);break;case C:t=a(n[h]);break;case O:t=u((o(n[h],n[y])-1)/7)+1}if(void 0===t)throw new Error("maximum value not defined!");return t},isSet:function(e){return void 0!==this.fields[e]},computeFields:function(){var e=this.time,t=this.timezoneOffset*j,n=u(t/N),o=t%N;if(n+=u(e/N),o+=e%N,o>=N)o-=N,n++;else for(;o<0;)o+=N,n--;n+=D;var i=c.getGregorianDateFromFixedDate(n),p=i.year,f=this.fields;if(f[h]=p,f[y]=i.month,f[v]=i.dayOfMonth,f[T]=i.dayOfWeek,0!==o){f[m]=u(o/_);var d=o%_;f[g]=u(d/j),d%=j,f[b]=u(d/k),f[P]=d%k}else f[m]=f[g]=f[b]=f[P]=0;var E=c.getFixedDate(p,r.JANUARY,1),S=n-E+1,M=n-i.dayOfMonth+1;f[C]=S,f[O]=u((i.dayOfMonth-1)/7)+1;var A=l(this,E,n);if(0===A){var L=E-1,V=E-a(p-1);A=l(this,V,L)}else if(A>=52){var F=E+a(p),I=s(F+6,this.firstDayOfWeek),R=I-F;R>=this.minimalDaysInFirstWeek&&n>=I-7&&(A=1)}f[x]=A,f[w]=l(this,M,n),this.fieldsComputed=!0},computeTime:function(){var e=void 0,t=this.fields;e=this.isSet(h)?t[h]:(new Date).getFullYear();var n=0;this.isSet(m)&&(n+=t[m]),n*=60,n+=t[g]||0,n*=60,n+=t[b]||0,n*=1e3,n+=t[P]||0;var r=0;t[h]=e,r+=this.getFixedDate();var o=(r-D)*N+n;o-=this.timezoneOffset*j,this.time=o,this.computeFields()},complete:function(){void 0===this.time&&this.computeTime(),this.fieldsComputed||this.computeFields()},getFixedDate:function(){var e=this,t=e.fields,n=e.firstDayOfWeek,a=t[h],i=r.JANUARY;e.isSet(y)&&(i=t[y],i>r.DECEMBER?(a+=u(i/12),i%=12):i<r.JANUARY&&(a+=V(i/12),i=A(i,12)));var l=c.getFixedDate(a,i,1),p=void 0,f=e.firstDayOfWeek;if(e.isSet(T)&&(f=t[T]),e.isSet(y))if(e.isSet(v))l+=t[v]-1;else if(e.isSet(w))p=s(l+6,n),p-l>=e.minimalDaysInFirstWeek&&(p-=7),f!==n&&(p=s(p+6,f)),l=p+7*(t[w]-1);else{var d=void 0;d=e.isSet(O)?t[O]:1;var m=7*d;d<0&&(m=o(a,i)+7*(d+1)),l=s(l+m-1,f)}else e.isSet(C)?l+=t[C]-1:e.isSet(x)&&(p=s(l+6,n),p-l>=e.minimalDaysInFirstWeek&&(p-=7),f!==n&&(p=s(p+6,f)),l=p+7*(t[x]-1));return l},getTime:function(){return void 0===this.time&&this.computeTime(),this.time},setTime:function(e){this.time=e,this.fieldsComputed=!1,this.complete()},get:function(e){return this.complete(),this.fields[e]},set:function(e,t){var n=arguments.length;if(2===n)this.fields[e]=t;else{if(!(n<P+1))throw new Error("illegal arguments for GregorianCalendar set");for(var r=0;r<n;r++)this.fields[h+r]=arguments[r]}this.time=void 0},add:function(e,t){if(t){var n=t,r=this,o=r.fields,a=r.get(e);if(e===h)a+=n,r.set(h,a),i(r);else if(e===y){a+=n;var s=V(a/12);a=A(a,12),s&&r.set(h,o[h]+s),r.set(y,a),i(r)}else{switch(e){case m:n*=_;break;case g:n*=j;break;case b:n*=k;break;case P:break;case w:case x:case O:n*=M;break;case T:case C:case v:n*=N;break;default:throw new Error("illegal field for add")}r.setTime(r.time+n)}}},getRolledValue:function(e,t,n,r){var o=t,a=e-n,i=r-n+1;return o%=i,n+(a+o+i)%i},roll:function(e,t){if(t){var n=this,r=n.get(e),o=n.getActualMinimum(e),a=n.getActualMaximum(e);switch(r=n.getRolledValue(r,t,o,a),n.set(e,r),e){case y:i(n);break;default:n.updateFieldsBySet(e)}}},rollSet:function(e,t){switch(this.set(e,t),e){case y:i(this);break;default:this.updateFieldsBySet(e)}},updateFieldsBySet:function(e){var t=this.fields;switch(e){case w:t[v]=void 0;break;case C:t[y]=void 0;break;case T:t[v]=void 0;break;case x:t[C]=void 0,t[y]=void 0}},getTimezoneOffset:function(){return this.timezoneOffset},setTimezoneOffset:function(e){this.timezoneOffset!==e&&(this.fieldsComputed=void 0,this.timezoneOffset=e)},setFirstDayOfWeek:function(e){this.firstDayOfWeek!==e&&(this.firstDayOfWeek=e,this.fieldsComputed=!1)},getFirstDayOfWeek:function(){return this.firstDayOfWeek},setMinimalDaysInFirstWeek:function(e){this.minimalDaysInFirstWeek!==e&&(this.minimalDaysInFirstWeek=e,this.fieldsComputed=!1)},getMinimalDaysInFirstWeek:function(){return this.minimalDaysInFirstWeek},getWeeksInWeekYear:function(){var e=this.getWeekYear();if(e===this.get(h))return this.getActualMaximum(x);var t=this.clone();return t.clear(),t.setWeekDate(e,2,this.get(T)),t.getActualMaximum(x)},getWeekYear:function(){var e=this.get(h),t=this.get(x),n=this.get(y);return n===r.JANUARY?t>=52&&--e:n===r.DECEMBER&&1===t&&++e,e},setWeekDate:function(e,t,n){if(n<r.SUNDAY||n>r.SATURDAY)throw new Error("invalid dayOfWeek: "+n);var o=this.fields,a=this.clone();a.clear(),a.setTimezoneOffset(0),a.set(h,e),a.set(x,1),a.set(T,this.getFirstDayOfWeek());var i=n-this.getFirstDayOfWeek();i<0&&(i+=7),i+=7*(t-1),0!==i?a.add(C,i):a.complete(),o[h]=a.get(h),o[y]=a.get(y),o[v]=a.get(v),this.complete()},clone:function(){void 0===this.time&&this.computeTime();var e=new r(this.locale);return e.setTimezoneOffset(e.getTimezoneOffset()),e.setFirstDayOfWeek(e.getFirstDayOfWeek()),e.setMinimalDaysInFirstWeek(e.getMinimalDaysInFirstWeek()),e.setTime(this.time),e},equals:function(e){return this.getTime()===e.getTime()&&this.firstDayOfWeek===e.firstDayOfWeek&&this.timezoneOffset===e.timezoneOffset&&this.minimalDaysInFirstWeek===e.minimalDaysInFirstWeek},compareToDay:function(e){var t=this.getYear(),n=e.getYear(),r=this.getMonth(),o=e.getMonth(),a=this.getDayOfMonth(),i=e.getDayOfMonth();return t!==n?t-n:r!==o?r-o:a-i},clear:function(e){void 0===e?this.field=[]:this.fields[e]=void 0,this.time=void 0,this.fieldsComputed=!1},toString:function(){var e=this;return"[GregorianCalendar]: "+e.getYear()+"/"+e.getMonth()+"/"+e.getDayOfMonth()+" "+e.getHourOfDay()+":"+e.getMinutes()+":"+e.getSeconds()}};var R=r.prototype;c.each(d,function(e,t){e&&(R["get"+e]=function(){return this.get(t)},R["isSet"+e]=function(){return this.isSet(t)},R["set"+e]=function(e){return this.set(t,e)},R["add"+e]=function(e){return this.add(t,e)},R["roll"+e]=function(e){return this.roll(t,e)},R["rollSet"+e]=function(e){return this.rollSet(t,e)})}),e.exports=r},function(e,t){"use strict";function n(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}function r(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;var r=Object.getOwnPropertyNames(t).map(function(e){return t[e]});if("0123456789"!==r.join(""))return!1;var o={};return"abcdefghijklmnopqrst".split("").forEach(function(e){o[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},o)).join("")}catch(a){return!1}}var o=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable;e.exports=r()?Object.assign:function(e,t){for(var r,i,s=n(e),l=1;l<arguments.length;l++){r=Object(arguments[l]);for(var u in r)o.call(r,u)&&(s[u]=r[u]);if(Object.getOwnPropertySymbols){i=Object.getOwnPropertySymbols(r);for(var c=0;c<i.length;c++)a.call(r,i[c])&&(s[i[c]]=r[i[c]])}}return s}},function(e,t,n){"use strict";e.exports={guid:n(402),classSet:n(401),joinClasses:n(403),KeyCode:n(24),PureRenderMixin:n(400),shallowEqual:n(123),createChainedFunction:n(46),Dom:{addEventListener:n(23),contains:n(118)},Children:{toArray:n(399),mapSelf:n(45)}}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.clone();return t.setTime(Date.now()),t}function a(e){return e.getYear()+"-"+(e.getMonth()+1)+"-"+e.getDayOfMonth()}function i(e){var t=o(e);return a(t)}function s(e,t){return"string"==typeof e?new y["default"](e,t.format):e}function l(e,t){t.setHourOfDay(e.getHourOfDay()),t.setMinutes(e.getMinutes()),t.setSeconds(e.getSeconds())}function u(e,t){var n=t?t(e):{};return n=d({},v,n)}function c(e,t){var n=!1;if(e){var r=e.getHourOfDay(),o=e.getMinutes(),a=e.getSeconds(),i=t.disabledHours();if(i.indexOf(r)===-1){var s=t.disabledMinutes(r);if(s.indexOf(o)===-1){var l=t.disabledSeconds(r,o);n=l.indexOf(a)!==-1}else n=!0}else n=!0}return!n}function p(e,t){var n=u(e,t);return c(e,n)}function f(e,t,n){return(!t||!t(e))&&!(n&&!p(e,n))}Object.defineProperty(t,"__esModule",{value:!0});var d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.getTodayTime=o,t.getTitleString=a,t.getTodayTimeStr=i,t.getFormatter=s,t.syncTime=l,t.getTimeConfig=u,t.isTimeValidByConfig=c,t.isTimeValid=p,t.isAllowedDate=f;var h=n(29),y=r(h),v={disabledHours:function(){return[]},disabledMinutes:function(){return[]},disabledSeconds:function(){return[]}}},[460,434],function(e,t,n){"use strict";e.exports=n(391)},function(e,t,n){e.exports=n(413)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(160),a=r(o),i=n(159),s=r(i);a["default"].Group=s["default"],t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";var r=function(){};e.exports=r},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(99),h=r(d),y=n(1),v=r(y),m=n(171),g=r(m),b=n(2),P=r(b),O=n(15),C=r(O),T=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return C["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.style,o=t.children,s=t.className,l=i(t,["prefixCls","style","children","className"]),u=(0,P["default"])((e={},a(e,s,!!s),a(e,n+"-wrapper",!0),e));return v["default"].createElement("label",{className:u,style:r},v["default"].createElement(h["default"],f({},l,{prefixCls:n,children:null})),void 0!==o?v["default"].createElement("span",null,o):null)},t}(v["default"].Component),c.Group=g["default"],c.defaultProps={prefixCls:"ant-checkbox"},p);t["default"]=T,e.exports=t["default"]},[460,428],function(e,t){"use strict";function n(e,t,r){var o=r;{if("object"!=typeof t)return"undefined"!=typeof o?("number"==typeof o&&(o+="px"),void(e.style[t]=o)):C(e,t);for(var a in t)t.hasOwnProperty(a)&&n(e,a,t[a])}}function r(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,a=o.body,i=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=i.clientLeft||a.clientLeft||0,r-=i.clientTop||a.clientTop||0,{left:n,top:r}}function o(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function a(e){return o(e)}function i(e){return o(e,!0)}function s(e){var t=r(e),n=e.ownerDocument,o=n.defaultView||n.parentWindow;return t.left+=a(o),t.top+=i(o),t}function l(e,t,n){var r=n,o="",a=e.ownerDocument;return r=r||a.defaultView.getComputedStyle(e,null),r&&(o=r.getPropertyValue(t)||r[t]),o}function u(e,t){var n=e[x]&&e[x][t];if(T.test(n)&&!w.test(t)){var r=e.style,o=r[S],a=e[E][S];e[E][S]=e[x][S],r[S]="fontSize"===t?"1em":n||0,n=r.pixelLeft+k,r[S]=o,e[E][S]=a}return""===n?"auto":n}function c(e,t){return"left"===e?t.useCssRight?"right":e:t.useCssBottom?"bottom":e}function p(e){return"left"===e?"right":"right"===e?"left":"top"===e?"bottom":"bottom"===e?"top":void 0}function f(e,t,r){"static"===n(e,"position")&&(e.style.position="relative");var o=-999,a=-999,i=c("left",r),l=c("top",r),u=p(i),f=p(l);"left"!==i&&(o=999),"top"!==l&&(a=999),"left"in t&&(e.style[u]="",e.style[i]=o+"px"),"top"in t&&(e.style[f]="",e.style[l]=a+"px");var d=s(e),h={},y=void 0;for(y in t)if(t.hasOwnProperty(y)){var v=c(y,r),m="left"===y?o:a;v===y?h[v]=m+t[y]-d[y]:h[v]=m+d[y]-t[y]}n(e,h)}function d(e,t){for(var n=0;n<e.length;n++)t(e[n])}function h(e){return"border-box"===C(e,"boxSizing")}function y(e,t,n){var r={},o=e.style,a=void 0;for(a in t)t.hasOwnProperty(a)&&(r[a]=o[a],o[a]=t[a]);n.call(e);for(a in t)t.hasOwnProperty(a)&&(o[a]=r[a])}function v(e,t,n){var r=0,o=void 0,a=void 0,i=void 0;for(a=0;a<t.length;a++)if(o=t[a])for(i=0;i<n.length;i++){var s=void 0;s="border"===o?o+n[i]+"Width":o+n[i],r+=parseFloat(C(e,s))||0}return r}function m(e){return null!==e&&void 0!==e&&e==e.window}function g(e,t,n){var r=n;if(m(e))return"width"===t?A.viewportWidth(e):A.viewportHeight(e);if(9===e.nodeType)return"width"===t?A.docWidth(e):A.docHeight(e);var o="width"===t?["Left","Right"]:["Top","Bottom"],a="width"===t?e.offsetWidth:e.offsetHeight,i=C(e),s=h(e,i),l=0;(null===a||void 0===a||a<=0)&&(a=void 0,l=C(e,t),(null===l||void 0===l||Number(l)<0)&&(l=e.style[t]||0),l=parseFloat(l)||0),void 0===r&&(r=s?M:_);var u=void 0!==a||s,c=a||l;return r===_?u?c-v(e,["border","padding"],o,i):l:u?r===M?c:c+(r===N?-v(e,["border"],o,i):v(e,["margin"],o,i)):l+v(e,j.slice(r),o,i)}function b(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=void 0,o=t[0];return 0!==o.offsetWidth?r=g.apply(void 0,t):y(o,L,function(){r=g.apply(void 0,t)}),r}function P(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}Object.defineProperty(t,"__esModule",{value:!0});var O=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,C=void 0,T=new RegExp("^("+O+")(?!px)[a-z%]+$","i"),w=/^(top|right|bottom|left)$/,x="currentStyle",E="runtimeStyle",S="left",k="px";"undefined"!=typeof window&&(C=window.getComputedStyle?l:u);var j=["margin","border","padding"],_=-1,N=2,M=1,D=0,A={};d(["Width","Height"],function(e){A["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],A["viewport"+e](n))},A["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,a=r.documentElement,i=a[n];return"CSS1Compat"===r.compatMode&&i||o&&o[n]||i}});var L={position:"absolute",visibility:"hidden",display:"block"};d(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);A["outer"+t]=function(t,n){return t&&b(t,e,n?D:M)};var r="width"===e?["Left","Right"]:["Top","Bottom"];A[e]=function(t,o){var a=o;{if(void 0===a)return t&&b(t,e,_);if(t){var i=C(t),s=h(t);return s&&(a+=v(t,["padding","border"],r,i)),n(t,e,a)}}}});var V={getWindow:function(e){if(e&&e.document&&e.setTimeout)return e;var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t,n){return"undefined"==typeof t?s(e):void f(e,t,n||{})},isWindow:m,each:d,css:n,clone:function(e){var t=void 0,n={};for(t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);var r=e.overflow;if(r)for(t in e)e.hasOwnProperty(t)&&(n.overflow[t]=e.overflow[t]);return n},mix:P,getWindowScrollLeft:function(e){return a(e)},getWindowScrollTop:function(e){return i(e)},merge:function(){for(var e={},t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];for(var o=0;o<n.length;o++)V.mix(e,n[o]);return e},viewportWidth:0,viewportHeight:0};P(V,A),t["default"]=V,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Divider=t.ItemGroup=t.MenuItemGroup=t.MenuItem=t.Item=t.SubMenu=void 0;var o=n(321),a=r(o),i=n(324),s=r(i),l=n(322),u=r(l),c=n(323),p=r(c),f=n(320),d=r(f);t.SubMenu=s["default"],t.Item=u["default"],t.MenuItem=u["default"],t.MenuItemGroup=p["default"],t.ItemGroup=p["default"],t.Divider=d["default"],t["default"]=a["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t,n){var r=t||"";return e.key||r+"item_"+u+"_"+n}function i(e,t){var n=-1;l["default"].Children.forEach(e,function(e){n++,e&&e.type.isMenuItemGroup?l["default"].Children.forEach(e.props.children,function(e){n++,t(e,n)}):t(e,n)})}Object.defineProperty(t,"__esModule",{value:!0}),t.noop=o,t.getKeyFromChildrenIndex=a,t.loopMenuItem=i;var s=n(1),l=r(s),u=Date.now()},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=l["default"].unstable_batchedUpdates?function(e){l["default"].unstable_batchedUpdates(n,e)}:n;return(0,i["default"])(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var a=n(128),i=r(a),s=n(4),l=r(s);e.exports=t["default"]},function(e,t){"use strict";var n={MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,QUESTION_MARK:63,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,SINGLE_QUOTE:222,OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,WIN_IME:229};n.isTextModifyingKeyEvent=function(e){var t=e.keyCode;if(e.altKey&&!e.ctrlKey||e.metaKey||t>=n.F1&&t<=n.F12)return!1;switch(t){case n.ALT:case n.CAPS_LOCK:case n.CONTEXT_MENU:case n.CTRL:case n.DOWN:case n.END:case n.ESC:case n.HOME:case n.INSERT:case n.LEFT:case n.MAC_FF_META:case n.META:case n.NUMLOCK:case n.NUM_CENTER:case n.PAGE_DOWN:case n.PAGE_UP:case n.PAUSE:case n.PRINT_SCREEN:case n.RIGHT:case n.SHIFT:case n.UP:case n.WIN_KEY:case n.WIN_KEY_RIGHT:return!1;default:return!0}},n.isCharacterKey=function(e){if(e>=n.ZERO&&e<=n.NINE)return!0;if(e>=n.NUM_ZERO&&e<=n.NUM_MULTIPLY)return!0;if(e>=n.A&&e<=n.Z)return!0;if(window.navigation.userAgent.indexOf("WebKit")!==-1&&0===e)return!0;switch(e){case n.SPACE:case n.QUESTION_MARK:case n.NUM_PLUS:case n.NUM_MINUS:case n.NUM_PERIOD:case n.NUM_DIVISION:case n.SEMICOLON:case n.DASH:case n.EQUALS:case n.COMMA:case n.PERIOD:case n.SLASH:case n.APOSTROPHE:case n.SINGLE_QUOTE:case n.OPEN_SQUARE_BRACKET:case n.BACKSLASH:case n.CLOSE_SQUARE_BRACKET:return!0;default:return!1}},e.exports=n},[460,423],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(36),a=r(o),i=n(216),s=r(i),l=n(69),u=r(l);a["default"].Button=u["default"],a["default"].Group=s["default"],t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(349),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.size,r=t.className,o=t.combobox,i=t.notFoundContent,s=t.prefixCls,l=t.showSearch,u=t.optionLabelProp,c=(0,m["default"])((e={},a(e,s+"-lg","large"===n),a(e,s+"-sm","small"===n),a(e,r,!!r),a(e,s+"-show-search",l),e)),f=this.context.antLocale;return f&&f.Select&&(i=i||f.Select.notFoundContent),o&&(i=null,u=u||"value"),d["default"].createElement(y["default"],p({},this.props,{className:c,optionLabelProp:u||"children",notFoundContent:i}))},t}(d["default"].Component),u.Option=h.Option,u.OptGroup=h.OptGroup,u.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",choiceTransitionName:"zoom",showSearch:!1},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=g,e.exports=t["default"]},[461,444],function(e,t,n){"use strict";function r(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}function o(e,t,n){return"string"==typeof e&&t?e.replace(n||T,function(e,n){return"\\"===e.charAt(0)?e.slice(1):void 0===t[n]?w:t[n]}):e}function a(e,t,n){n.push({field:e,count:t})}function i(e){for(var t=e.length,n=!1,r=[],o=null,i=0,s=-1,l=0;l<t;l++){var u=e.charAt(l);if("'"!==u)if(n)o+=u;else if(u>="a"&&u<="z"||u>="A"&&u<="Z"){if(P.indexOf(u)===-1)throw new Error('Illegal pattern character "'+u+'"');s!==-1&&s!==u?(a(s,i,r),s=u,i=1):(s=u,i++)}else 0!==i&&(a(s,i,r),s=-1,i=0),r.push({text:u});else{if(l+1<t&&(u=e.charAt(l+1),"'"===u)){l++,0!==i&&(a(s,i,r),s=-1,i=0),n&&(o+=u);continue}n?(r.push({text:o}),n=!1):(0!==i&&(a(s,i,r),s=-1,i=0),o="",n=!0)}}if(n)throw new Error("Unterminated quote");return 0!==i&&a(s,i,r),r}function s(e,t,n,r){var o=!0;e:for(;o;){var a=e,i=t,s=n,l=r;o=!1;var u=l||[],c=s||m;if(a>=0){if(a<100&&i>=1&&i<=2)return a<10&&2===i&&u.push(x),u.push(a),u.join("");if(a>=1e3&&a<1e4){if(4===i)return u.push(a),u.join("");if(2===i&&2===c){e=a%100,t=2,n=2,r=u,o=!0,u=c=void 0;continue e}}}return u.push(a+""),u.join("")}}function l(e,t){this.locale=t||v,this.originalPattern=e,this.pattern=i(e)}function u(e,t,n,r){var o=void 0,a=void 0;switch(e){case"G":a=r.getYear()>0?1:0,o=n.eras[a];break;case"Y":a=r.getWeekYear(),a<=0&&(a=1-a),o=s(a,2,2!==t?m:2);break;case"y":a=r.getYear(),a<=0&&(a=1-a),o=s(a,2,2!==t?m:2);break;case"M":a=r.getMonth(),o=t>=4?n.months[a]:3===t?n.shortMonths[a]:s(a+1,t);break;case"k":o=s(r.getHourOfDay()||24,t);break;case"E":a=r.getDayOfWeek(),o=t>=4?n.weekdays[a]:n.shortWeekdays[a];break;case"a":o=n.ampms[r.getHourOfDay()>=12?1:0];break;case"h":o=s(r.getHourOfDay()%12||12,t);break;case"K":o=s(r.getHourOfDay()%12,t);break;case"Z":var i=r.getTimezoneOffset(),l=[i<0?"-":"+"];i=Math.abs(i),l.push(s(Math.floor(i/60)%100,2),s(i%60,2)),o=l.join("");break;default:var u=C[e];a=r.get(u),o=s(a,t)}return o}function c(e,t,n,r){for(var o=0;o<r;o++)if(e.charAt(t+o)!==n.charAt(o))return!1;return!0}function p(e,t,n){var r=-1,o=-1,a=void 0,i=n.length;for(a=0;a<i;a++){var s=n[a],l=s.length;l>r&&c(e,t,s,l)&&(r=l,o=a)}return o>=0?{value:o,startIndex:t+r}:null}function f(e){var t=void 0,n=void 0,r=e.length;for(t=0;t<r&&(n=e.charAt(t),!(n<"0"||n>"9"));t++);return t}function d(e,t,n,r){var o=e,a=void 0;if(r){if(e.length<t+n)return null;if(o=e.slice(t,t+n),!o.match(/^\d+$/))throw new Error("GregorianCalendarFormat parse error, dateStr: "+e+", patter: "+this.originalPattern)}else o=o.slice(t);if(a=parseInt(o,10),isNaN(a))throw new Error("GregorianCalendarFormat parse error, dateStr: "+e+", patter: "+this.originalPattern);return{value:a,startIndex:t+f(o)}}function h(e,t,n,r,o,a,i){var s=void 0,l=void 0,u=void 0,c=n;if(t.length<=c)return c;var f=this.locale;switch(r){case"G":s=p(t,c,f.eras),s&&(e.isSetYear()?0===s.value&&(l=e.getYear(),e.setYear(1-l)):i.era=s.value);break;case"y":s=d.call(this,t,c,o,a),s&&(l=s.value,"era"in i&&0===i.era&&(l=1-l),e.setYear(l));break;case"M":var h=void 0;o>=3?(s=p(t,c,f[3===o?"shortMonths":"months"]),s&&(h=s.value)):(s=d.call(this,t,c,o,a),s&&(h=s.value-1)),s&&e.setMonth(h);break;case"k":s=d.call(this,t,c,o,a),s&&e.setHourOfDay(s.value%24);break;case"E":s=p(t,c,f[o>3?"weekdays":"shortWeekdays"]),s&&e.setDayOfWeek(s.value);break;case"a":s=p(t,c,f.ampms),s&&(e.isSetHourOfDay()?s.value&&(u=e.getHourOfDay(),u<12&&e.setHourOfDay((u+12)%24)):i.ampm=s.value);break;case"h":s=d.call(this,t,c,o,a),s&&(u=s.value%=12,i.ampm&&(u+=12),e.setHourOfDay(u));break;case"K":s=d.call(this,t,c,o,a),s&&(u=s.value,i.ampm&&(u+=12),e.setHourOfDay(u));break;case"Z":var y=t.charAt(c);if("-"===y)c++;else{if("+"!==y)break;c++}if(s=d.call(this,t,c,2,!0)){var v=60*s.value;c=s.startIndex,s=d.call(this,t,c,2,!0),s&&(v+=s.value),e.setTimezoneOffset(v)}break;default:if(s=d.call(this,t,c,o,a)){var m=C[r];e.set(m,s.value)}}return s&&(c=s.startIndex),c}var y=n(9),v=n(41),m=Number.MAX_VALUE,g=n(267),b={FULL:0,LONG:1,MEDIUM:2,SHORT:3},P=new Array(y.DAY_OF_WEEK_IN_MONTH+2).join("1"),O=0,C={};P=P.split(""),P[O]="G",P[y.YEAR]="y",P[y.MONTH]="M",P[y.DAY_OF_MONTH]="d",P[y.HOUR_OF_DAY]="H",P[y.MINUTES]="m",P[y.SECONDS]="s",P[y.MILLISECONDS]="S",P[y.WEEK_OF_YEAR]="w",P[y.WEEK_OF_MONTH]="W",P[y.DAY_OF_YEAR]="D",P[y.DAY_OF_WEEK_IN_MONTH]="F",P.push("Y"),P.forEach(function(e,t){var n=t;"Y"===e&&(n=y.YEAR),e&&(C[e]=n)});var T=/\\?\{([^{}]+)\}/g,w="";P=P.join("")+"ahkKZE";var x="0";r(l.prototype,{format:function(e){if(!e.isGregorianCalendar)throw new Error("calendar must be type of GregorianCalendar");var t=void 0,n=[],r=this.pattern,o=r.length;for(t=0;t<o;t++){var a=r[t];a.text?n.push(a.text):"field"in a&&n.push(u(a.field,a.count,this.locale,e))}return n.join("")},parse:function(e,t){var n=t||{},r=n.locale,o=new y(r),a=void 0,i=void 0,s={},l=n.obeyCount||!1,u=e.length,c=-1,p=0,f=0,d=this.pattern,v=d.length;e:for(a=0;c<0&&a<v;a++){var m=d[a],b=void 0,P=void 0;if(f=p,b=m.text)if(P=b.length,P+p>u)c=p;else{for(i=0;i<P;i++)if(b.charAt(i)!==e.charAt(i+p)){c=p;break e}p+=P}else if("field"in m){if(!n.obeyCount){var O=d[a+1];if(l=!1,O)if("field"in O)l=!0;else{var C=O.text.charAt(0);C>="0"&&C<="9"&&(l=!0)}}p=h.call(this,o,e,p,m.field,m.count,l,s),p===f&&(c=p)}}return c>=0?void g(!1,"error when parsing date: "+e+", position: "+e.slice(0,c)+"^"):o}}),r(l,{Style:b,getInstance:function(e){ return this.getDateTimeInstance(b.SHORT,b.SHORT,e)},getDateInstance:function(e,t){return this.getDateTimeInstance(e,void 0,t)},getDateTimeInstance:function(e,t,n){var r=n||v,a="";void 0!==e&&(a=r.datePatterns[e]);var i="";void 0!==t&&(i=r.timePatterns[t]);var s=a;return i&&(s=a?o(r.dateTimePattern,{date:a,time:i}):i),new l(s,r)},getTimeInstance:function(e,t){return this.getDateTimeInstance(void 0,e,t)}}),e.exports=l,l.version="@VERSION@"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=n(296),s=r(i),l=n(12);t["default"]={propTypes:{className:a.PropTypes.string,locale:a.PropTypes.object,style:a.PropTypes.object,visible:a.PropTypes.bool,onSelect:a.PropTypes.func,prefixCls:a.PropTypes.string,onChange:a.PropTypes.func,onOk:a.PropTypes.func},getDefaultProps:function(){return{locale:s["default"],style:{},visible:!0,prefixCls:"rc-calendar",formatter:"yyyy-MM-dd",className:"",onSelect:o,onChange:o,onClear:o}},shouldComponentUpdate:function(e){return this.props.visible||e.visible},getFormatter:function(){var e=this.props.formatter,t=this.props.locale;return this.normalFormatter&&e===this.lastFormatter?this.normalFormatter:(this.normalFormatter=(0,l.getFormatter)(e,t),this.lastFormatter=e,this.normalFormatter)}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.props;if("value"in t)return t.value;if(e.key)return e.key;throw new Error("no key or value for "+e)}function a(e,t){return"value"===t?o(e):e.props[t]}function i(e){return e.combobox}function s(e){return e.multiple||e.tags}function l(e){return s(e)||i(e)}function u(e){return!l(e)}function c(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function p(e){e.preventDefault()}function f(e,t){for(var n=-1,r=0;r<e.length;r++)if(e[r].key===t){n=r;break}return n}function d(e,t){if(null===t||void 0===t)return[];var n=[];return m["default"].Children.forEach(e,function(e){if(e.type===y.ItemGroup)n=n.concat(d(e.props.children,t));else{var r=o(e),a=e.key;f(t,r)!==-1&&a&&n.push(a)}}),n}function h(e){for(var t=0;t<e.length;t++){var n=e[t];if(n.type===y.ItemGroup){var r=h(n.props.children);if(r)return r}else if(!n.props.disabled)return n}return null}Object.defineProperty(t,"__esModule",{value:!0}),t.UNSELECTABLE_ATTRIBUTE=t.UNSELECTABLE_STYLE=void 0,t.getValuePropValue=o,t.getPropValue=a,t.isCombobox=i,t.isMultipleOrTags=s,t.isMultipleOrTagsOrCombobox=l,t.isSingleMode=u,t.toArray=c,t.preventDefaultEvent=p,t.findIndexInValueByKey=f,t.getSelectKeys=d,t.findFirstMenuItem=h;var y=n(21),v=n(1),m=r(v);t.UNSELECTABLE_STYLE={userSelect:"none",WebkitUserSelect:"none"},t.UNSELECTABLE_ATTRIBUTE={unselectable:"unselectable"}},function(e,t){"use strict";function n(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var r,o,a=n(e),i=1;i<arguments.length;i++){r=arguments[i],o=Object.keys(Object(r));for(var s=0;s<o.length;s++)a[o[s]]=r[o[s]]}return a}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=e.type,l=[],u=e.required||!e.required&&r.hasOwnProperty(e.field);if(u){if((0,s.isEmptyValue)(t,a)&&!e.required)return n();i["default"].required(e,t,r,l,o,a),(0,s.isEmptyValue)(t,a)||i["default"].type(e,t,r,l,o)}n(l)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Col=t.Row=void 0;var o=n(195),a=r(o),i=n(194),s=r(i);t.Row=a["default"],t.Col=s["default"]},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=e.arrowWidth,n=void 0===t?5:t,a=e.horizontalArrowShift,i=void 0===a?16:a,s=e.verticalArrowShift,l=void 0===s?12:s;return{left:{points:["cr","cl"],overflow:r,offset:[-4,0],targetOffset:o},right:{points:["cl","cr"],overflow:r,offset:[4,0],targetOffset:o},top:{points:["bc","tc"],overflow:r,offset:[0,-4],targetOffset:o},bottom:{points:["tc","bc"],overflow:r,offset:[0,4],targetOffset:o},topLeft:{points:["bl","tc"],overflow:r,offset:[-(i+n),-4],targetOffset:o},leftTop:{points:["tr","cl"],overflow:r,offset:[-4,-(l+n)],targetOffset:o},topRight:{points:["br","tc"],overflow:r,offset:[i+n,-4],targetOffset:o},rightTop:{points:["tl","cr"],overflow:r,offset:[4,-(l+n)],targetOffset:o},bottomRight:{points:["tr","bc"],overflow:r,offset:[i+n,4],targetOffset:o},rightBottom:{points:["bl","cr"],overflow:r,offset:[4,l+n],targetOffset:o},bottomLeft:{points:["tl","bc"],overflow:r,offset:[-(i+n),4],targetOffset:o},leftBottom:{points:["br","cl"],overflow:r,offset:[-4,l+n],targetOffset:o}}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n;var r={adjustX:1,adjustY:1},o=[0,0];e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(340),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=n(15),b=r(g),P=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return b["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.checked,i=t.disabled,s=t.className,l=t.style,u=(0,m["default"])((e={},a(e,""+n,!0),a(e,n+"-checked",o),a(e,n+"-disabled",i),a(e,s,!!s),e));return y["default"].createElement("label",{className:u,style:l},y["default"].createElement(d["default"],p({},this.props,{style:null,children:null})),r?y["default"].createElement("span",null,r):null)},t}(y["default"].Component),u.defaultProps={prefixCls:"ant-radio"},c);t["default"]=P,e.exports=t["default"]},[460,442],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(111),h=r(d),y=n(35),v=r(y),m=(0,v["default"])({verticalArrowShift:8}),g=(u=l=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.onVisibleChange=function(e){r.setState({visible:e})},r.onPopupAlign=function(e,t){var n=Object.keys(m).filter(function(e){return m[e].points[0]===t.points[0]&&m[e].points[1]===t.points[1]})[0];if(n){var r=e.getBoundingClientRect(),o={top:"50%",left:"50%"};n.indexOf("top")>=0||n.indexOf("Bottom")>=0?o.top=r.height-t.offset[1]+"px":(n.indexOf("Top")>=0||n.indexOf("bottom")>=0)&&(o.top=-t.offset[1]+"px"),n.indexOf("left")>=0||n.indexOf("Right")>=0?o.left=r.width-t.offset[0]+"px":(n.indexOf("right")>=0||n.indexOf("Left")>=0)&&(o.left=-t.offset[0]+"px"),e.style.transformOrigin=o.left+" "+o.top}},r.state={visible:!1},r}return s(t,e),t.prototype.getPopupDomNode=function(){return this.refs.tooltip.getPopupDomNode()},t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.title,r=e.overlay,o=e.children,a=e.transitionName,i=this.state.visible;n||r||(i=!1),"visible"in this.props&&(i=this.props.visible);var s=this.props.openClassName||t+"-open",l=o&&o.props&&o.props.className?o.props.className+" "+s:s;return f["default"].createElement(h["default"],c({transitionName:a,builtinPlacements:m,overlay:n,visible:i,onVisibleChange:this.onVisibleChange,onPopupAlign:this.onPopupAlign,ref:"tooltip"},this.props),i?(0,p.cloneElement)(o,{className:l}):o)},t}(f["default"].Component),l.defaultProps={prefixCls:"ant-tooltip",placement:"top",transitionName:"zoom-big",mouseEnterDelay:.1,mouseLeaveDelay:.1},u);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=window.getComputedStyle(e),r="",o=0;o<d.length&&!(r=n.getPropertyValue(d[o]+t));o++);return r}function a(e){if(p){var t=parseFloat(o(e,"transition-duration"))||0,n=parseFloat(o(e,"animation-duration"))||0,r=Math.max(t,n);e.rcEndAnimTimeout=setTimeout(function(){e.rcEndAnimTimeout=null,e.rcEndListener&&e.rcEndListener()},1e3*r+200)}}function i(e){e.rcEndAnimTimeout&&(clearTimeout(e.rcEndAnimTimeout),e.rcEndAnimTimeout=null)}Object.defineProperty(t,"__esModule",{value:!0});var s=n(256),l=r(s),u=n(77),c=r(u),p=0!==l["default"].endEvents.length,f=["Webkit","Moz","O","ms"],d=["-webkit-","-moz-","-o-","ms-",""],h=function(e,t,n){var r=t,o=r+"-active",s=n,u=void 0,p=void 0,f=(0,c["default"])(e);return n&&"[object Object]"===Object.prototype.toString.call(n)&&(s=n.end,u=n.start,p=n.active),e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),i(e),f.remove(r),f.remove(o),l["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,s&&s())},l["default"].addEndEventListener(e,e.rcEndListener),u&&u(),f.add(r),e.rcAnimTimeout=setTimeout(function(){e.rcAnimTimeout=null,f.add(o),p&&setTimeout(p,0),a(e)},30),{stop:function(){e.rcEndListener&&e.rcEndListener()}}};h.style=function(e,t,n){e.rcEndListener&&e.rcEndListener(),e.rcEndListener=function(t){t&&t.target!==e||(e.rcAnimTimeout&&(clearTimeout(e.rcAnimTimeout),e.rcAnimTimeout=null),i(e),l["default"].removeEndEventListener(e,e.rcEndListener),e.rcEndListener=null,n&&n())},l["default"].addEndEventListener(e,e.rcEndListener),e.rcAnimTimeout=setTimeout(function(){for(var n in t)t.hasOwnProperty(n)&&(e.style[n]=t[n]);e.rcAnimTimeout=null,a(e)},0)},h.setTransition=function(e,t,n){var r=t,o=n;void 0===n&&(o=r,r=""),r=r||"",f.forEach(function(t){e.style[t+"Transition"+r]=o})},h.isCssAnimationSupported=p,t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(263)},function(e,t){"use strict";e.exports={eras:["BC","AD"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],weekdays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortWeekdays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],veryShortWeekdays:["Su","Mo","Tu","We","Th","Fr","Sa"],ampms:["AM","PM"],datePatterns:["EEEE, MMMM d, yyyy","MMMM d, yyyy","MMM d, yyyy","M/d/yy"],timePatterns:["h:mm:ss a 'GMT'Z","h:mm:ss a","h:mm:ss a","h:mm a"],dateTimePattern:"{date} {time}"}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(293),p=r(c),f=n(292),d=r(f),h=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls;return u["default"].createElement("table",{className:t+"-table",cellSpacing:"0",role:"grid"},u["default"].createElement(p["default"],e),u["default"].createElement(d["default"],e))},t}(u["default"].Component);t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}function i(){var e=new d["default"];return e.setTime(Date.now()),e}function s(e){var t=void 0;return e?(t=e.clone(),t.setTime(Date.now())):t=i(),t}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(2),p=r(c),f=n(9),d=r(f),h=n(12),y={propTypes:{value:l.PropTypes.object,defaultValue:l.PropTypes.object,onKeyDown:l.PropTypes.func},getDefaultProps:function(){return{onKeyDown:a}},getInitialState:function(){var e=this.props,t=e.value||e.defaultValue||i();return{value:t,selectedValue:e.selectedValue||e.defaultSelectedValue}},componentWillReceiveProps:function(e){var t=e.value,n=e.selectedValue;"value"in e&&(t=t||e.defaultValue||s(this.state.value),this.setState({value:t})),"selectedValue"in e&&this.setState({selectedValue:n})},onSelect:function(e,t){e&&this.setValue(e),this.setSelectedValue(e,t)},renderRoot:function(e){var t,n=this.props,r=n.prefixCls,a=(t={},o(t,r,1),o(t,r+"-hidden",!n.visible),o(t,n.className,!!n.className),o(t,e.className,!!e.className),t);return u["default"].createElement("div",{className:""+(0,p["default"])(a),style:this.props.style,tabIndex:"0",onKeyDown:this.onKeyDown},e.children)},setSelectedValue:function(e,t){this.isAllowedDate(e)&&("selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onSelect(e,t))},setValue:function(e){var t=this.state.value;"value"in this.props||this.setState({value:e}),(t&&e&&t.getTime()!==e.getTime()||!t&&e||t&&!e)&&this.props.onChange(e)},isAllowedDate:function(e){var t=this.props.disabledDate,n=this.props.disabledTime;return(0,h.isAllowedDate)(e,t,n)}};t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t}(u["default"].Component);t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e}var o=n(1);e.exports=function(e){return o.Children.map(e,r)}},function(e,t){"use strict";function n(){var e=arguments;return function(){for(var t=0;t<e.length;t++)e[t]&&e[t].apply&&e[t].apply(this,arguments)}}e.exports=n},function(e,t,n){(function(e,r){function o(e,t){this._id=e,this._clearFn=t}var a=n(281).nextTick,i=Function.prototype.apply,s=Array.prototype.slice,l={},u=0;t.setTimeout=function(){return new o(i.call(setTimeout,window,arguments),clearTimeout)},t.setInterval=function(){return new o(i.call(setInterval,window,arguments),clearInterval)},t.clearTimeout=t.clearInterval=function(e){e.close()},o.prototype.unref=o.prototype.ref=function(){},o.prototype.close=function(){this._clearFn.call(window,this._id)},t.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},t.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},t._unrefActive=t.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},t.setImmediate="function"==typeof e?e:function(e){var n=u++,r=!(arguments.length<2)&&s.call(arguments,1);return l[n]=!0,a(function(){l[n]&&(r?e.apply(null,r):e.call(null),t.clearImmediate(n))}),n},t.clearImmediate="function"==typeof r?r:function(e){delete l[e]}}).call(t,n(47).setImmediate,n(47).clearImmediate)},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},3,function(e,t){function n(e,t,n){n=n||{},n.childrenKeyName=n.childrenKeyName||"children";var r,o=e||[],a=[],i=0;do{var r=o.filter(function(e){return t(e,i)})[0];if(!r)break;a.push(r),o=r[n.childrenKeyName]||[],i+=1}while(o.length>0);return a}e.exports=n},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o,a){!e.required||n.hasOwnProperty(e.field)&&!i.isEmptyValue(t,a)||r.push(i.format(o.messages.required,e.fullField))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(){if(void 0!==r)return r;var e="Webkit Moz O ms Khtml".split(" "),t=document.createElement("div");if(void 0!==t.style.animationName&&(r=!0),void 0!==r)for(var n=0;n<e.length;n++)if(void 0!==t.style[e[n]+"AnimationName"]){r=!0;break}return r=r||!1}Object.defineProperty(t,"__esModule",{value:!0});var r=void 0;t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){var r=void 0;return(0,i["default"])(e,"ant-motion-collapse",{start:function(){t?(r=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?r:0)+"px"},end:function(){e.style.height="",n()}})}Object.defineProperty(t,"__esModule",{value:!0});var a=n(39),i=r(a),s={enter:function(e,t){return o(e,!0,t)},leave:function(e,t){return o(e,!1,t)},appear:function(e,t){return o(e,!0,t)}};t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.prefixCls,n=e.separator,r=e.children,o=a(e,["prefixCls","separator","children"]),i=void 0;return i="href"in this.props?d["default"].createElement("a",p({className:t+"-link"},o),r):d["default"].createElement("span",p({className:t+"-link"},o),r),d["default"].createElement("span",null,i,d["default"].createElement("span",{className:t+"-separator"},n))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-breadcrumb",separator:"/"},u.propTypes={prefixCls:d["default"].PropTypes.string,separator:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.element]),href:d["default"].PropTypes.string},c);t["default"]=h,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.PREFIX_CLS="ant-fullcalendar"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(84),i=r(a),s=n(95),l=r(s),u=n(72),c=r(u),p=o({},i["default"]);p.lang=o({placeholder:"\u8bf7\u9009\u62e9\u65e5\u671f",rangePlaceholder:["\u5f00\u59cb\u65e5\u671f","\u7ed3\u675f\u65e5\u671f"]},l["default"]),p.timePickerLocale=o({},c["default"]),p.lang.ok="\u786e \u5b9a",t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(313),y=r(h),v=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.overlay,n=a(e,["overlay"]),r=d["default"].cloneElement(t,{openTransitionName:"zoom-big"});return d["default"].createElement(y["default"],p({},n,{overlay:r}))},t}(d["default"].Component),u.defaultProps={transitionName:"slide-up",prefixCls:"ant-dropdown",mouseEnterDelay:.15,mouseLeaveDelay:.1},c);t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(57),a=r(o),i=n(182),s=r(i);a["default"].Button=s["default"],t["default"]=a["default"],e.exports=t["default"]},[462,431],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(192),a=r(o),i=n(191),s=r(i);a["default"].Group=s["default"],t["default"]=a["default"],e.exports=t["default"]},[460,49],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(311),y=r(h),v=n(23),m=r(v),g=n(16),b=r(g),P=void 0,O=void 0,C=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return n=r=i(this,e.call.apply(e,[this].concat(l))),r.handleCancel=function(e){r.props.onCancel(e)},r.handleOk=function(){r.props.onOk()},o=n,i(r,o)}return s(t,e),t.prototype.componentDidMount=function(){O||((0,m["default"])(document.documentElement,"click",function(e){P={x:e.pageX,y:e.pageY},setTimeout(function(){return P=null},20)}),O=!0)},t.prototype.render=function(){var e=this.props,t=e.okText,n=e.cancelText;this.context.antLocale&&this.context.antLocale.Modal&&(t=t||this.context.antLocale.Modal.okText,n=n||this.context.antLocale.Modal.cancelText);var r=[d["default"].createElement(b["default"],{key:"cancel",type:"ghost",size:"large",onClick:this.handleCancel},n||"\u53d6\u6d88"),d["default"].createElement(b["default"],{key:"confirm",type:"primary",size:"large",loading:e.confirmLoading,onClick:this.handleOk},t||"\u786e\u5b9a")],o=e.footer||r;return d["default"].createElement(y["default"],p({onClose:this.handleCancel,footer:o},e,{visible:e.visible,mousePosition:P}))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-modal",onOk:l,onCancel:l,width:520,transitionName:"zoom",maskTransitionName:"fade",confirmLoading:!1,visible:!1},u.propTypes={prefixCls:f.PropTypes.string,onOk:f.PropTypes.func,onCancel:f.PropTypes.func,okText:f.PropTypes.node,cancelText:f.PropTypes.node,width:f.PropTypes.oneOfType([f.PropTypes.number,f.PropTypes.string]),confirmLoading:f.PropTypes.bool,visible:f.PropTypes.bool,align:f.PropTypes.object,footer:f.PropTypes.node,title:f.PropTypes.node,closable:f.PropTypes.bool},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=C,e.exports=t["default"]},function(e,t){"use strict";function n(e){i=e?o({},i,e):o({},a)}function r(){return i}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.changeConfirmLocale=n,t.getConfirmLocale=r;var a={okText:"\u786e\u5b9a",cancelText:"\u53d6\u6d88",justOkText:"\u77e5\u9053\u4e86"},i=o({},a)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(208),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(439),n(28),n(13)},[460,440],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(213),l=r(s),u=n(17),c=r(u),p=l["default"];p.Line=function(e){return(0,c["default"])(!1,'<Progress.Line /> is deprecated, use <Progress type="line" /> instead.'),i["default"].createElement(l["default"],o({},e,{type:"line"}))},p.Circle=function(e){return(0,c["default"])(!1,'<Progress.Circle /> is deprecated, use <Progress type="circle" /> instead.'),i["default"].createElement(l["default"],o({},e,{type:"circle"}))},t["default"]=p,e.exports=t["default"]},[460,441],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(36),d=r(f),h=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.defaultProps={prefixCls:"ant-radio-button"},u);t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(4),v=n(2),m=r(v),g=n(52),b=r(g),P=n(17),O=r(P),C=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n)),o=r.getSpinning(n); return r.state={spinning:o},r}return u(t,e),t.prototype.isNestedPattern=function(){return!(!this.props||!this.props.children)},t.prototype.componentDidMount=function(){(0,O["default"])(!("spining"in this.props),"`spining` property of Popover is a spell mistake, use `spinning` instead."),(0,b["default"])()||((0,y.findDOMNode)(this).className+=" "+this.props.prefixCls+"-show-text")},t.prototype.componentWillUnmount=function(){this.debounceTimeout&&clearTimeout(this.debounceTimeout)},t.prototype.getSpinning=function(e){return"spining"in e?((0,O["default"])(!1,"`spining` property of Spin is a spell mistake, use `spinning` instead."),e.spining):e.spinning},t.prototype.componentWillReceiveProps=function(e){var t=this,n=this.getSpinning(e);this.debounceTimeout&&clearTimeout(this.debounceTimeout),n?this.debounceTimeout=setTimeout(function(){return t.setState({spinning:n})},250):this.setState({spinning:n})},t.prototype.render=function(){var e,t=this.props,n=t.className,r=t.size,o=t.prefixCls,s=t.tip,l=i(t,["className","size","prefixCls","tip"]),u=this.state.spinning,c=(0,m["default"])((e={},a(e,o,!0),a(e,o+"-sm","small"===r),a(e,o+"-lg","large"===r),a(e,o+"-spinning",u),a(e,o+"-show-text",!!this.props.tip),a(e,n,!!n),e)),p=h["default"].createElement("div",f({},l,{className:c}),h["default"].createElement("span",{className:o+"-dot "+o+"-dot-first"}),h["default"].createElement("span",{className:o+"-dot "+o+"-dot-second"}),h["default"].createElement("span",{className:o+"-dot "+o+"-dot-third"}),h["default"].createElement("div",{className:o+"-text"},s||"\u52a0\u8f7d\u4e2d..."));return this.isNestedPattern()?h["default"].createElement("div",f({},l,{className:u?o+"-nested-loading":""}),p,h["default"].createElement("div",{className:o+"-container"},this.props.children)):p},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-spin",spinning:!0},c.propTypes={className:h["default"].PropTypes.string,size:h["default"].PropTypes.oneOf(["small","default","large"])},p);t["default"]=C,e.exports=t["default"]},[460,446],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(374),i=r(a),s=o({placeholder:"\u8bf7\u9009\u62e9\u65f6\u95f4"},i["default"]);t["default"]=s,e.exports=t["default"]},[461,452],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.color,s=n.last,l=n.children,u=n.pending,c=n.className,p=n.dot,d=i(n,["prefixCls","color","last","children","pending","className","dot"]),y=(0,v["default"])((e={},a(e,r+"-item",!0),a(e,r+"-item-last",s),a(e,r+"-item-pending",u),a(e,c,c),e)),m=(0,v["default"])((t={},a(t,r+"-item-head",!0),a(t,r+"-item-head-custom",p),a(t,r+"-item-head-"+o,!0),t));return h["default"].createElement("li",f({},d,{className:y}),h["default"].createElement("div",{className:r+"-item-tail"}),h["default"].createElement("div",{className:m,style:{color:/blue|red|green/.test(o)?null:o}},p),h["default"].createElement("div",{className:r+"-item-content"},l))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-timeline",color:"blue",last:!1,pending:!1},p);t["default"]=m,e.exports=t["default"]},[460,454],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(6),h=r(d),y=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return n=r=i(this,e.call.apply(e,[this].concat(l))),r.handleChange=function(e){r.props.onChange(e)},r.handleClear=function(e){e.preventDefault(),r.props.handleClear(e)},o=n,i(r,o)}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.placeholder,n=e.value,r=e.prefixCls;return f["default"].createElement("div",null,f["default"].createElement("input",{placeholder:t,className:r+" ant-input",value:n,ref:"input",onChange:this.handleChange}),n&&n.length>0?f["default"].createElement("a",{href:"#",className:r+"-action",onClick:this.handleClear},f["default"].createElement(h["default"],{type:"cross-circle"})):f["default"].createElement("span",{className:r+"-action"},f["default"].createElement(h["default"],{type:"search"})))},t}(f["default"].Component),u.defaultProps={placeholder:"",onChange:l,handleClear:l},u.propTypes={prefixCls:p.PropTypes.string,placeholder:p.PropTypes.string,onChange:p.PropTypes.func,handleClear:p.PropTypes.func},c);t["default"]=y,e.exports=t["default"]},function(e,t,n){function r(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}try{var o=n(78)}catch(a){var o=n(78)}var i=/\s+/,s=Object.prototype.toString;e.exports=function(e){return new r(e)},r.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array(),n=o(t,e);return~n||t.push(e),this.el.className=t.join(" "),this},r.prototype.remove=function(e){if("[object RegExp]"==s.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=o(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},r.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n<t.length;n++)e.test(t[n])&&this.remove(t[n]);return this},r.prototype.toggle=function(e,t){return this.list?("undefined"!=typeof t?t!==this.list.toggle(e,t)&&this.list.toggle(e):this.list.toggle(e),this):("undefined"!=typeof t?t?this.add(e):this.remove(e):this.has(e)?this.remove(e):this.add(e),this)},r.prototype.array=function(){var e=this.el.getAttribute("class")||"",t=e.replace(/^\s+|\s+$/g,""),n=t.split(i);return""===n[0]&&n.shift(),n},r.prototype.has=r.prototype.contains=function(e){return this.list?this.list.contains(e):!!~o(this.array(),e)}},function(e,t){e.exports=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;n<e.length;++n)if(e[n]===t)return n;return-1}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.ownerDocument,n=t.body,r=void 0,o=i["default"].css(e,"position"),a="fixed"===o||"absolute"===o;if(!a)return"html"===e.nodeName.toLowerCase()?null:e.parentNode;for(r=e.parentNode;r&&r!==n;r=r.parentNode)if(o=i["default"].css(r,"position"),"static"!==o)return r;return null}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),r={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=r},function(e,t){"use strict";e.exports={eras:["\u516c\u5143\u524d","\u516c\u5143"],months:["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],shortMonths:["\u4e00\u6708","\u4e8c\u6708","\u4e09\u6708","\u56db\u6708","\u4e94\u6708","\u516d\u6708","\u4e03\u6708","\u516b\u6708","\u4e5d\u6708","\u5341\u6708","\u5341\u4e00\u6708","\u5341\u4e8c\u6708"],weekdays:["\u661f\u671f\u5929","\u661f\u671f\u4e00","\u661f\u671f\u4e8c","\u661f\u671f\u4e09","\u661f\u671f\u56db","\u661f\u671f\u4e94","\u661f\u671f\u516d"],shortWeekdays:["\u5468\u65e5","\u5468\u4e00","\u5468\u4e8c","\u5468\u4e09","\u5468\u56db","\u5468\u4e94","\u5468\u516d"],veryShortWeekdays:["\u65e5","\u4e00","\u4e8c","\u4e09","\u56db","\u4e94","\u516d"],ampms:["\u4e0a\u5348","\u4e0b\u5348"],datePatterns:["yyyy'\u5e74'M'\u6708'd'\u65e5' EEEE","yyyy'\u5e74'M'\u6708'd'\u65e5'","yyyy-M-d","yy-M-d"],timePatterns:["ahh'\u65f6'mm'\u5206'ss'\u79d2' 'GMT'Z","ahh'\u65f6'mm'\u5206'ss'\u79d2'","H:mm:ss","ah:mm"],dateTimePattern:"{date} {time}"}},function(e,t){"use strict";e.exports={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6,JANUARY:0,FEBRUARY:1,MARCH:2,APRIL:3,MAY:4,JUNE:5,JULY:6,AUGUST:7,SEPTEMBER:8,OCTOBER:9,NOVEMBER:10,DECEMBER:11}},function(e,t){"use strict";e.exports={timezoneOffset:-480,firstDayOfWeek:0,minimalDaysInFirstWeek:1}},function(e,t){"use strict";e.exports={timezoneOffset:480,firstDayOfWeek:1,minimalDaysInFirstWeek:1}},function(e,t,n){var r=n(417),o=function(e){var t=/[height|width]$/;return t.test(e)},a=function(e){var t="",n=Object.keys(e);return n.forEach(function(a,i){var s=e[a];a=r(a),o(a)&&"number"==typeof s&&(s+="px"),t+=s===!0?a:s===!1?"not "+a:"("+a+": "+s+")",i<n.length-1&&(t+=" and ")}),t},i=function(e){var t="";return"string"==typeof e?e:e instanceof Array?(e.forEach(function(n,r){t+=a(n),r<e.length-1&&(t+=", ")}),t):a(e)};e.exports=i},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={isAppearSupported:function(e){return e.transitionName&&e.transitionAppear||e.animation.appear},isEnterSupported:function(e){return e.transitionName&&e.transitionEnter||e.animation.enter},isLeaveSupported:function(e){return e.transitionName&&e.transitionLeave||e.animation.leave},allowAppearCallback:function(e){return e.transitionAppear||e.animation.appear},allowEnterCallback:function(e){return e.transitionEnter||e.animation.enter},allowLeaveCallback:function(e){return e.transitionLeave||e.animation.leave}};t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(96),s=r(i),l=n(43),u=r(l),c=n(30),p=r(c),f=n(24),d=r(f),h=a["default"].createClass({displayName:"MonthCalendar",mixins:[p["default"],u["default"]],onKeyDown:function(e){var t=e.keyCode,n=e.ctrlKey||e.metaKey,r=this.state.value,o=r;switch(t){case d["default"].DOWN:o=r.clone(),o.addMonth(3);break;case d["default"].UP:o=r.clone(),o.addMonth(-3);break;case d["default"].LEFT:o=r.clone(),n?o.addYear(-1):o.addMonth(-1);break;case d["default"].RIGHT:o=r.clone(),n?o.addYear(1):o.addMonth(1);break;case d["default"].ENTER:return this.onSelect(r),e.preventDefault(),1;default:return}if(o!==r)return this.setValue(o),e.preventDefault(),1},render:function(){var e=this.props,t=a["default"].createElement(s["default"],{locale:e.locale,disabledDate:e.disabledDate,style:{position:"relative"},value:this.state.value,rootPrefixCls:e.prefixCls,onChange:this.setValue,onSelect:this.onSelect});return this.renderRoot({children:t})}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(4),u=r(l),c=n(46),p=r(c),f=n(24),d=r(f),h=n(297),y=r(h),v=n(14),m=r(v),g=s["default"].createClass({displayName:"Picker",propTypes:{animation:i.PropTypes.oneOfType([i.PropTypes.func,i.PropTypes.string]),disabled:i.PropTypes.bool,transitionName:i.PropTypes.string,onChange:i.PropTypes.func,onOpen:i.PropTypes.func,onClose:i.PropTypes.func,children:i.PropTypes.func,getCalendarContainer:i.PropTypes.func,calendar:i.PropTypes.element,style:i.PropTypes.object,open:i.PropTypes.bool,defaultOpen:i.PropTypes.bool,prefixCls:i.PropTypes.string,placement:i.PropTypes.any,value:i.PropTypes.oneOfType([i.PropTypes.object,i.PropTypes.array]),defaultValue:i.PropTypes.oneOfType([i.PropTypes.object,i.PropTypes.array]),align:i.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-calendar-picker",style:{},align:{},placement:"bottomLeft",defaultOpen:!1,onChange:o,onOpen:o,onClose:o}},getInitialState:function(){var e=this.props,t=void 0;t="open"in e?e.open:e.defaultOpen;var n=e.value||e.defaultValue;return this.saveCalendarRef=a.bind(this,"calendarInstance"),{open:t,value:n}},componentWillReceiveProps:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})},onCalendarKeyDown:function(e){e.keyCode===d["default"].ESC&&(e.stopPropagation(),this.close(this.focus))},onCalendarSelect:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=this.props;"value"in n||this.setState({value:e}),(!n.calendar.props.timePicker&&"dateInput"!==t.source||"todayButton"===t.source)&&this.close(this.focus),n.onChange(e)},onCalendarOk:function(){this.close(this.focus)},onCalendarClear:function(){this.close(this.focus)},onVisibleChange:function(e){var t=this;this.setOpen(e,function(){e&&t.calendarInstance.focus()})},getCalendarElement:function(){var e=this.props,t=this.state,n=e.calendar,r=t.value,o=void 0;o=Array.isArray(r)?r[0]:r;var a={ref:this.saveCalendarRef,defaultValue:o||n.props.defaultValue,defaultSelectedValue:r,onKeyDown:this.onCalendarKeyDown,onOk:(0,p["default"])(n.props.onOk,this.onCalendarOk),onSelect:(0,p["default"])(n.props.onSelect,this.onCalendarSelect),onClear:(0,p["default"])(n.props.onClear,this.onCalendarClear)};return s["default"].cloneElement(n,a)},setOpen:function(e,t){var n=this.props,r=n.onOpen,o=n.onClose;if(this.state.open!==e){this.setState({open:e},t);var a={open:e};e?r(a):o(a)}},open:function(e){this.setOpen(!0,e)},close:function(e){this.setOpen(!1,e)},focus:function(){this.state.open||u["default"].findDOMNode(this).focus()},render:function(){var e=this.props,t=e.prefixCls,n=e.placement,r=e.style,o=e.getCalendarContainer,a=e.align,i=e.animation,l=e.disabled,u=e.transitionName,c=e.children,p=this.state;return s["default"].createElement(m["default"],{popup:this.getCalendarElement(),popupAlign:a,builtinPlacements:y["default"],popupPlacement:n,action:l&&!p.open?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:o,popupStyle:r,popupAnimation:i,popupTransitionName:u,popupVisible:p.open,onPopupVisibleChange:this.onVisibleChange,prefixCls:t},c(p,e))}});t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=this.props.value.clone();t.addMonth(e),this.props.onValueChange(t)}function a(e){var t=this.props.value.clone();t.addYear(e),this.props.onValueChange(t)}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(96),u=r(l),c=n(12),p=n(98),f=r(p),d=n(45),h=r(d),y=s["default"].createClass({displayName:"CalendarHeader",propTypes:{enablePrev:i.PropTypes.any,enableNext:i.PropTypes.any,prefixCls:i.PropTypes.string,locale:i.PropTypes.object,value:i.PropTypes.object,onValueChange:i.PropTypes.func},getDefaultProps:function(){return{enableNext:1,enablePrev:1}},getInitialState:function(){var e=this.props;return this.yearFormatter=(0,c.getFormatter)(e.locale.yearFormat,e.locale),this.monthFormatter=(0,c.getFormatter)(e.locale.monthFormat,e.locale),this.nextMonth=o.bind(this,1),this.previousMonth=o.bind(this,-1),this.nextYear=a.bind(this,1),this.previousYear=a.bind(this,-1),{}},componentWillReceiveProps:function(e){var t=this.props.locale,n=e.locale;n!==t&&(this.yearFormatter=(0,c.getFormatter)(n.yearFormat,n),this.monthFormatter=(0,c.getFormatter)(n.monthFormat,n))},onSelect:function(e){this.setState({showMonthPanel:0,showYearPanel:0}),this.props.onValueChange(e)},getMonthYearElement:function(){var e=this.props,t=e.prefixCls,n=e.locale,r=this.props.value,o=n.monthBeforeYear,a=t+"-"+(o?"my-select":"ym-select"),i=s["default"].createElement("a",{className:t+"-year-select",role:"button",onClick:this.showYearPanel,title:n.monthSelect},this.yearFormatter.format(r)),l=s["default"].createElement("a",{className:t+"-month-select",role:"button",onClick:this.showMonthPanel,title:n.monthSelect},this.monthFormatter.format(r)),u=[];return u=o?[l,i]:[i,l],s["default"].createElement("span",{className:a},(0,h["default"])(u))},showIf:function(e,t){return e?t:null},showMonthPanel:function(){this.setState({showMonthPanel:1,showYearPanel:0})},showYearPanel:function(){this.setState({showMonthPanel:0,showYearPanel:1})},render:function(){var e=this.props,t=e.enableNext,n=e.enablePrev,r=e.prefixCls,o=e.locale,a=e.value,i=this.state,l=null;i.showMonthPanel?l=u["default"]:i.showYearPanel&&(l=f["default"]);var c=void 0;return l&&(c=s["default"].createElement(l,{locale:o,defaultValue:a,rootPrefixCls:r,onSelect:this.onSelect})),s["default"].createElement("div",{className:r+"-header"},s["default"].createElement("div",{style:{position:"relative"}},this.showIf(n,s["default"].createElement("a",{className:r+"-prev-year-btn",role:"button",onClick:this.previousYear,title:o.previousYear},"\xab")),this.showIf(n,s["default"].createElement("a",{className:r+"-prev-month-btn",role:"button",onClick:this.previousMonth,title:o.previousMonth},"\u2039")),this.getMonthYearElement(),this.showIf(t,s["default"].createElement("a",{className:r+"-next-month-btn",onClick:this.nextMonth,title:o.nextMonth},"\u203a")),this.showIf(t,s["default"].createElement("a",{className:r+"-next-year-btn",onClick:this.nextYear,title:o.nextYear},"\xbb"))),c)}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.prefixCls,n=e.locale,r=e.okDisabled,o=e.onOk,a=t+"-ok-btn";return r&&(a+=" "+t+"-ok-btn-disabled"),i["default"].createElement("a",{className:a,role:"button",onClick:r?null:o},n.ok)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var a=n(1),i=r(a);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e.prefixCls,n=e.locale,r=e.value,o=e.timePicker,a=e.disabledDate,l=e.disabledTime,u=e.onToday,c=e.text,p=!1,f=c;!f&&o&&(f=n.now),f=f||n.today;var d="";return a&&(p=!(0,s.isAllowedDate)((0,s.getTodayTime)(r),a,l),p&&(d=t+"-today-btn-disabled")),i["default"].createElement("a",{className:t+"-today-btn "+d,role:"button",onClick:p?null:u,title:(0,s.getTodayTimeStr)(r)},f)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var a=n(1),i=r(a),s=n(12);e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={DATE_ROW_COUNT:6,DATE_COL_COUNT:7},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return t&&(e.setHourOfDay(t.getHourOfDay()),e.setMinutes(t.getMinutes()),e.setSeconds(t.getSeconds())),e}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),s=r(i),l=n(4),u=r(l),c=n(12),p=s["default"].createClass({displayName:"DateInput",propTypes:{prefixCls:i.PropTypes.string,timePicker:i.PropTypes.object,disabledTime:i.PropTypes.any,formatter:i.PropTypes.object,locale:i.PropTypes.object,gregorianCalendarLocale:i.PropTypes.object,disabledDate:i.PropTypes.func,onChange:i.PropTypes.func,onClear:i.PropTypes.func,placeholder:i.PropTypes.string,onSelect:i.PropTypes.func,selectedValue:i.PropTypes.object},getInitialState:function(){var e=this.props.selectedValue;return{str:e&&this.props.formatter.format(e)||"",invalid:!1}},componentWillReceiveProps:function(e){var t=e.selectedValue;this.setState({str:t&&e.formatter.format(t)||"",invalid:!1})},onInputChange:function(e){var t=e.target.value;this.setState({str:t});var n=void 0,r=this.props,a=r.disabledDate,i=r.formatter,s=r.gregorianCalendarLocale,l=r.onChange;if(t){try{n=o(i.parse(t,{locale:s,obeyCount:!0}),this.props.selectedValue)}catch(u){return void this.setState({invalid:!0})}if(!n||a&&a(n))return void this.setState({invalid:!0});var c=this.props.selectedValue;c&&n?c.getTime()!==n.getTime()&&l(n):c!==n&&l(n)}else l(null);this.setState({invalid:!1})},onClear:function(){this.setState({str:""}),this.props.onClear(null)},getRootDOMNode:function(){return u["default"].findDOMNode(this)},focus:function(){this.refs.dateInput.focus()},render:function(){var e=this.props,t=this.state,n=t.invalid,r=t.str,o=e.selectedValue,i=e.locale,l=e.prefixCls,u=e.placeholder,p=e.onChange,f=e.timePicker,d=e.disabledTime,h=e.gregorianCalendarLocale,y=n?l+"-input-invalid":"",v=d&&f?(0,c.getTimeConfig)(o,d):null;return s["default"].createElement("div",{className:l+"-input-wrap"},s["default"].createElement("div",{className:l+"-time-picker-wrap"},f?s["default"].cloneElement(f,a({showClear:!1,allowEmpty:!1,getPopupContainer:this.getRootDOMNode,gregorianCalendarLocale:h,value:o,onChange:p},v)):null),s["default"].createElement("div",{className:l+"-date-input-wrap"},s["default"].createElement("input",{ref:"dateInput",className:l+"-input "+y,value:r,placeholder:u,onChange:this.onInputChange})),e.showClear?s["default"].createElement("a",{className:l+"-clear-btn",role:"button",title:i.clear,onClick:this.onClear}):null)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(288),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(81),a=r(o);t["default"]={today:"\u4eca\u5929",now:"\u6b64\u523b",backToToday:"\u8fd4\u56de\u4eca\u5929",ok:"\u786e\u5b9a",clear:"\u6e05\u9664",month:"\u6708",year:"\u5e74",previousMonth:"\u4e0a\u4e2a\u6708 (\u7ffb\u9875\u4e0a\u952e)",nextMonth:"\u4e0b\u4e2a\u6708 (\u7ffb\u9875\u4e0b\u952e)",monthSelect:"\u9009\u62e9\u6708\u4efd",yearSelect:"\u9009\u62e9\u5e74\u4efd",decadeSelect:"\u9009\u62e9\u5e74\u4ee3",yearFormat:"yyyy'\u5e74'",monthFormat:"M'\u6708'",dateFormat:"yyyy'\u5e74'M'\u6708'd'\u65e5'",previousYear:"\u4e0a\u4e00\u5e74 (Control\u952e\u52a0\u5de6\u65b9\u5411\u952e)",nextYear:"\u4e0b\u4e00\u5e74 (Control\u952e\u52a0\u53f3\u65b9\u5411\u952e)",previousDecade:"\u4e0a\u4e00\u5e74\u4ee3",nextDecade:"\u4e0b\u4e00\u5e74\u4ee3",previousCentury:"\u4e0a\u4e00\u4e16\u7eaa",nextCentury:"\u4e0b\u4e00\u4e16\u7eaa",format:a["default"]},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=this.state.value.clone();t.addYear(e),this.setAndChangeValue(t)}function a(){}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(98),u=r(l),c=n(97),p=r(c),f=s["default"].createClass({displayName:"MonthPanel",propTypes:{onChange:i.PropTypes.func,disabledDate:i.PropTypes.func,onSelect:i.PropTypes.func},getDefaultProps:function(){return{onChange:a,onSelect:a}},getInitialState:function(){var e=this.props;return this.nextYear=o.bind(this,1),this.previousYear=o.bind(this,-1),this.prefixCls=e.rootPrefixCls+"-month-panel",{value:e.value||e.defaultValue}},componentWillReceiveProps:function(e){"value"in e&&this.setState({value:e.value})},onYearPanelSelect:function(e){this.setState({showYearPanel:0}),this.setAndChangeValue(e)},setAndChangeValue:function(e){this.setValue(e),this.props.onChange(e)},setAndSelectValue:function(e){this.setValue(e),this.props.onSelect(e)},setValue:function(e){"value"in this.props||this.setState({value:e})},showYearPanel:function(){this.setState({showYearPanel:1})},render:function(){var e=this.props,t=this.state.value,n=e.locale,r=t.getYear(),o=this.prefixCls,a=void 0;return this.state.showYearPanel&&(a=s["default"].createElement(u["default"],{locale:n,value:t,rootPrefixCls:e.rootPrefixCls,onSelect:this.onYearPanelSelect})),s["default"].createElement("div",{className:o,style:e.style},s["default"].createElement("div",null,s["default"].createElement("div",{className:o+"-header"},s["default"].createElement("a",{className:o+"-prev-year-btn",role:"button",onClick:this.previousYear,title:n.previousYear},"\xab"),s["default"].createElement("a",{className:o+"-year-select",role:"button",onClick:this.showYearPanel,title:n.yearSelect},s["default"].createElement("span",{className:o+"-year-select-content"},r),s["default"].createElement("span",{className:o+"-year-select-arrow"},"x")),s["default"].createElement("a",{className:o+"-next-year-btn",role:"button",onClick:this.nextYear,title:n.nextYear},"\xbb")),s["default"].createElement("div",{className:o+"-body"},s["default"].createElement(p["default"],{disabledDate:e.disabledDate,onSelect:this.setAndSelectValue,locale:n,value:t,prefixCls:o}))),a)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function u(e){var t=this.state.value.clone();t.rollSetMonth(e),this.setAndSelectValue(t)}function c(){}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(2),h=r(d),y=4,v=3,m=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.state={value:n.value},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value})},t.prototype.getMonths=function(){for(var e=this.props,t=this.state.value,n=t.clone(),r=e.locale,o=[],a=r.format.shortMonths,i=0,s=0;s<y;s++){o[s]=[];for(var l=0;l<v;l++)n.rollSetMonth(i),o[s][l]={value:i,content:a[i],title:a[i]},i++}return o},t.prototype.setAndSelectValue=function(e){this.setState({value:e}),this.props.onSelect(e)},t.prototype.render=function(){var e=this,t=this.props,n=this.state.value,r=n.clone();r.setTime(Date.now());var o=this.getMonths(),i=n.getMonth(),s=t.prefixCls,l=t.locale,c=t.contentRender,p=t.cellRender,d=o.map(function(o,d){var y=o.map(function(o){var d,y=!1;if(t.disabledDate){var v=n.clone();v.rollSetMonth(o.value),y=t.disabledDate(v)}var m=(d={},a(d,s+"-cell",1),a(d,s+"-cell-disabled",y),a(d,s+"-selected-cell",o.value===i),a(d,s+"-current-cell",r.getYear()===n.getYear()&&o.value===r.getMonth()),d),g=void 0;if(p){var b=n.clone();b.rollSetMonth(o.value),g=p(b,l)}else{var P=void 0;if(c){var O=n.clone();O.rollSetMonth(o.value),P=c(O,l)}else P=o.content;g=f["default"].createElement("div",{className:s+"-month"},P)}return f["default"].createElement("td",{role:"gridcell",key:o.value,onClick:y?null:u.bind(e,o.value),title:o.title,className:(0,h["default"])(m)},g)});return f["default"].createElement("tr",{key:d,role:"row"},y)});return f["default"].createElement("table",{className:s+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:s+"-tbody"},d))},t}(p.Component);m.defaultProps={onSelect:c},m.propTypes={onSelect:p.PropTypes.func,cellRender:p.PropTypes.func,prefixCls:p.PropTypes.string,value:p.PropTypes.object},t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function u(e){var t=this.state.value.clone();t.addYear(e),this.setState({value:t})}function c(e){var t=this.state.value.clone();t.setYear(e),t.rollSetMonth(this.state.value.getMonth()),this.props.onSelect(t)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(2),h=r(d),y=n(294),v=r(y),m=4,g=3,b=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.prefixCls=n.rootPrefixCls+"-year-panel",r.state={value:n.value||n.defaultValue},r.nextDecade=u.bind(r,10),r.previousDecade=u.bind(r,-10),["showDecadePanel","onDecadePanelSelect"].forEach(function(e){r[e]=r[e].bind(r)}),r}return l(t,e),t.prototype.onDecadePanelSelect=function(e){this.setState({value:e,showDecadePanel:0})},t.prototype.getYears=function(){for(var e=this.state.value,t=e.getYear(),n=10*parseInt(t/10,10),r=n-1,o=n+9,a=[],i=0,s=0;s<m;s++){a[s]=[];for(var l=0;l<g;l++){var u=r+i,c=void 0;c=u<n?"":u>o?"":String(u),a[s][l]={content:c,year:u,title:c},i++}}return a},t.prototype.showDecadePanel=function(){this.setState({showDecadePanel:1})},t.prototype.render=function(){var e=this,t=this.props,n=this.state.value,r=t.locale,o=this.getYears(),i=n.getYear(),s=10*parseInt(i/10,10),l=s+9,u=this.prefixCls,p=o.map(function(t,n){var r=t.map(function(t){var n,r=(n={},a(n,u+"-cell",1),a(n,u+"-selected-cell",t.year===i),a(n,u+"-last-decade-cell",t.year<s),a(n,u+"-next-decade-cell",t.year>l),n),o=void 0;return o=t.year<s?e.previousDecade:t.year>l?e.nextDecade:c.bind(e,t.year),f["default"].createElement("td",{role:"gridcell",title:t.title,key:t.content,onClick:o,className:(0,h["default"])(r)},f["default"].createElement("a",{ className:u+"-year"},t.content))});return f["default"].createElement("tr",{key:n,role:"row"},r)}),d=void 0;return this.state.showDecadePanel&&(d=f["default"].createElement(v["default"],{locale:r,value:n,rootPrefixCls:t.rootPrefixCls,onSelect:this.onDecadePanelSelect})),f["default"].createElement("div",{className:this.prefixCls},f["default"].createElement("div",null,f["default"].createElement("div",{className:u+"-header"},f["default"].createElement("a",{className:u+"-prev-decade-btn",role:"button",onClick:this.previousDecade,title:r.previousDecade},"\xab"),f["default"].createElement("a",{className:u+"-decade-select",role:"button",onClick:this.showDecadePanel,title:r.decadeSelect},f["default"].createElement("span",{className:u+"-decade-select-content"},s,"-",l),f["default"].createElement("span",{className:u+"-decade-select-arrow"},"x")),f["default"].createElement("a",{className:u+"-next-decade-btn",role:"button",onClick:this.nextDecade,title:r.nextDecade},"\xbb")),f["default"].createElement("div",{className:u+"-body"},f["default"].createElement("table",{className:u+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:u+"-tbody"},p)))),d)},t}(f["default"].Component);t["default"]=b,b.propTypes={rootPrefixCls:p.PropTypes.string,value:p.PropTypes.object,defaultValue:p.PropTypes.object},b.defaultProps={onSelect:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(302)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){function e(e){var t=l["default"].createClass({displayName:"Form",mixins:n,getInitialState:function(){var e=void 0;return r&&(e=r(this.props)),this.fields=e||{},this.instances={},this.fieldsMeta={},this.cachedBind={},{submitting:!1}},componentWillReceiveProps:function(e){r&&(this.fields=r(e))},onChange:function(e,t){for(var n=e,r=this.getFieldMeta(n),a=r.validate,s=arguments.length,l=Array(s>2?s-2:0),c=2;c<s;c++)l[c-2]=arguments[c];r[t]&&r[t].apply(r,l);var p=r.getValueFromEvent?r.getValueFromEvent.apply(r,l):u.getValueFromEvent.apply(void 0,l),f=void 0,d=(0,u.getNameKeyObj)(n);this.getFieldMeta(d.name).exclusive&&(n=d.name);var h=this.getField(n);f=i({},h,{value:p,dirty:(0,u.hasRules)(a)}),this.setFields(o({},n,f))},onChangeValidate:function(e,t){for(var n=e,r=this.getFieldMeta(n),o=arguments.length,a=Array(o>2?o-2:0),i=2;i<o;i++)a[i-2]=arguments[i];r[t]&&r[t].apply(r,a);var s=r.getValueFromEvent?r.getValueFromEvent.apply(r,a):u.getValueFromEvent.apply(void 0,a),l=(0,u.getNameKeyObj)(n);this.getFieldMeta(l.name).exclusive&&(n=l.name);var c=this.getField(n);c.value=s,c.dirty=!0,this.validateFieldsInternal([c],{action:t,options:{firstFields:!!r.validateFirst}})},getCacheBind:function(e,t,n){var r=this.cachedBind[e]=this.cachedBind[e]||{};return r[t]||(r[t]=n.bind(this,e,t)),r[t]},getFieldMeta:function(e){return this.fieldsMeta[e]},getField:function(e){var t=this.fields;return i({},t[e],{name:e})},getFieldProps:function(e){function t(e){return e.trigger.indexOf(l)===-1||!e.rules||!e.rules.length}var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];if(!e)throw new Error("must call getFieldProps with valid name string!");var o=r.rules,a=r.trigger,l=void 0===a?d:a,p=r.valuePropName,y=void 0===p?"value":p,v=r.getValueProps,m=r.exclusive,g=r.validateTrigger,b=void 0===g?f:g,P=r.validate,O=void 0===P?[]:P,C=(0,u.getNameKeyObj)(e),T=C.name,w=C.key,x=this.fieldsMeta,E=void 0,S=x[T];w?(S=x[T]=x[T]||{},S.virtual=!m,S.hidden=!m,S.exclusive=m,E=x[e]=x[e]||{}):E=x[e]=x[e]||{},"initialValue"in r&&(E.initialValue=r.initialValue);var k={};w&&(k.key=w),s&&(k[s]=e);var j=O.map(function(e){var t=i({},e,{trigger:e.trigger||[]});return"string"==typeof t.trigger&&(t.trigger=[t.trigger]),t});o&&j.push({trigger:b?[].concat(b):[],rules:o}),j.filter(function(e){return!!e.rules&&e.rules.length}).map(function(e){return e.trigger}).reduce(function(e,t){return e.concat(t)},[]).forEach(function(t){k[t]=n.getCacheBind(e,t,n.onChangeValidate)}),l&&j.every(t)&&(k[l]=this.getCacheBind(e,l,this.onChange));var _=m?this.getField(T):this.getField(e),N=h;_&&"value"in _&&(N=_.value),N===h&&(N=m?x[T].initialValue:E.initialValue),v?k=i({},k,v(N)):k[y]=N,k.ref=this.getCacheBind(e,e+"__ref",this.saveRef);var M=i({},E,r,{validate:j});return x[e]=M,c&&(k[c]=M),k},getFieldMember:function(e,t){var n=this.getField(e);return n&&n[t]},getFieldError:function(e){return(0,u.getErrorStrs)(this.getFieldMember(e,"errors"))},getValidFieldsName:function(){var e=this.fieldsMeta;return e?Object.keys(e).filter(function(t){return!e[t].hidden}):[]},getFieldsValue:function(e){var t=this,n=e||(0,u.flatFieldNames)(this.getValidFieldsName()),r={};return n.forEach(function(e){r[e]=t.getFieldValue(e)}),r},getFieldValue:function(e){var t=this.fields;return this.getValueFromFields(e,t)},getFieldInstance:function(e){return this.instances[e]},getValueFromFieldsInternal:function(e,t){var n=t[e];if(n&&"value"in n)return n.value;var r=this.fieldsMeta[e];return r&&r.initialValue},getValueFromFields:function(e,t){var n=this.fieldsMeta;if(n[e]&&n[e].virtual){var r={};for(var o in n)if(n.hasOwnProperty(o)){var a=(0,u.getNameKeyObj)(o);a.name===e&&a.key&&(r[a.key]=this.getValueFromFieldsInternal(o,t))}return r}return this.getValueFromFieldsInternal(e,t)},getRules:function(e,t){var n=e.validate.filter(function(e){return!t||e.trigger.indexOf(t)>=0}).map(function(e){return e.rules});return(0,u.flattenArray)(n)},setFields:function(e){var t=this,n=this.fieldsMeta,r=e,o=i({},this.fields,r),s={};Object.keys(n).forEach(function(e){var r=(0,u.getNameKeyObj)(e),a=r.name,i=r.key;i&&n[a].exclusive||(s[e]=t.getValueFromFields(e,o))});var l=Object.keys(r);Object.keys(s).forEach(function(e){var r=s[e],a=n[e];if(a&&a.normalize){var l=a.normalize(r,t.getValueFromFields(e,t.fields),s);l!==r&&(o[e]=i({},o[e],{value:l}))}}),this.fields=o,a&&!function(){var e={};l.forEach(function(n){e[n]=t.getField(n)}),a(t.props,e)}(),this.forceUpdate()},setFieldsValue:function(e){var t={},n=this.fieldsMeta,r=this.fields;for(var o in e)if(e.hasOwnProperty(o)){var a=e[o];if(n[o]&&n[o].virtual){(0,u.clearVirtualField)(o,r,n);for(var i in a)a.hasOwnProperty(i)&&(t[(0,u.getNameKeyStr)(o,i)]=a[i])}else t[o]={name:o,value:a}}this.setFields(t)},setFieldsInitialValue:function(e){var t=this.fieldsMeta;for(var n in e)if(e.hasOwnProperty(n)){var r=t[n];t[n]=i({},r,{initialValue:e[n]})}},saveRef:function(e,t,n){if(!n)return delete this.fieldsMeta[e],delete this.fields[e],delete this.instances[e],void delete this.cachedBind[e];var r=this.getFieldMeta(e);if(r&&r.ref){if("string"==typeof r.ref)throw new Error("can not set ref string for "+e);r.ref(n)}this.instances[e]=n},validateFieldsInternal:function(e,t,n){var r=this,o=t.fieldNames,a=t.action,s=t.options,l=void 0===s?{}:s,c={},f={},d={},h={};if(e.forEach(function(e){var t=e.name;if(l.force!==!0&&e.dirty===!1)return void(e.errors&&(h[t]={errors:e.errors}));var n=r.getFieldMeta(t),o=i({},e);o.errors=void 0,o.validating=!0,o.dirty=!0,c[t]=r.getRules(n,a),f[t]=o.value,d[t]=o}),this.setFields(d),Object.keys(f).forEach(function(e){f[e]=r.getFieldValue(e)}),n&&(0,u.isEmptyObject)(d))return void n((0,u.isEmptyObject)(h)?null:h,this.getFieldsValue((0,u.flatFieldNames)(o)));var v=new p["default"](c);y&&v.messages(y),v.validate(f,l,function(e){var t=i({},h);e&&e.length&&e.forEach(function(e){var n=e.field;t[n]||(t[n]={errors:[]});var r=t[n].errors;r.push(e)});var a=[],s={};Object.keys(c).forEach(function(e){var n=t[e],o=r.getField(e);o.value!==f[e]?a.push({name:e}):(o.errors=n&&n.errors,o.value=f[e],o.validating=!1,o.dirty=!1,s[e]=o)}),r.setFields(s),n&&(a.length&&a.forEach(function(e){var n=e.name,r=[{message:n+" need to revalidate",field:n}];t[n]={expired:!0,errors:r}}),n((0,u.isEmptyObject)(t)?null:t,r.getFieldsValue((0,u.flatFieldNames)(o))))})},validateFields:function(e,t,n){var r=this,o=(0,u.getParams)(e,t,n),a=o.names,i=o.callback,s=o.options,l=a||this.getValidFieldsName(),c=l.map(function(e){var t=r.getFieldMeta(e);if(!(0,u.hasRules)(t.validate))return null;var n=r.getField(e);return n.value=r.getFieldValue(e),n}).filter(function(e){return!!e});return c.length?("firstFields"in s||(s.firstFields=l.filter(function(e){var t=r.getFieldMeta(e);return!!t.validateFirst})),void this.validateFieldsInternal(c,{fieldNames:l,options:s},i)):void(i&&i(null,this.getFieldsValue((0,u.flatFieldNames)(l))))},isFieldValidating:function(e){return this.getFieldMember(e,"validating")},isFieldsValidating:function(e){var t=this,n=e||this.getValidFieldsName();return n.some(function(e){return t.isFieldValidating(e)})},isSubmitting:function(){return this.state.submitting},submit:function(e){var t=this,n=function(){t.setState({submitting:!1})};this.setState({submitting:!0}),e(n)},resetFields:function(e){var t={},n=this.fields,r=!1,o=e||Object.keys(n);o.forEach(function(e){var o=n[e];o&&"value"in o&&(r=!0,t[e]={})}),r&&this.setFields(t)},render:function(){var t=o({},b,this.getForm());P&&(t.ref="wrappedComponent");var n=m.call(this,i({},t,this.props));return l["default"].createElement(e,n)}});return(0,u.argumentContainer)(t,e)}var t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1],r=t.mapPropsToFields,a=t.onFieldsChange,s=t.fieldNameProp,c=t.fieldMetaProp,y=t.validateMessages,v=t.mapProps,m=void 0===v?u.mirror:v,g=t.formPropName,b=void 0===g?"form":g,P=t.withRef;return e}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(101),c=n(129),p=r(c),f="onChange",d=f,h={};t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return e.displayName||e.name||"WrappedComponent"}function a(e,t){return e.displayName="Form("+o(t)+")",e.WrappedComponent=t,(0,O["default"])(e,t)}function i(e){if(!e||!e.target)return e;var t=e.target;return"checkbox"===t.type?t.checked:t.value}function s(e){return e?e.map(function(e){return e&&e.message?e.message:e}):e}function l(e){return 0===Object.keys(e).length}function u(e){return Array.prototype.concat.apply([],e)}function c(e){return e}function p(e){return!!e&&e.some(function(e){return!!e.rules&&e.rules.length})}function f(e,t){return 0===e.lastIndexOf(t,0)}function d(e,t,n){var r=e,o=n,a=t;return void 0===n&&("function"==typeof r?(o=r,a={},r=void 0):Array.isArray(e)?"function"==typeof a?(o=a,a={}):a=a||{}:(o=a,a=r||{},r=void 0)),{names:r,callback:o,options:a}}function h(e,t){return t?""+e+C+t:e}function y(e){var t=e.indexOf(C);if(e.indexOf(C)!==-1){var n=e.slice(0,t),r=e.slice(t+C.length);return{name:n,key:r}}return{name:e}}function v(e,t){var n=b({},e);return Object.keys(n).forEach(function(e){if(t[e]&&t[e].virtual){var r=n[e];for(var o in r)r.hasOwnProperty(o)&&(n[h(e,o)]=r[o]);delete n[e]}}),n}function m(e){var t={};return e.forEach(function(e){t[y(e).name]=1}),Object.keys(t)}function g(e,t,n){n[e]&&n[e].virtual&&Object.keys(t).forEach(function(n){y(n).name===e&&delete t[n]})}Object.defineProperty(t,"__esModule",{value:!0});var b=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.argumentContainer=a,t.getValueFromEvent=i,t.getErrorStrs=s,t.isEmptyObject=l,t.flattenArray=u,t.mirror=c,t.hasRules=p,t.startsWith=f,t.getParams=d,t.getNameKeyStr=h,t.getNameKeyObj=y,t.flatFields=v,t.flatFieldNames=m,t.clearVirtualField=g;var P=n(269),O=r(P),C="."},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){return!e.length||e.every(function(e){return!!e.props.disabled})}function i(e,t){var n=t,r=e.children,o=e.eventKey;if(n){var a=void 0;if((0,P.loopMenuItem)(r,function(e,t){e.props.disabled||n!==(0,P.getKeyFromChildrenIndex)(e,o,t)||(a=!0)}),a)return n}return n=null,e.defaultActiveFirst?((0,P.loopMenuItem)(r,function(e,t){n||e.props.disabled||(n=(0,P.getKeyFromChildrenIndex)(e,o,t))}),n):n}function s(e,t,n){n&&(void 0!==t?(this.instanceArray[e]=this.instanceArray[e]||[],this.instanceArray[e][t]=n):this.instanceArray[e]=n)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),c=r(u),p=n(4),f=r(p),d=n(11),h=n(2),y=r(h),v=n(40),m=r(v),g=n(10),b=r(g),P=n(22),O=n(319),C=r(O),T={propTypes:{focusable:u.PropTypes.bool,multiple:u.PropTypes.bool,style:u.PropTypes.object,defaultActiveFirst:u.PropTypes.bool,visible:u.PropTypes.bool,activeKey:u.PropTypes.string,selectedKeys:u.PropTypes.arrayOf(u.PropTypes.string),defaultSelectedKeys:u.PropTypes.arrayOf(u.PropTypes.string),defaultOpenKeys:u.PropTypes.arrayOf(u.PropTypes.string),openKeys:u.PropTypes.arrayOf(u.PropTypes.string),children:u.PropTypes.any},getDefaultProps:function(){return{prefixCls:"rc-menu",className:"",mode:"vertical",level:1,inlineIndent:24,visible:!0,focusable:!0,style:{}}},getInitialState:function(){var e=this.props;return{activeKey:i(e,e.activeKey)}},componentWillReceiveProps:function(e){var t=void 0;if("activeKey"in e)t={activeKey:i(e,e.activeKey)};else{var n=this.state.activeKey,r=i(e,n);r!==n&&(t={activeKey:r})}t&&this.setState(t)},shouldComponentUpdate:function(e){return this.props.visible||e.visible},componentWillMount:function(){this.instanceArray=[]},onKeyDown:function(e){var t=this,n=e.keyCode,r=void 0;if(this.getFlatInstanceArray().forEach(function(t){t&&t.props.active&&(r=t.onKeyDown(e))}),r)return 1;var o=null;return n!==d.KeyCode.UP&&n!==d.KeyCode.DOWN||(o=this.step(n===d.KeyCode.UP?-1:1)),o?(e.preventDefault(),this.setState({activeKey:o.props.eventKey},function(){(0,m["default"])(f["default"].findDOMNode(o),f["default"].findDOMNode(t),{onlyScrollIfNeeded:!0})}),1):void 0===o?(e.preventDefault(),this.setState({activeKey:null}),1):void 0},onCommonItemHover:function(e){var t=this.props.mode,n=e.key,r=e.hover,o=e.trigger,a=this.state.activeKey;if(o&&!r&&!this.props.closeSubMenuOnMouseLeave&&e.item.isSubMenu&&"inline"!==t||this.setState({activeKey:r?n:null}),r&&"inline"!==t){var i=this.getFlatInstanceArray().filter(function(e){return e&&e.props.eventKey===a})[0];i&&i.isSubMenu&&i.props.eventKey!==n&&this.onOpenChange({item:i,key:i.props.eventKey,open:!1})}},getFlatInstanceArray:function(){var e=this.instanceArray,t=e.some(function(e){return Array.isArray(e)});return t&&(e=[],this.instanceArray.forEach(function(t){Array.isArray(t)?e.push.apply(e,t):e.push(t)}),this.instanceArray=e),e},renderCommonMenuItem:function(e,t,n,r){var o=this.state,a=this.props,i=(0,P.getKeyFromChildrenIndex)(e,a.eventKey,t),l=e.props,u=i===o.activeKey,p=(0,b["default"])({mode:a.mode,level:a.level,inlineIndent:a.inlineIndent,renderMenuItem:this.renderMenuItem,rootPrefixCls:a.prefixCls,index:t,parentMenu:this,ref:l.disabled?void 0:(0,d.createChainedFunction)(e.ref,s.bind(this,t,n)),eventKey:i,closeSubMenuOnMouseLeave:a.closeSubMenuOnMouseLeave,onItemHover:this.onItemHover,active:!l.disabled&&u,multiple:a.multiple,onClick:this.onClick,openTransitionName:this.getOpenTransitionName(),openAnimation:a.openAnimation,onOpenChange:this.onOpenChange,onDeselect:this.onDeselect,onDestroy:this.onDestroy,onSelect:this.onSelect},r);return"inline"===a.mode&&(p.closeSubMenuOnMouseLeave=p.openSubMenuOnMouseEnter=!1),c["default"].cloneElement(e,p)},renderRoot:function(e){var t;this.instanceArray=[];var n=(t={},o(t,e.prefixCls,1),o(t,e.prefixCls+"-"+e.mode,1),o(t,e.className,!!e.className),t),r={className:(0,y["default"])(n),role:"menu","aria-activedescendant":""};return e.id&&(r.id=e.id),e.focusable&&(r.tabIndex="0",r.onKeyDown=this.onKeyDown),c["default"].createElement(C["default"],l({style:e.style,tag:"ul",hiddenClassName:e.prefixCls+"-hidden",visible:e.visible},r),c["default"].Children.map(e.children,this.renderMenuItem))},step:function(e){var t=this.getFlatInstanceArray(),n=this.state.activeKey,r=t.length;if(!r)return null;e<0&&(t=t.concat().reverse());var o=-1;if(t.every(function(e,t){return!e||e.props.eventKey!==n||(o=t,!1)}),this.props.defaultActiveFirst||o===-1||!a(t.slice(o,r-1)))for(var i=(o+1)%r,s=i;;){var l=t[s];if(l&&!l.props.disabled)return l;if(s=(s+1+r)%r,s===i)return null}}};t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(328),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t){"use strict";e.exports={ZERO:48,NINE:57,NUMPAD_ZERO:96,NUMPAD_NINE:105,BACKSPACE:8,DELETE:46,ENTER:13,ARROW_UP:38,ARROW_DOWN:40}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={items_per_page:"\u6761/\u9875",jump_to:"\u8df3\u81f3",page:"\u9875",first_page:"\u7b2c\u4e00\u9875",last_page:"\u6700\u540e\u4e00\u9875",prev_page:"\u4e0a\u4e00\u9875",next_page:"\u4e0b\u4e00\u9875",prev_5:"\u5411\u524d 5 \u9875",next_5:"\u5411\u540e 5 \u9875"},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t}(u["default"].Component);t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"TabPane",propTypes:{active:a.PropTypes.bool},render:function(){var e,t=this.props;if(this._isActived=this._isActived||t.active,!this._isActived)return null;var n=t.rootPrefixCls+"-tabpane",r=(0,l["default"])((e={},o(e,n+"-hidden",!t.active),o(e,n,1),e));return i["default"].createElement("div",{role:"tabpanel","aria-hidden":t.active?"false":"true",className:r},t.children)}});t["default"]=u,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function r(e){var t=void 0,r=void 0,o=void 0,a=e.ownerDocument,i=a.body,s=a&&a.documentElement;t=e.getBoundingClientRect(),r=t.left,o=t.top,r-=s.clientLeft||i.clientLeft||0,o-=s.clientTop||i.clientTop||0;var l=a.defaultView||a.parentWindow;return r+=n(l),o+=n(l,!0),{left:r,top:o}}function o(){if(!window.getComputedStyle)return!1;if(void 0!==a)return a;var e=document.createElement("p"),t=void 0,n={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var r in n)void 0!==e.style[r]&&(e.style[r]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(n[r]),void 0!==t&&t.length>0&&"none"!==t&&(a=r));return document.body.removeChild(e),a}Object.defineProperty(t,"__esModule",{value:!0}),t.getScroll=n,t.offset=r,t.getTransformPropertyName=o;var a=void 0},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(14),u=r(l),c=n(377),p=r(c),f=n(380),d=r(f),h=n(110),y=r(h),v=n(379),m=s["default"].createClass({displayName:"Picker",propTypes:{prefixCls:i.PropTypes.string,locale:i.PropTypes.object,value:i.PropTypes.object,disabled:i.PropTypes.bool,allowEmpty:i.PropTypes.bool,defaultValue:i.PropTypes.object,open:i.PropTypes.bool,defaultOpen:i.PropTypes.bool,align:i.PropTypes.object,placement:i.PropTypes.any,transitionName:i.PropTypes.string,getPopupContainer:i.PropTypes.func,placeholder:i.PropTypes.string,formatter:i.PropTypes.any,showHour:i.PropTypes.bool,style:i.PropTypes.object,className:i.PropTypes.string,showSecond:i.PropTypes.bool,disabledHours:i.PropTypes.func,disabledMinutes:i.PropTypes.func,disabledSeconds:i.PropTypes.func,hideDisabledOptions:i.PropTypes.bool,onChange:i.PropTypes.func,onOpen:i.PropTypes.func,onClose:i.PropTypes.func},mixins:[y["default"]],getDefaultProps:function(){return{defaultOpen:!1,style:{},className:"",align:{},allowEmpty:!0,showHour:!0,showSecond:!0,disabledHours:o,disabledMinutes:o,disabledSeconds:o,hideDisabledOptions:!1,placement:"bottomLeft",onChange:o,onOpen:o,onClose:o}},getInitialState:function(){this.savePanelRef=a.bind(this,"panelInstance");var e=this.props,t=e.defaultOpen,n=e.defaultValue,r=e.open,o=void 0===r?t:r,i=e.value,s=void 0===i?n:i;return{open:o,value:s}},componentWillReceiveProps:function(e){var t=e.value,n=e.open;"value"in e&&this.setState({value:t}),void 0!==n&&this.setState({open:n})},onPanelChange:function(e){this.setValue(e)},onPanelClear:function(){this.setValue(null),this.setOpen(!1)},onVisibleChange:function(e){this.setOpen(e)},onEsc:function(){this.setOpen(!1),this.refs.picker.focus()},onKeyDown:function(e){40===e.keyCode&&this.setOpen(!0)},setValue:function(e){"value"in this.props||this.setState({value:e}),this.props.onChange(e)},getFormatter:function(){var e=this.props.formatter,t=this.props.locale;return e?e===this.lastFormatter?this.normalFormatter:(this.normalFormatter=(0,v.getFormatter)(e,t),this.lastFormatter=e,this.normalFormatter):this.props.showSecond?this.props.showHour?(this.normalFormatter||(this.normalFormatter=(0,v.getFormatter)("HH:mm:ss",t)),this.normalFormatter):(this.notShowHourFormatter||(this.notShowHourFormatter=(0,v.getFormatter)("mm:ss",t)),this.notShowHourFormatter):(this.notShowSecondFormatter||(this.notShowSecondFormatter=(0,v.getFormatter)("HH:mm",t)),this.notShowSecondFormatter)},getPanelElement:function(){var e=this.props,t=e.prefixCls,n=e.defaultValue,r=e.locale,o=e.placeholder,a=e.disabledHours,i=e.disabledMinutes,l=e.disabledSeconds,u=e.hideDisabledOptions,c=e.allowEmpty,f=e.showHour,d=e.showSecond;return s["default"].createElement(p["default"],{prefixCls:t+"-panel",ref:this.savePanelRef,value:this.state.value,onChange:this.onPanelChange,gregorianCalendarLocale:r.calendar,onClear:this.onPanelClear,defaultValue:n,showHour:f,onEsc:this.onEsc,showSecond:d,locale:r,allowEmpty:c,formatter:this.getFormatter(),placeholder:o,disabledHours:a,disabledMinutes:i,disabledSeconds:l,hideDisabledOptions:u})},setOpen:function(e,t){var n=this.props,r=n.onOpen,o=n.onClose;if(this.state.open!==e){this.setState({open:e},t);var a={open:e};e?r(a):o(a)}},render:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=e.placement,o=e.align,a=e.disabled,i=e.transitionName,l=e.style,c=e.className,p=e.showHour,f=e.showSecond,h=e.getPopupContainer,y=this.state,v=y.open,m=y.value,g=void 0;return p&&f||(g=t+"-panel-narrow"),s["default"].createElement(u["default"],{prefixCls:t+"-panel",popupClassName:g,popup:this.getPanelElement(),popupAlign:o,builtinPlacements:d["default"],popupPlacement:r,action:a?[]:["click"],destroyPopupOnHide:!0,getPopupContainer:h,popupTransitionName:i,popupVisible:v,onPopupVisibleChange:this.onVisibleChange},s["default"].createElement("span",{className:t+" "+c,style:l},s["default"].createElement("input",{className:t+"-input",ref:"picker",type:"text",placeholder:n,readOnly:!0,onKeyDown:this.onKeyDown,disabled:a,value:m&&this.getFormatter().format(m)||""}),s["default"].createElement("span",{className:t+"-icon"})))}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=n(373),i=r(a);t["default"]={propTypes:{prefixCls:o.PropTypes.string,locale:o.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-time-picker",locale:i["default"]}}},e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(382)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},s=n(1),l=r(s),u=function(e){function t(){o(this,t),i(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return a(t,e),t}(l["default"].Component);t["default"]=u,u.propTypes={value:l["default"].PropTypes.string},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){var t=e.props;if("value"in t)return t.value;if(e.key)return e.key;throw new Error("no key or value for "+e)}function s(e,t){return"value"===t?i(e):e.props[t]}function l(e){return e.combobox}function u(e){return e.multiple||e.tags||e.treeCheckable}function c(e){return u(e)||l(e)}function p(e){return!c(e)}function f(e){var t=e;return void 0===e?t=[]:Array.isArray(e)||(t=[e]),t}function d(e){e.preventDefault()}function h(e){var t=e;return"label"===t&&(t="title"),t}function y(e,t){return e.every(function(e,n){return e===t[n]})}function v(e){var t=1;return Array.isArray(e)&&(t=e.length),t}function m(e,t,n){return 1===t?(n.first=!0,n.last=!0):(n.first=0===e,n.last=e===t-1),n}function g(e,t,n){var r=function o(e,n,r){var a=v(e);D["default"].Children.forEach(e,function(e,i){var s=n+"-"+i;e&&e.props.children&&e.type&&o(e.props.children,s,{node:e,pos:s}),e&&t(e,i,s,e.key||s,m(i,a,{}),r)})};r(e,0,n)}function b(e){if(!e.length)return e;var t=[],n={};e.forEach(function(e){var t=e.pos.split("-").length;n[t]||(n[t]=[]),n[t].push(e)});var r=Object.keys(n).sort(function(e,t){return t-e});return r.reduce(function(e,r){return r&&r!==e&&n[e].forEach(function(e){var o=!1;n[r].forEach(function(t){y(t.pos.split("-"),e.pos.split("-"))&&(o=!0,t.children||(t.children=[]),t.children.push(e))}),o||t.push(e)}),r}),n[r[r.length-1]].concat(t)}function P(e){var t={};e.forEach(function(e){var n=e.split("-").length;t[n]||(t[n]=[]),t[n].push(e)});for(var n=Object.keys(t).sort(),r=function(e){n[e+1]&&t[n[e]].forEach(function(r){for(var o=function(e){t[n[e]].forEach(function(o,a){y(r.split("-"),o.split("-"))&&(t[n[e]][a]=null)}),t[n[e]]=t[n[e]].filter(function(e){return e})},a=e+1;a<n.length;a++)o(a)})},o=0;o<n.length;o++)r(o);var a=[];return n.forEach(function(e){a=a.concat(t[e])}),a}function O(e){var t=e.match(/(.+)(-[^-]+)$/),n="";return t&&3===t.length&&(n=t[1]),n}function C(e){return e.split("-")}function T(e,t,n){var r=Object.keys(e);r.forEach(function(o,a){var i=C(o),s=!1;t.forEach(function(t){var l=C(t);i.length>l.length&&y(l,i)&&(e[o].halfChecked=!1,e[o].checked=n,r[a]=null),i[0]===l[0]&&i[1]===l[1]&&(s=!0)}),s||(r[a]=null)}),r=r.filter(function(e){return e});for(var o=function(n){var o=function i(o){var a=C(o).length;if(!(a<=2)){var s=0,l=0,u=O(o);r.forEach(function(r){var o=C(r);if(o.length===a&&y(C(u),o))if(s++,e[r].checked){l++;var i=t.indexOf(r);i>-1&&(t.splice(i,1),i<=n&&n--)}else e[r].halfChecked&&(l+=.5)});var c=e[u];0===l?(c.checked=!1,c.halfChecked=!1):l===s?(c.checked=!0,c.halfChecked=!1):(c.halfChecked=!0,c.checked=!1),i(u)}};o(t[n],n),a=n},a=0;a<t.length;a++)o(a)}function w(e,t){var n=[],r=[],o=[];return Object.keys(e).forEach(function(t){var a=e[t];a.checked?(r.push(a.key),o.push(N({},a,{pos:t}))):a.halfChecked&&n.push(a.key)}),{halfCheckedKeys:n,checkedKeys:r,checkedNodes:o,treeNodesStates:e,checkedPositions:t}}function x(e,t){var n=[],r={};return g(e,function(e,o,a,s,l){r[a]={node:e,key:s,checked:!1,halfChecked:!1,siblingPosition:l},t.indexOf(i(e))!==-1&&(r[a].checked=!0,n.push(a))}),T(r,P(n.sort()),!0),w(r,n)}function E(e){var t=arguments.length<=1||void 0===arguments[1]?function(e){return e}:arguments[1];return Array.from(e).map(function(e){var n=t(e);return n&&n.props&&n.props.children?D["default"].cloneElement(n,{},E(n.props.children,t)):n})}function S(e){var t=arguments.length<=1||void 0===arguments[1]?0:arguments[1];return D["default"].Children.map(e,function(e,n){var r=t+"-"+n,o={title:e.props.title,label:e.props.label||e.props.title,value:e.props.value,key:e.key,_pos:r};return e.props.children&&(o.children=S(e.props.children,r)),o})}function k(e,t){e.forEach(function(e){t(e),e.children&&k(e.children,t)})}function j(e,t){function n(e){e.forEach(function(e){if(!e.__checked){var t=a.indexOf(e.value),r=e.children;t>-1?(e.__checked=!0,s.push({node:e,pos:e._pos}),a.splice(t,1),r&&k(r,function(e){e.__checked=!0,s.push({node:e,pos:e._pos})})):r&&n(r)}})}function r(e){var t=arguments.length<=1||void 0===arguments[1]?{root:!0}:arguments[1],n=0;e.forEach(function(e){var t=e.children;if(!t||e.__checked||e.__halfChecked)e.__checked?n++:e.__halfChecked&&(n+=.5);else{var o=r(t,e);o.__checked?n++:o.__halfChecked&&(n+=.5)}});var o=e.length;return n===o?(t.__checked=!0,s.push({node:t,pos:t._pos})):n<o&&n>0&&(t.__halfChecked=!0),t.root?e:t}var a=[].concat(o(e));if(!a.length)return a;var i=S(t),s=[];return n(i),r(i),s.forEach(function(e,t){delete s[t].node.__checked,delete s[t].node._pos,s[t].node.props={title:s[t].node.title,label:s[t].node.label||s[t].node.title,value:s[t].node.value},s[t].node.children&&(s[t].node.props.children=s[t].node.children),delete s[t].node.title,delete s[t].node.label,delete s[t].node.value,delete s[t].node.children}),s}function _(e,t){function n(e){for(var r=arguments.length<=1||void 0===arguments[1]?a({},t.id,t.rootPId):arguments[1],o=[],i=0;i<e.length;i++)e[i][t.pId]===r[t.id]&&(e[i].key=e[i][t.id],o.push(e[i]),e.splice(i--,1));if(o.length&&(r.children=o,o.forEach(function(t){return n(e,t)})),r[t.id]===t.rootPId)return o}return n(e)}Object.defineProperty(t,"__esModule",{value:!0});var N=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.getValuePropValue=i,t.getPropValue=s,t.isCombobox=l,t.isMultipleOrTags=u,t.isMultipleOrTagsOrCombobox=c,t.isSingleMode=p,t.toArray=f,t.preventDefaultEvent=d,t.labelCompatible=h,t.isInclude=y,t.loopAllChildren=g,t.flatToHierarchy=b,t.filterParentPosition=P,t.handleCheckState=T,t.getTreeNodesStates=x, t.recursiveCloneChildren=E,t.filterAllCheckedData=j,t.processSimpleTreeData=_;var M=n(1),D=r(M),A={userSelect:"none",WebkitUserSelect:"none"};t.UNSELECTABLE_STYLE=A;var L={unselectable:"unselectable"};t.UNSELECTABLE_ATTRIBUTE=L},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(387),a=r(o),i=n(388),s=r(i);a["default"].TreeNode=s["default"],t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0,n=e.userAgent,r=n.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)||[];return/trident/i.test(r[1])?(t=/\brv[ :]+(\d+)/g.exec(n)||[],"IE "+(t[1]||"")):"Chrome"===r[1]&&(t=n.match(/\b(OPR|Edge)\/(\d+)/))?t.slice(1).join(" ").replace("OPR","Opera"):(r=r[2]?[r[1],r[2]]:[e.appName,e.appVersion,"-?"],t=n.match(/version\/(\d+)/i),t&&r.splice(1,1,t[1]),r.join(" "))}function a(e){for(var t=e,n=0,r=0;t&&!isNaN(t.offsetLeft)&&!isNaN(t.offsetTop);)n+=t.offsetLeft-t.scrollLeft,r+=t.offsetTop-t.scrollTop,t=t.offsetParent;return{top:r,left:n}}function i(e){var t=1;return Array.isArray(e)&&(t=e.length),t}function s(e,t,n){return 1===t?(n.first=!0,n.last=!0):(n.first=0===e,n.last=e===t-1),n}function l(e,t,n){var r=function o(e,n,r){var a=i(e);g["default"].Children.forEach(e,function(e,i){var l=n+"-"+i;e.props.children&&e.type&&e.type.isTreeNode&&o(e.props.children,l,{node:e,pos:l}),t(e,i,l,e.key||l,s(i,a,{}),r)})};r(e,0,n)}function u(e,t){return e.every(function(e,n){return e===t[n]})}function c(e){var t={};e.forEach(function(e){var n=e.split("-").length;t[n]||(t[n]=[]),t[n].push(e)});for(var n=Object.keys(t).sort(),r=function(e){n[e+1]&&t[n[e]].forEach(function(r){for(var o=function(e){t[n[e]].forEach(function(o,a){u(r.split("-"),o.split("-"))&&(t[n[e]][a]=null)}),t[n[e]]=t[n[e]].filter(function(e){return e})},a=e+1;a<n.length;a++)o(a)})},o=0;o<n.length;o++)r(o);var a=[];return n.forEach(function(e){a=a.concat(t[e])}),a}function p(e){var t=e.match(/(.+)(-[^-]+)$/),n="";return t&&3===t.length&&(n=t[1]),n}function f(e){return e.split("-")}function d(e,t,n){var r=Object.keys(e);r.forEach(function(o,a){var i=f(o),s=!1;t.forEach(function(t){var l=f(t);i.length>l.length&&u(l,i)&&(e[o].halfChecked=!1,e[o].checked=n,r[a]=null),i[0]===l[0]&&i[1]===l[1]&&(s=!0)}),s||(r[a]=null)}),r=r.filter(function(e){return e});for(var o=function(n){var o=function i(o){var a=f(o).length;if(!(a<=2)){var s=0,l=0,c=p(o);r.forEach(function(r){var o=f(r);if(o.length===a&&u(f(c),o))if(s++,e[r].checked){l++;var i=t.indexOf(r);i>-1&&(t.splice(i,1),i<=n&&n--)}else e[r].halfChecked&&(l+=.5)});var d=e[c];0===l?(d.checked=!1,d.halfChecked=!1):l===s?(d.checked=!0,d.halfChecked=!1):(d.halfChecked=!0,d.checked=!1),i(c)}};o(t[n],n),a=n},a=0;a<t.length;a++)o(a)}function h(e){var t=[],n=[],r=[],o=[];return Object.keys(e).forEach(function(a){var i=e[a];i.checked?(n.push(i.key),r.push(i.node),o.push({node:i.node,pos:a})):i.halfChecked&&t.push(i.key)}),{halfCheckedKeys:t,checkedKeys:n,checkedNodes:r,checkedNodesPositions:o,treeNodesStates:e}}function y(e,t){return t?{checked:e,halfChecked:t}:e}function v(e,t){if(e===t)return!0;if(null===e||"undefined"==typeof e||null===t||"undefined"==typeof t)return!1;if(e.length!==t.length)return!1;for(var n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}Object.defineProperty(t,"__esModule",{value:!0}),t.browser=o,t.getOffset=a,t.loopAllChildren=l,t.isInclude=u,t.filterParentPosition=c,t.handleCheckState=d,t.getCheck=h,t.getStrictlyValue=y,t.arraysEqual=v;var m=n(1),g=r(m)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=i["default"].createClass({displayName:"LazyRenderBox",propTypes:{children:a.PropTypes.any,className:a.PropTypes.string,visible:a.PropTypes.bool,hiddenClassName:a.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){if(this.props.hiddenClassName){var e=this.props.className;return this.props.visible||(e+=" "+this.props.hiddenClassName),i["default"].createElement("div",o({},this.props,{className:e}))}return i["default"].Children.count(this.props.children)>1?i["default"].createElement("div",this.props):i["default"].Children.only(this.props.children)}});t["default"]=s,e.exports=t["default"]},function(e,t){"use strict";function n(){return"rc-upload-"+r+"-"+ ++o}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n;var r=+new Date,o=0;e.exports=t["default"]},function(e,t){"use strict";e.exports=function(e,t){for(var n=t;n;){if(n===e)return!0;n=n.parentNode}return!1}},function(e,t){"use strict";var n={className:"",adaptiveHeight:!1,arrows:!0,autoplay:!1,autoplaySpeed:3e3,centerMode:!1,centerPadding:"50px",cssEase:"ease",dots:!1,dotsClass:"slick-dots",draggable:!0,easing:"linear",edgeFriction:.35,fade:!1,focusOnSelect:!1,infinite:!0,initialSlide:0,lazyLoad:!1,pauseOnHover:!1,responsive:null,rtl:!1,slide:"div",slidesToShow:1,slidesToScroll:1,speed:500,swipe:!0,swipeToSlide:!1,touchMove:!0,touchThreshold:5,useCSS:!0,variableWidth:!1,vertical:!1,waitForAnimate:!0,afterChange:null,beforeChange:null,edgeEvent:null,init:null,swipeEvent:null,nextArrow:null,prevArrow:null};e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(4),s=r(i),l=a["default"].version>="0.14.0"?s["default"]:a["default"];t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(120),s=r(i),l=n(414),u=r(l),c=n(122),p=n(32),f=r(p),d={initialize:function(e){var t=a["default"].Children.count(e.children),n=this.getWidth(s["default"].findDOMNode(this.refs.list)),r=this.getWidth(s["default"].findDOMNode(this.refs.track)),o=this.getWidth(s["default"].findDOMNode(this))/e.slidesToShow,i=e.rtl?t-1-e.initialSlide:e.initialSlide;this.setState({slideCount:t,slideWidth:o,listWidth:n,trackWidth:r,currentSlide:i},function(){var t=(0,c.getTrackLeft)((0,f["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},e,this.state)),n=(0,c.getTrackCSS)((0,f["default"])({left:t},e,this.state));this.setState({trackStyle:n}),this.autoPlay()})},update:function(e){var t=a["default"].Children.count(e.children),n=this.getWidth(s["default"].findDOMNode(this.refs.list)),r=this.getWidth(s["default"].findDOMNode(this.refs.track)),o=this.getWidth(s["default"].findDOMNode(this))/e.slidesToShow;this.setState({slideCount:t,slideWidth:o,listWidth:n,trackWidth:r},function(){var t=(0,c.getTrackLeft)((0,f["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},e,this.state)),n=(0,c.getTrackCSS)((0,f["default"])({left:t},e,this.state));this.setState({trackStyle:n})})},getWidth:function(e){return e.getBoundingClientRect().width||e.offsetWidth},adaptHeight:function(){if(this.props.adaptiveHeight){var e='[data-index="'+this.state.currentSlide+'"]';if(this.refs.list){var t=s["default"].findDOMNode(this.refs.list);t.style.height=t.querySelector(e).offsetHeight+"px"}}},slideHandler:function(e){var t,n,r,o,a,i=this;if(!this.props.waitForAnimate||!this.state.animating){if(this.props.fade)return n=this.state.currentSlide,t=e<0?e+this.state.slideCount:e>=this.state.slideCount?e-this.state.slideCount:e,this.props.lazyLoad&&this.state.lazyLoadedList.indexOf(t)<0&&this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(t)}),a=function(){i.setState({animating:!1}),i.props.afterChange&&i.props.afterChange(n),u["default"].removeEndEventListener(s["default"].findDOMNode(i.refs.track).children[n],a)},this.setState({animating:!0,currentSlide:t},function(){u["default"].addEndEventListener(s["default"].findDOMNode(this.refs.track).children[n],a)}),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,n),void this.autoPlay();if(t=e,n=t<0?this.props.infinite===!1?0:this.state.slideCount%this.props.slidesToScroll!==0?this.state.slideCount-this.state.slideCount%this.props.slidesToScroll:this.state.slideCount+t:t>=this.state.slideCount?this.props.infinite===!1?this.state.slideCount-this.props.slidesToShow:this.state.slideCount%this.props.slidesToScroll!==0?0:t-this.state.slideCount:t,r=(0,c.getTrackLeft)((0,f["default"])({slideIndex:t,trackRef:this.refs.track},this.props,this.state)),o=(0,c.getTrackLeft)((0,f["default"])({slideIndex:n,trackRef:this.refs.track},this.props,this.state)),this.props.infinite===!1&&(r=o),this.props.beforeChange&&this.props.beforeChange(this.state.currentSlide,n),this.props.lazyLoad){for(var l=!0,p=[],d=t;d<t+this.props.slidesToShow;d++)l=l&&this.state.lazyLoadedList.indexOf(d)>=0,l||p.push(d);l||this.setState({lazyLoadedList:this.state.lazyLoadedList.concat(p)})}if(this.props.useCSS===!1)this.setState({currentSlide:n,trackStyle:(0,c.getTrackCSS)((0,f["default"])({left:o},this.props,this.state))},function(){this.props.afterChange&&this.props.afterChange(n)});else{var h={animating:!1,currentSlide:n,trackStyle:(0,c.getTrackCSS)((0,f["default"])({left:o},this.props,this.state)),swipeLeft:null};a=function(){i.setState(h),i.props.afterChange&&i.props.afterChange(n),u["default"].removeEndEventListener(s["default"].findDOMNode(i.refs.track),a)},this.setState({animating:!0,currentSlide:n,trackStyle:(0,c.getTrackAnimateCSS)((0,f["default"])({left:r},this.props,this.state))},function(){u["default"].addEndEventListener(s["default"].findDOMNode(this.refs.track),a)})}this.autoPlay()}},swipeDirection:function(e){var t,n,r,o;return t=e.startX-e.curX,n=e.startY-e.curY,r=Math.atan2(n,t),o=Math.round(180*r/Math.PI),o<0&&(o=360-Math.abs(o)),o<=45&&o>=0||o<=360&&o>=315?this.props.rtl===!1?"left":"right":o>=135&&o<=225?this.props.rtl===!1?"right":"left":"vertical"},autoPlay:function(){var e=this;if(!this.state.autoPlayTimer){var t=function(){if(e.state.mounted){var t=e.props.rtl?e.state.currentSlide-e.props.slidesToScroll:e.state.currentSlide+e.props.slidesToScroll;e.slideHandler(t)}};this.props.autoplay&&this.setState({autoPlayTimer:window.setInterval(t,this.props.autoplaySpeed)})}},pause:function(){this.state.autoPlayTimer&&(window.clearInterval(this.state.autoPlayTimer),this.setState({autoPlayTimer:null}))}};t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(120),a=r(o),i=function(e,t){return t.reduce(function(t,n){return t&&e.hasOwnProperty(n)},!0)?null:console.error("Keys Missing",e)},s=function(e){i(e,["left","variableWidth","slideCount","slidesToShow","slideWidth"]);var t;t=e.variableWidth?(e.slideCount+2*e.slidesToShow)*e.slideWidth:e.centerMode?(e.slideCount+2*(e.slidesToShow+1))*e.slideWidth:(e.slideCount+2*e.slidesToShow)*e.slideWidth;var n={opacity:1,width:t,WebkitTransform:"translate3d("+e.left+"px, 0px, 0px)",transform:"translate3d("+e.left+"px, 0px, 0px)",transition:"",WebkitTransition:"",msTransform:"translateX("+e.left+"px)"};return!window.addEventListener&&window.attachEvent&&(n.marginLeft=e.left+"px"),n};t.getTrackCSS=s;var l=function(e){i(e,["left","variableWidth","slideCount","slidesToShow","slideWidth","speed","cssEase"]);var t=s(e);return t.WebkitTransition="-webkit-transform "+e.speed+"ms "+e.cssEase,t.transition="transform "+e.speed+"ms "+e.cssEase,t};t.getTrackAnimateCSS=l;var u=function(e){i(e,["slideIndex","trackRef","infinite","centerMode","slideCount","slidesToShow","slidesToScroll","slideWidth","listWidth","variableWidth"]);var t,n,r=0;if(e.fade)return 0;if(e.infinite&&(e.slideCount>e.slidesToShow&&(r=e.slideWidth*e.slidesToShow*-1),e.slideCount%e.slidesToScroll!==0&&e.slideIndex+e.slidesToScroll>e.slideCount&&e.slideCount>e.slidesToShow&&(r=e.slideIndex>e.slideCount?(e.slidesToShow-(e.slideIndex-e.slideCount))*e.slideWidth*-1:e.slideCount%e.slidesToScroll*e.slideWidth*-1)),e.centerMode&&(e.infinite?r+=e.slideWidth*Math.floor(e.slidesToShow/2):r=e.slideWidth*Math.floor(e.slidesToShow/2)),t=e.slideIndex*e.slideWidth*-1+r,e.variableWidth===!0){var o;e.slideCount<=e.slidesToShow||e.infinite===!1?n=a["default"].findDOMNode(e.trackRef).childNodes[e.slideIndex]:(o=e.slideIndex+e.slidesToShow,n=a["default"].findDOMNode(e.trackRef).childNodes[o]),t=n?n.offsetLeft*-1:0,e.centerMode===!0&&(n=e.infinite===!1?a["default"].findDOMNode(e.trackRef).children[e.slideIndex]:a["default"].findDOMNode(e.trackRef).children[e.slideIndex+e.slidesToShow+1],t=n?n.offsetLeft*-1:0,t+=(e.listWidth-n.offsetWidth)/2)}return t};t.getTrackLeft=u},function(e,t,n){"use strict";var r=n(276);e.exports=function(e,t,n,o){var a=n?n.call(o,e,t):void 0;if(void 0!==a)return!!a;if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var i=r(e),s=r(t),l=i.length;if(l!==s.length)return!1;o=o||null;for(var u=Object.prototype.hasOwnProperty.bind(t),c=0;c<l;c++){var p=i[c];if(!u(p))return!1;var f=e[p],d=t[p],h=n?n.call(o,f,d,p):void 0;if(h===!1||void 0===h&&f!==d)return!1}return!0}},function(e,t){(function(t){function n(e,t){function n(){if(!o){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),o=!0}return e.apply(this,arguments)}if(r("noDeprecation"))return e;var o=!1;return n}function r(e){try{if(!t.localStorage)return!1}catch(n){return!1}var r=t.localStorage[e];return null!=r&&"true"===String(r).toLowerCase()}e.exports=n}).call(t,function(){return this}())},function(e,t,n){function r(e){return n(o(e))}function o(e){return a[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var a={"./affix/index.jsx":149,"./affix/style/index.js":150,"./alert/index.jsx":151,"./alert/style/index.js":152,"./badge/index.jsx":154,"./badge/style/index.js":155,"./breadcrumb/index.jsx":157,"./breadcrumb/style/index.js":158,"./button/index.jsx":16,"./button/style/index.js":25,"./calendar/index.jsx":162,"./calendar/style/index.js":164,"./card/index.jsx":165,"./card/style/index.js":166,"./carousel/index.jsx":167,"./carousel/style/index.js":168,"./cascader/index.jsx":169,"./cascader/style/index.js":170,"./checkbox/index.jsx":18,"./checkbox/style/index.js":19,"./col/index.js":172,"./col/style/index.js":173,"./collapse/index.jsx":174,"./collapse/style/index.js":175,"./date-picker/index.jsx":179,"./date-picker/style/index.js":180,"./dropdown/index.jsx":58,"./dropdown/style/index.js":59,"./form/index.jsx":186,"./form/style/index.js":187,"./icon/index.jsx":6,"./icon/style/index.js":188,"./input-number/index.jsx":189,"./input-number/style/index.js":190,"./input/index.jsx":60,"./input/style/index.js":13,"./layout/index.jsx":34,"./layout/style/index.js":61,"./locale-provider/index.jsx":196,"./locale-provider/style/index.js":197,"./menu/index.jsx":198,"./menu/style/index.js":199,"./message/index.jsx":200,"./message/style/index.js":201,"./modal/index.jsx":203,"./modal/style/index.js":204,"./notification/index.jsx":205,"./notification/style/index.js":206,"./pagination/index.jsx":64,"./pagination/style/index.js":65,"./popconfirm/index.jsx":210,"./popconfirm/style/index.js":211,"./popover/index.jsx":212,"./popover/style/index.js":66,"./progress/index.jsx":67,"./progress/style/index.js":68,"./queue-anim/index.jsx":214,"./queue-anim/style/index.js":215,"./radio/index.jsx":26,"./radio/style/index.js":37,"./rate/index.jsx":217,"./rate/style/index.js":218,"./row/index.js":219,"./row/style/index.js":220,"./select/index.jsx":27,"./select/style/index.js":28,"./slider/index.jsx":221,"./slider/style/index.js":222,"./spin/index.jsx":70,"./spin/style/index.js":71,"./steps/index.jsx":223,"./steps/style/index.js":224,"./style/index.js":225,"./switch/index.jsx":226,"./switch/style/index.js":227,"./table/index.jsx":229,"./table/style/index.js":230,"./tabs/index.jsx":232,"./tabs/style/index.js":233,"./tag/index.jsx":234,"./tag/style/index.js":235,"./time-picker/index.jsx":236,"./time-picker/style/index.js":73,"./timeline/index.jsx":238,"./timeline/style/index.js":239,"./tooltip/index.jsx":38,"./tooltip/style/index.js":75,"./transfer/index.jsx":240,"./transfer/style/index.js":243,"./tree-select/index.jsx":244,"./tree-select/style/index.js":245,"./tree/index.jsx":246,"./tree/style/index.js":247,"./upload/index.jsx":249,"./upload/style/index.js":250,"./validation/index.jsx":252,"./validation/style/index.js":253};r.keys=function(){return Object.keys(a)},r.resolve=o,e.exports=r,r.id=125},function(e,t){"use strict";function n(){return!1}function r(){return!0}function o(){this.timeStamp=Date.now(),this.target=void 0,this.currentTarget=void 0}Object.defineProperty(t,"__esModule",{value:!0}),o.prototype={isEventObject:1,constructor:o,isDefaultPrevented:n,isPropagationStopped:n,isImmediatePropagationStopped:n,preventDefault:function(){this.isDefaultPrevented=r},stopPropagation:function(){this.isPropagationStopped=r},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=r,this.stopPropagation()},halt:function(e){e?this.stopImmediatePropagation():this.stopPropagation(),this.preventDefault()}},t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return null===e||void 0===e}function a(){return f}function i(){return d}function s(e){var t=e.type,n="function"==typeof e.stopPropagation||"boolean"==typeof e.cancelBubble;u["default"].call(this),this.nativeEvent=e;var r=i;"defaultPrevented"in e?r=e.defaultPrevented?a:i:"getPreventDefault"in e?r=e.getPreventDefault()?a:i:"returnValue"in e&&(r=e.returnValue===d?a:i),this.isDefaultPrevented=r;var o=[],s=void 0,l=void 0,c=void 0,p=h.concat();for(y.forEach(function(e){t.match(e.reg)&&(p=p.concat(e.props),e.fix&&o.push(e.fix))}),l=p.length;l;)c=p[--l],this[c]=e[c];for(!this.target&&n&&(this.target=e.srcElement||document),this.target&&3===this.target.nodeType&&(this.target=this.target.parentNode),l=o.length;l;)(s=o[--l])(this,e);this.timeStamp=e.timeStamp||Date.now()}Object.defineProperty(t,"__esModule",{value:!0});var l=n(126),u=r(l),c=n(10),p=r(c),f=!0,d=!1,h=["altKey","bubbles","cancelable","ctrlKey","currentTarget","eventPhase","metaKey","shiftKey","target","timeStamp","view","type"],y=[{reg:/^key/,props:["char","charCode","key","keyCode","which"],fix:function(e,t){o(e.which)&&(e.which=o(t.charCode)?t.keyCode:t.charCode),void 0===e.metaKey&&(e.metaKey=e.ctrlKey)}},{reg:/^touch/,props:["touches","changedTouches","targetTouches"]},{reg:/^hashchange$/,props:["newURL","oldURL"]},{reg:/^gesturechange$/i,props:["rotation","scale"]},{reg:/^(mousewheel|DOMMouseScroll)$/,props:[],fix:function(e,t){var n=void 0,r=void 0,o=void 0,a=t.wheelDelta,i=t.axis,s=t.wheelDeltaY,l=t.wheelDeltaX,u=t.detail;a&&(o=a/120),u&&(o=0-(u%3===0?u/3:u)),void 0!==i&&(i===e.HORIZONTAL_AXIS?(r=0,n=0-o):i===e.VERTICAL_AXIS&&(n=0,r=o)),void 0!==s&&(r=s/120),void 0!==l&&(n=-1*l/120),n||r||(r=o),void 0!==n&&(e.deltaX=n),void 0!==r&&(e.deltaY=r),void 0!==o&&(e.delta=o)}},{reg:/^mouse|contextmenu|click|mspointer|(^DOMMouseScroll$)/i,props:["buttons","clientX","clientY","button","offsetX","relatedTarget","which","fromElement","toElement","offsetY","pageX","pageY","screenX","screenY"],fix:function(e,t){var n=void 0,r=void 0,a=void 0,i=e.target,s=t.button;return i&&o(e.pageX)&&!o(t.clientX)&&(n=i.ownerDocument||document,r=n.documentElement,a=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||a&&a.scrollLeft||0)-(r&&r.clientLeft||a&&a.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||a&&a.scrollTop||0)-(r&&r.clientTop||a&&a.clientTop||0)),e.which||void 0===s||(1&s?e.which=1:2&s?e.which=3:4&s?e.which=2:e.which=0),!e.relatedTarget&&e.fromElement&&(e.relatedTarget=e.fromElement===i?e.toElement:e.fromElement),e}}],v=u["default"].prototype;(0,p["default"])(s.prototype,v,{constructor:s,preventDefault:function(){var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=d,v.preventDefault.call(this)},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=f,v.stopPropagation.call(this)}}),t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){function r(t){var r=new i["default"](t);n.call(e,r)}return e.addEventListener?(e.addEventListener(t,r,!1),{remove:function(){e.removeEventListener(t,r,!1)}}):e.attachEvent?(e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}):void 0}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var a=n(127),i=r(a);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if("object"!==("undefined"==typeof e?"undefined":s(e)))return t}function a(e){this.rules=null,this._messages=p.messages,this.define(e)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},l=n(5),u=n(141),c=r(u),p=n(130),f=n(7),d=n(278),h=r(d);a.prototype={messages:function(e){return e&&(this._messages=(0,h["default"])((0,p.newMessages)(),e,o)),this._messages},define:function(e){if(!e)throw new Error("Cannot configure a schema with no rules");if("object"!==("undefined"==typeof e?"undefined":s(e))||Array.isArray(e))throw new Error("Rules must be an object");this.rules={};var t=void 0,n=void 0;for(t in e)e.hasOwnProperty(t)&&(n=e[t],this.rules[t]=Array.isArray(n)?n:[n])},validate:function(e){function t(e){function t(e){Array.isArray(e)?o=o.concat.apply(o,e):o.push(e)}var n=void 0,r=void 0,o=[],a={};for(n=0;n<e.length;n++)t(e[n]);if(o.length)for(n=0;n<o.length;n++)r=o[n].field,a[r]=a[r]||[],a[r].push(o[n]);else o=null,a=null;y(o,a)}var n=this,r=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],u=arguments[2],c=e,d=r;if(!this.rules)throw new Error("Cannot validate with no rules.");var y=u;if("function"==typeof d&&(y=d,d={}),d.messages){var v=this.messages();v===p.messages&&(v=(0,p.newMessages)()),(0,h["default"])(v,d.messages,o),d.messages=v}else d.messages=this.messages();d.error=f.error;var m=void 0,g=void 0,b={},P=d.keys||Object.keys(this.rules);P.forEach(function(t){m=n.rules[t],g=c[t],m.forEach(function(r){var o=r;"function"==typeof o.transform&&(c===e&&(c=i({},c)),g=c[t]=o.transform(g)),o="function"==typeof o?{validator:o}:i({},o),o.field=t,o.fullField=o.fullField||t,o.type=n.getType(o),o.validator=n.getValidationMethod(o),o.validator&&(b[t]=b[t]||[],b[t].push({rule:o,value:g,source:c,field:t}))})});var O={};(0,l.asyncMap)(b,d,function(e,t){function n(e,t){return i({},t,{fullField:o.fullField+"."+e})}function r(){var r=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],s=r;if(Array.isArray(s)||(s=[s]),s.length&&(0,l.warning)("async-validator:",s),s.length&&o.message&&(s=[].concat(o.message)),s=s.map((0,l.complementError)(o)),(d.first||d.fieldFirst)&&s.length)return O[o.field]=1,t(s);if(u){if(o.required&&!e.value)return s=o.message?[].concat(o.message).map((0,l.complementError)(o)):[d.error(o,(0,l.format)(d.messages.required,o.field))],t(s);var c={};if(o.defaultField)for(var p in e.value)e.value.hasOwnProperty(p)&&(c[p]=o.defaultField);c=i({},c,e.rule.fields);for(var f in c)if(c.hasOwnProperty(f)){var h=Array.isArray(c[f])?c[f]:[c[f]];c[f]=h.map(n.bind(null,f))}var y=new a(c);y.messages(d.messages),e.rule.options&&(e.rule.options.messages=d.messages,e.rule.options.error=d.error),y.validate(e.value,e.rule.options||d,function(e){t(e&&e.length?s.concat(e):e)})}else t(s)}var o=e.rule,u=!("object"!==o.type&&"array"!==o.type||"object"!==s(o.fields)&&"object"!==s(o.defaultField));u=u&&(o.required||!o.required&&e.value),o.field=e.field,o.validator(o,e.value,r,e.source,d)},function(e){t(e)})},getType:function(e){if(void 0===e.type&&e.pattern instanceof RegExp&&(e.type="pattern"),"function"!=typeof e.validator&&e.type&&!c["default"].hasOwnProperty(e.type))throw new Error((0,l.format)("Unknown rule type %s",e.type));return e.type||"string"},getValidationMethod:function(e){return"function"==typeof e.validator?e.validator:c["default"][e.type]||!1}},a.register=function(e,t){if("function"!=typeof t)throw new Error("Cannot register a validator by type, validator is not a function");c["default"][e]=t},a.messages=p.messages,t["default"]=a,e.exports=t["default"]},function(e,t){"use strict";function n(){return{"default":"Validation error on field %s",required:"%s is required","enum":"%s must be one of %s",whitespace:"%s cannot be empty",date:{format:"%s date %s is invalid for format %s",parse:"%s date could not be parsed, %s is invalid ",invalid:"%s date %s is invalid"},types:{string:"%s is not a %s",method:"%s is not a %s (function)",array:"%s is not an %s",object:"%s is not an %s",number:"%s is not a %s",date:"%s is not a %s","boolean":"%s is not a %s",integer:"%s is not an %s","float":"%s is not a %s",regexp:"%s is not a valid %s",email:"%s is not a valid %s",url:"%s is not a valid %s",hex:"%s is not a valid %s"},string:{len:"%s must be exactly %s characters",min:"%s must be at least %s characters",max:"%s cannot be longer than %s characters",range:"%s must be between %s and %s characters"},number:{len:"%s must equal %s",min:"%s cannot be less than %s",max:"%s cannot be greater than %s",range:"%s must be between %s and %s"},array:{len:"%s must be exactly %s in length",min:"%s cannot be less than %s in length",max:"%s cannot be greater than %s in length",range:"%s must be between %s and %s in length"},pattern:{mismatch:"%s value %s does not match pattern %s"},clone:function(){var e=JSON.parse(JSON.stringify(this));return e.clone=this.clone,e}}}Object.defineProperty(t,"__esModule",{value:!0}),t.newMessages=n;t.messages=n()},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){e[s]=Array.isArray(e[s])?e[s]:[],e[s].indexOf(t)===-1&&r.push(i.format(o.messages[s],e.fullField,e[s].join(", ")))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a),s="enum";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){e.pattern instanceof RegExp&&(e.pattern.test(t)||r.push(i.format(o.messages.pattern.mismatch,e.fullField,t,e.pattern)))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){var a="number"==typeof e.len,s="number"==typeof e.min,l="number"==typeof e.max,u=t,c=null,p="number"==typeof t,f="string"==typeof t,d=Array.isArray(t);return p?c="number":f?c="string":d&&(c="array"),!!c&&((f||d)&&(u=t.length),void(a?u!==e.len&&r.push(i.format(o.messages[c].len,e.fullField,e.len)):s&&!l&&u<e.min?r.push(i.format(o.messages[c].min,e.fullField,e.min)):l&&!s&&u>e.max?r.push(i.format(o.messages[c].max,e.fullField,e.max)):s&&l&&(u<e.min||u>e.max)&&r.push(i.format(o.messages[c].range,e.fullField,e.min,e.max))))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function a(e,t,n,r,o){if(e.required&&void 0===t)return void(0,c["default"])(e,t,n,r,o);var a=["integer","float","array","regexp","object","method","email","number","date","url","hex"],s=e.type;a.indexOf(s)>-1?f[s](t)||r.push(l.format(o.messages.types[s],e.fullField,e.type)):s&&("undefined"==typeof t?"undefined":i(t))!==e.type&&r.push(l.format(o.messages.types[s],e.fullField,e.type))}Object.defineProperty(t,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},s=n(5),l=o(s),u=n(51),c=r(u),p={email:/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/,url:new RegExp("^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$","i"),hex:/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i},f={integer:function(e){return f.number(e)&&parseInt(e,10)===e},"float":function(e){return f.number(e)&&!f.integer(e)},array:function(e){return Array.isArray(e)},regexp:function(e){if(e instanceof RegExp)return!0;try{return!!new RegExp(e)}catch(t){return!1}},date:function(e){return"function"==typeof e.getTime&&"function"==typeof e.getMonth&&"function"==typeof e.getYear},number:function(e){return!isNaN(e)&&"number"==typeof e},object:function(e){return"object"===("undefined"==typeof e?"undefined":i(e))&&!f.array(e)},method:function(e){return"function"==typeof e},email:function(e){return"string"==typeof e&&!!e.match(p.email)},url:function(e){return"string"==typeof e&&!!e.match(p.url)},hex:function(e){return"string"==typeof e&&!!e.match(p.hex)}};t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t["default"]=e,t}function o(e,t,n,r,o){(/^\s+$/.test(t)||""===t)&&r.push(i.format(o.messages.whitespace,e.fullField))}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"array")&&!e.required)return n();i["default"].required(e,t,r,a,o,"array"),(0,s.isEmptyValue)(t,"array")||(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var i=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,a.isEmptyValue)(t)&&!e.required)return n();s["default"].required(e,t,r,i,o),void 0!==t&&s["default"].type(e,t,r,i,o)}n(i)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(5),i=n(7),s=r(i);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),(0,s.isEmptyValue)(t)||(i["default"].type(e,t,r,a,o),t&&i["default"].range(e,t.getTime(),r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],u=e.required||!e.required&&r.hasOwnProperty(e.field);if(u){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o), t&&i["default"][l](e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5),l="enum";t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={string:n(148),method:n(143),number:n(144),"boolean":n(137),regexp:n(147),integer:n(142),"float":n(140),array:n(136),object:n(145),"enum":n(139),pattern:n(146),email:n(33),url:n(33),date:n(138),hex:n(33)},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&i["default"].type(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),void 0!==t&&i["default"].type(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"string")&&!e.required)return n();i["default"].required(e,t,r,a,o),(0,s.isEmptyValue)(t,"string")||i["default"].pattern(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t)&&!e.required)return n();i["default"].required(e,t,r,a,o),(0,s.isEmptyValue)(t)||i["default"].type(e,t,r,a,o)}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=[],l=e.required||!e.required&&r.hasOwnProperty(e.field);if(l){if((0,s.isEmptyValue)(t,"string")&&!e.required)return n();i["default"].required(e,t,r,a,o,"string"),(0,s.isEmptyValue)(t,"string")||(i["default"].type(e,t,r,a,o),i["default"].range(e,t,r,a,o),i["default"].pattern(e,t,r,a,o),e.whitespace===!0&&i["default"].whitespace(e,t,r,a,o))}n(a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(7),i=r(a),s=n(5);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function u(e){var t=e.getBoundingClientRect(),n=document.body,r=e.clientTop||n.clientTop||0,o=e.clientLeft||n.clientLeft||0,a=l(window,!0),i=l(window);return{top:t.top+a-r,left:t.left+i-o}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=n(1),d=r(f),h=n(4),y=r(h),v=n(23),m=r(v),g=n(2),b=r(g),P=n(17),O=r(P),C=(p=c=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.handleScroll=function(){var e=r.props,t=e.offsetTop,n=e.offsetBottom,o=e.offset;t=t||o;var a=l(window,!0),i=u(y["default"].findDOMNode(r)),s={width:y["default"].findDOMNode(r.refs.fixedNode).offsetWidth,height:y["default"].findDOMNode(r.refs.fixedNode).offsetHeight},c={};"number"!=typeof t&&"number"!=typeof n?(c.top=!0,t=0):(c.top="number"==typeof t,c.bottom="number"==typeof n),a>i.top-t&&c.top?r.state.affixStyle||r.setState({affixStyle:{position:"fixed",top:t,left:i.left,width:y["default"].findDOMNode(r).offsetWidth}},function(){return r.props.onChange(!!r.state.affixStyle)}):a<i.top+s.height+n-window.innerHeight&&c.bottom?r.state.affixStyle||r.setState({affixStyle:{position:"fixed",bottom:n,left:i.left,width:y["default"].findDOMNode(r).offsetWidth}},function(){return r.props.onChange(!!r.state.affixStyle)}):r.state.affixStyle&&r.setState({affixStyle:null},function(){return r.props.onChange(!!r.state.affixStyle)})},r.state={affixStyle:null},r}return s(t,e),t.prototype.componentDidMount=function(){(0,O["default"])(!("offset"in this.props),"`offset` prop of Affix is deprecated, use `offsetTop` instead."),this.scrollEvent=(0,m["default"])(window,"scroll",this.handleScroll),this.resizeEvent=(0,m["default"])(window,"resize",this.handleScroll)},t.prototype.componentWillUnmount=function(){this.scrollEvent&&this.scrollEvent.remove(),this.resizeEvent&&this.resizeEvent.remove()},t.prototype.render=function(){var e=(0,b["default"])({"ant-affix":this.state.affixStyle});return d["default"].createElement("div",this.props,d["default"].createElement("div",{className:e,ref:"fixedNode",style:this.state.affixStyle},this.props.children))},t}(d["default"].Component),c.propTypes={offsetTop:d["default"].PropTypes.number,offsetBottom:d["default"].PropTypes.number},c.defaultProps={onChange:function(){}},p);t["default"]=C,e.exports=t["default"]},[460,419],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(4),h=r(d),y=n(8),v=r(y),m=n(6),g=r(m),b=n(2),P=r(b),O=(c=u=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.handleClose=function(e){e.preventDefault();var t=h["default"].findDOMNode(r);t.style.height=t.offsetHeight+"px",t.style.height=t.offsetHeight+"px",r.setState({closing:!1}),r.props.onClose.call(r,e)},r.animationEnd=function(){r.setState({closed:!0,closing:!0})},r.state={closing:!0,closed:!1},r}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.closable,r=t.description,o=t.type,i=t.prefixCls,s=t.message,l=t.closeText,u=t.showIcon,c="";switch(o){case"success":c="check-circle";break;case"info":c="info-circle";break;case"error":c="cross-circle";break;case"warning":c="exclamation-circle";break;default:c="default"}r&&(c+="-o");var p=(0,P["default"])((e={},a(e,i,!0),a(e,i+"-"+o,!0),a(e,i+"-close",!this.state.closing),a(e,i+"-with-description",!!r),a(e,i+"-no-icon",!u),e));return l&&(n=!0),this.state.closed?null:f["default"].createElement(v["default"],{component:"",showProp:"data-show",transitionName:"slide-up",onEnd:this.animationEnd},f["default"].createElement("div",{"data-show":this.state.closing,className:p},u?f["default"].createElement(g["default"],{className:"ant-alert-icon",type:c}):null,f["default"].createElement("span",{className:i+"-message"},s),f["default"].createElement("span",{className:i+"-description"},r),n?f["default"].createElement("a",{onClick:this.handleClose,className:i+"-close-icon"},l||f["default"].createElement(g["default"],{type:"cross"})):null))},t}(f["default"].Component),u.defaultProps={prefixCls:"ant-alert",showIcon:!1,onClose:function(){},type:"info"},c);t["default"]=O,e.exports=t["default"]},[460,420],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(e){return e?e.toString().split("").reverse().map(function(e){return Number(e)}):[]}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(4),y=n(52),v=r(y),m=(c=u=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.state={animateStarted:!0,count:n.count},r}return s(t,e),t.prototype.componentDidMount=function(){(0,v["default"])()||((0,h.findDOMNode)(this).className+=" not-support-css-animation")},t.prototype.getPositionByNum=function(e,t){if(this.state.animateStarted)return 10+e;var n=l(this.state.count)[t],r=l(this.lastCount)[t];return this.state.count>this.lastCount?n>=r?10+e:20+e:n<=r?10+e:e},t.prototype.componentWillReceiveProps=function(e){var t=this;if("count"in e){if(this.state.count===e.count)return;this.lastCount=this.state.count,this.setState({animateStarted:!0},function(){setTimeout(function(){t.setState({animateStarted:!1,count:e.count},function(){t.props.onAnimated()})},5)})}},t.prototype.renderNumberList=function(e){for(var t=[],n=0;n<30;n++){var r=e===n?"current":null;t.push(d["default"].createElement("p",{key:n,className:r},n%10))}return t},t.prototype.renderCurrentNumber=function(e,t){var n=this.getPositionByNum(e,t),r=this.props.height,o=this.state.animateStarted||void 0===l(this.lastCount)[t];return(0,f.createElement)("span",{className:this.props.prefixCls+"-only",style:{transition:o&&"none",WebkitTransform:"translate3d(0, "+-n*r+"px, 0)",transform:"translate3d(0, "+-n*r+"px, 0)",height:r},key:t},this.renderNumberList(n))},t.prototype.renderNumberElement=function(){var e=this,t=this.state;return!t.count||isNaN(t.count)?t.count:l(t.count).map(function(t,n){return e.renderCurrentNumber(t,n)}).reverse()},t.prototype.render=function(){var e=p({},this.props,{className:this.props.prefixCls+" "+this.props.className});return(0,f.createElement)(this.props.component,e,this.renderNumberElement())},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-scroll-number",count:null,component:"sup",onAnimated:function(){},height:18},u.propTypes={count:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.number]),component:d["default"].PropTypes.string,onAnimated:d["default"].PropTypes.func,height:d["default"].PropTypes.number},c);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(8),y=r(h),v=n(153),m=r(v),g=n(2),b=r(g),P=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.count,r=t.prefixCls,o=t.overflowCount,i=t.className,s=t.style,l=t.children,u=this.props.dot;n=n>o?o+"+":n,u&&(n="");var c=!(n&&"0"!==n||u),f=r+(u?"-dot":"-count"),h=(0,b["default"])((e={},a(e,i,!!i),a(e,r,!0),a(e,r+"-not-a-wrapper",!l),e));return d["default"].createElement("span",p({className:h,title:n},this.props,{style:null}),l,d["default"].createElement(y["default"],{component:"",showProp:"data-show",transitionName:r+"-zoom",transitionAppear:!0},c?null:d["default"].createElement(m["default"],{"data-show":!c,className:f,count:n,style:s})))},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-badge",count:null,dot:!1,overflowCount:99},u.propTypes={count:d["default"].PropTypes.oneOfType([d["default"].PropTypes.string,d["default"].PropTypes.number]),dot:d["default"].PropTypes.bool,overflowCount:d["default"].PropTypes.number},c);t["default"]=P,e.exports=t["default"]},[460,421],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(54),d=r(f),h=function(e,t,n){if(!e)return null;var r=Object.keys(n).join("|"),o=e.replace(new RegExp(":("+r+")","g"),function(e,t){return n[t]||e});return p["default"].createElement("span",null,o)},y=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=void 0,t=this.props,n=t.separator,r=t.prefixCls,o=t.routes,a=t.params,i=t.children,s=t.linkRender,l=t.nameRender;return o&&o.length>0?!function(){var t=[],r=o.length-1;e=o.map(function(e,o){e.path=e.path||"";var i=e.path.replace(/^\//,"");Object.keys(a).forEach(function(e){i=i.replace(":"+e,a[e])}),i&&t.push(i);var u=l(e.breadcrumbName,e,a);if(u){var c=o===r?u:s("/"+t.join("/"),u,t);return p["default"].createElement(d["default"],{separator:n,key:e.breadcrumbName||o},c)}return null})}():e=p["default"].Children.map(i,function(e,t){return(0,c.cloneElement)(e,{separator:n,key:t})}),p["default"].createElement("div",{className:r},e)},t}(p["default"].Component),l.defaultProps={prefixCls:"ant-breadcrumb",separator:"/",linkRender:function(e,t){return p["default"].createElement("a",{href:"#"+e},t)},nameRender:h},l.propTypes={prefixCls:p["default"].PropTypes.string,separator:p["default"].PropTypes.oneOfType([p["default"].PropTypes.string,p["default"].PropTypes.element]),routes:p["default"].PropTypes.array,params:p["default"].PropTypes.object,linkRender:p["default"].PropTypes.func,nameRender:p["default"].PropTypes.func},u);t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(156),a=r(o),i=n(54),s=r(i);a["default"].Item=s["default"],t["default"]=a["default"],e.exports=t["default"]},[460,422],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e){var t,n=e.size,r=e.className,i=a(e,["size","className"]),l={large:"lg",small:"sm"}[n]||"",c=(0,p["default"])((t={"ant-btn-group":!0},o(t,f+l,l),o(t,r,r),t));return u["default"].createElement("div",s({},i,{className:c}))}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=i;var l=n(1),u=r(l),c=n(2),p=r(c),f="ant-btn-group-";i.propTypes={size:u["default"].PropTypes.oneOf(["large","small"])},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function c(e){return"string"==typeof e}function p(e){return c(e.type)&&w(e.props.children)?m["default"].cloneElement(e,{},e.props.children.split("").join(" ")):c(e)?(w(e)&&(e=e.split("").join(" ")),m["default"].createElement("span",null,e)):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var f,d,h,y=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},v=n(1),m=r(v),g=n(2),b=r(g),P=n(4),O=n(6),C=r(O),T=/^[\u4e00-\u9fa5]{2}$/,w=T.test.bind(T),x=(d=f=function(e){function t(){var n,r,o;s(this,t);for(var a=arguments.length,i=Array(a),u=0;u<a;u++)i[u]=arguments[u];return n=r=l(this,e.call.apply(e,[this].concat(i))),h.call(r),o=n,l(r,o)}return u(t,e),t.prototype.componentWillUnmount=function(){this.clickedTimeout&&clearTimeout(this.clickedTimeout),this.timeout&&clearTimeout(this.timeout)},t.prototype.render=function(){var e,t=this.props,n=t.type,r=t.shape,o=t.size,s=t.className,l=t.htmlType,u=t.children,c=t.icon,f=t.loading,d=t.prefixCls,h=i(t,["type","shape","size","className","htmlType","children","icon","loading","prefixCls"]),v={large:"lg",small:"sm"}[o]||"",g=(0,b["default"])((e={},a(e,d,!0),a(e,d+"-"+n,n),a(e,d+"-"+r,r),a(e,d+"-"+v,v),a(e,d+"-icon-only",!u&&c),a(e,d+"-loading",f),a(e,s,s),e)),P=f?"loading":c,O=m["default"].Children.map(u,p);return m["default"].createElement("button",y({},h,{type:l||"button",className:g,onMouseUp:this.handleMouseUp,onClick:this.handleClick}),P?m["default"].createElement(C["default"],{type:P}):null,O)},t}(m["default"].Component),f.defaultProps={prefixCls:"ant-btn",onClick:function(){},loading:!1},f.propTypes={type:m["default"].PropTypes.string,shape:m["default"].PropTypes.oneOf(["circle","circle-outline"]),size:m["default"].PropTypes.oneOf(["large","default","small"]),htmlType:m["default"].PropTypes.oneOf(["submit","button","reset"]),onClick:m["default"].PropTypes.func,loading:m["default"].PropTypes.bool,className:m["default"].PropTypes.string,icon:m["default"].PropTypes.string},h=function(){var e=this;this.clearButton=function(t){t.className=t.className.replace(" "+e.props.prefixCls+"-clicked","")},this.handleClick=function(){var t,n=(0,P.findDOMNode)(e);e.clearButton(n),e.clickedTimeout=setTimeout(function(){return n.className+=" "+e.props.prefixCls+"-clicked"},10),clearTimeout(e.timeout),e.timeout=setTimeout(function(){return e.clearButton(n)},500),(t=e.props).onClick.apply(t,arguments)},this.handleMouseUp=function(t){(0,P.findDOMNode)(e).blur(),e.props.onMouseUp&&e.props.onMouseUp(t)}},d);t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(55),h=n(27),y=r(h),v=n(26),m=y["default"].Option,g=(c=u=function(e){function t(){var n,r,o;a(this,t);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return n=r=i(this,e.call.apply(e,[this].concat(l))),r.onYearChange=function(e){var t=r.props.value.clone();t.setYear(parseInt(e,10)),r.props.onValueChange(t)},r.onMonthChange=function(e){var t=r.props.value.clone();t.setMonth(parseInt(e,10)),r.props.onValueChange(t)},r.onTypeChange=function(e){r.props.onTypeChange(e.target.value)},o=n,i(r,o)}return s(t,e),t.prototype.getYearSelectElement=function(e){for(var t=this.props,n=t.yearSelectOffset,r=t.yearSelectTotal,o=t.locale,a=t.prefixCls,i=t.fullscreen,s=e-n,l=s+r,u="\u5e74"===o.year?"\u5e74":"",c=[],p=s;p<l;p++)c.push(f["default"].createElement(m,{key:""+p},p+u));return f["default"].createElement(y["default"],{style:{width:75},size:i?null:"small",dropdownMatchSelectWidth:!1,dropdownMenuStyle:{minWidth:103},className:a+"-year-select",onChange:this.onYearChange,value:String(e)},c)},t.prototype.getMonthSelectElement=function(e){for(var t=this.props,n=t.locale.format.months,r=t.prefixCls,o=t.fullscreen,a=[],i=0;i<12;i++)a.push(f["default"].createElement(m,{key:""+i},n[i]));return f["default"].createElement(y["default"],{style:{minWidth:70},dropdownMenuStyle:{minWidth:125},size:o?null:"small",dropdownMatchSelectWidth:!1,className:r+"-month-select",value:String(e),onChange:this.onMonthChange},a)},t.prototype.render=function(){var e=this.props,t=e.type,n=e.value,r=e.prefixCls,o=e.locale,a=this.getYearSelectElement(n.getYear()),i="date"===t?this.getMonthSelectElement(n.getMonth()):null,s=f["default"].createElement(v.Group,{onChange:this.onTypeChange,value:t},f["default"].createElement(v.Button,{value:"date"},o.month),f["default"].createElement(v.Button,{value:"month"},o.year));return f["default"].createElement("div",{className:r+"-header"},a,i,s)},t}(f["default"].Component),u.defaultProps={prefixCls:d.PREFIX_CLS+"-header",yearSelectOffset:10,yearSelectTotal:20,onValueChange:l,onTypeChange:l},u.propTypes={value:p.PropTypes.object,locale:p.PropTypes.object,yearSelectOffset:p.PropTypes.number,yearSelectTotal:p.PropTypes.number,onValueChange:p.PropTypes.func,onTypeChange:p.PropTypes.func,prefixCls:p.PropTypes.string,selectPrefixCls:p.PropTypes.string,type:p.PropTypes.string},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){return null}function u(e){return e<10?"0"+e:""+e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f,d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=n(1),y=r(h),v=n(9),m=r(v),g=n(163),b=r(g),P=n(289),O=r(P),C=n(55),T=n(161),w=r(T),x=(p=c=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return f.call(r),r.state={value:r.parseDateFromValue(n.value||new Date),mode:n.mode},r}return s(t,e),t.prototype.parseDateFromValue=function(e){var t=new m["default"](this.getLocale());return t.setTime(+e),t},t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:this.parseDateFromValue(e.value)})},t.prototype.render=function(){var e=this.props,t=this.state,n=t.value,r=t.mode,o=e.prefixCls,a=e.style,i=e.className,s=e.fullscreen,u="year"===r?"month":"date",c=this.getLocale(),p=i||"";return s&&(p+=" "+o+"-fullscreen"),y["default"].createElement("div",{className:p,style:a},y["default"].createElement(w["default"],{fullscreen:s,type:u,value:n,locale:c.lang,prefixCls:o,onTypeChange:this.setType,onValueChange:this.setValue}),y["default"].createElement(O["default"],d({},e,{Select:l,locale:c.lang,type:u,prefixCls:o,showHeader:!1,value:n,monthCellRender:this.monthCellRender,dateCellRender:this.dateCellRender})))},t}(y["default"].Component),c.defaultProps={monthCellRender:l,dateCellRender:l,locale:{},fullscreen:!0,prefixCls:C.PREFIX_CLS,onPanelChange:l,mode:"month"},c.propTypes={monthCellRender:h.PropTypes.func,dateCellRender:h.PropTypes.func,fullscreen:h.PropTypes.bool,locale:h.PropTypes.object,prefixCls:h.PropTypes.string,className:h.PropTypes.string,style:h.PropTypes.object,onPanelChange:h.PropTypes.func,value:h.PropTypes.instanceOf(Date)},c.contextTypes={antLocale:h.PropTypes.object},f=function(){var e=this;this.getLocale=function(){var t=e.props,n=b["default"],r=e.context;r&&r.antLocale&&r.antLocale.Calendar&&(n=r.antLocale.Calendar);var o=d({},n,t.locale);return o.lang=d({},n.lang,t.locale.lang),o},this.monthCellRender=function(t,n){var r=e.props.prefixCls,o=t.getMonth();return y["default"].createElement("div",{className:r+"-month"},y["default"].createElement("div",{className:r+"-value"},n.format.shortMonths[o]),y["default"].createElement("div",{className:r+"-content"},e.props.monthCellRender(t)))},this.dateCellRender=function(t){var n=e.props.prefixCls;return y["default"].createElement("div",{className:n+"-date"},y["default"].createElement("div",{className:n+"-value"},u(t.getDayOfMonth())),y["default"].createElement("div",{className:n+"-content"},e.props.dateCellRender(t)))},this.setValue=function(t){"value"in e.props||e.state.value===t||e.setState({value:t}),e.props.onPanelChange(t,e.state.mode)},this.setType=function(t){var n="date"===t?"month":"year";e.state.mode!==n&&(e.setState({mode:n}),e.props.onPanelChange(e.state.value,n))}},p);t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(56)},function(e,t,n){"use strict";n(3),n(424),n(28),n(37)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(2),c=r(u);t["default"]=function(e){var t,n=e.prefixCls,r=void 0===n?"ant-card":n,s=e.className,u=e.children,p=e.extra,f=e.bodyStyle,d=e.title,h=e.loading,y=e.bordered,v=void 0===y||y,m=a(e,["prefixCls","className","children","extra","bodyStyle","title","loading","bordered"]),g=(0,c["default"])((t={},o(t,r,!0),o(t,s,!!s),o(t,r+"-loading",h),o(t,r+"-bordered",v),t));h&&(u=l["default"].createElement("div",null,l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588"),l["default"].createElement("p",null,"\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u3000\u2588\u2588\u2588"))); var b=d?l["default"].createElement("div",{className:r+"-head"},l["default"].createElement("h3",{className:r+"-head-title"},d)):null;return l["default"].createElement("div",i({},m,{className:g}),b,p?l["default"].createElement("div",{className:r+"-extra"},p):null,l["default"].createElement("div",{className:r+"-body",style:f},u))},e.exports=t["default"]},[460,425],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(407),f=r(p),d=n(1),h=r(d);if("undefined"!=typeof window){var y=function(){return{matches:!1,addListener:function(){},removeListener:function(){}}};window.matchMedia=window.matchMedia||y}var v=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=c({},this.props);"fade"===e.effect&&(e.fade=!0,e.draggable=!1);var t="ant-carousel";return e.vertical&&(t+=" ant-carousel-vertical"),h["default"].createElement("div",{className:t},h["default"].createElement(f["default"],e))},t}(h["default"].Component),l.defaultProps={dots:!0,arrows:!1},u);t["default"]=v,e.exports=t["default"]},[460,426],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f,d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h=n(1),y=r(h),v=n(301),m=r(v),g=n(60),b=r(g),P=n(6),O=r(P),C=n(50),T=r(C),w=n(2),x=r(w),E=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));f.call(r);var o=void 0;return"value"in n?o=n.value:"defaultValue"in n&&(o=n.defaultValue),r.state={value:o||[],popupVisible:!1},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value||[]})},t.prototype.getLabel=function(){var e=this,t=this.props,n=t.options,r=t.displayRender,o=(0,T["default"])(n,function(t,n){return t.value===e.state.value[n]}),a=o.map(function(e){return e.label});return r(a,o)},t.prototype.render=function(){var e,t,n=this.props,r=n.prefixCls,o=n.children,s=n.placeholder,l=n.size,u=n.disabled,c=n.className,p=n.style,f=n.allowClear,h=i(n,["prefixCls","children","placeholder","size","disabled","className","style","allowClear"]),v=(0,x["default"])({"ant-input-lg":"large"===l,"ant-input-sm":"small"===l}),g=f&&!u&&this.state.value.length>0?y["default"].createElement(O["default"],{type:"cross-circle",className:r+"-picker-clear",onClick:this.clearSelection}):null,P=(0,x["default"])((e={},a(e,r+"-picker-arrow",!0),a(e,r+"-picker-arrow-expand",this.state.popupVisible),e)),C=(0,x["default"])((t={},a(t,c,!!c),a(t,r+"-picker",!0),a(t,r+"-picker-disabled",u),t));return delete h.onChange,y["default"].createElement(m["default"],d({},n,{value:this.state.value,popupVisible:this.state.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,onChange:this.handleChange}),o||y["default"].createElement("span",{style:p,className:C},y["default"].createElement(b["default"],d({},h,{placeholder:this.state.value&&this.state.value.length>0?null:s,className:r+"-input ant-input "+v,value:null,disabled:u,readOnly:!0})),y["default"].createElement("span",{className:r+"-picker-label"},this.getLabel()),g,y["default"].createElement(O["default"],{type:"down",className:P})))},t}(y["default"].Component),c.defaultProps={prefixCls:"ant-cascader",placeholder:"Please select",transitionName:"slide-up",popupPlacement:"bottomLeft",onChange:function(){},options:[],displayRender:function(e){return e.join(" / ")},disabled:!1,allowClear:!0,onPopupVisibleChange:function(){}},f=function(){var e=this;this.handleChange=function(t,n){e.setValue(t,n)},this.handlePopupVisibleChange=function(t){e.setState({popupVisible:t}),e.props.onPopupVisibleChange(t)},this.setValue=function(t){var n=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];"value"in e.props||e.setState({value:t}),e.props.onChange(t,n)},this.clearSelection=function(t){t.preventDefault(),t.stopPropagation(),e.setValue([]),e.setState({popupVisible:!1})}},p);t["default"]=E,e.exports=t["default"]},[461,427],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p,f=n(1),d=r(f),h=n(18),y=r(h),v=n(15),m=r(v),g=(c=u=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));p.call(r);var o=void 0;return"value"in n?o=n.value||[]:"defaultValue"in n&&(o=n.defaultValue||[]),r.state={value:o},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.value||[]})},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return m["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getOptions=function(){var e=this.props.options;return e.map(function(e){return"string"==typeof e?{label:e,value:e}:e})},t.prototype.render=function(){var e=this,t=this.getOptions();return d["default"].createElement("div",{className:"ant-checkbox-group"},t.map(function(t){return d["default"].createElement(y["default"],{disabled:"disabled"in t?t.disabled:e.props.disabled,checked:e.state.value.indexOf(t.value)!==-1,onChange:function(){return e.toggleOption(t)},className:"ant-checkbox-group-item",key:t.value},t.label)}))},t}(d["default"].Component),u.defaultProps={options:[],defaultValue:[],onChange:function(){}},u.propTypes={defaultValue:d["default"].PropTypes.array,value:d["default"].PropTypes.array,options:d["default"].PropTypes.array.isRequired,onChange:d["default"].PropTypes.func},p=function(){var e=this;this.toggleOption=function(t){var n=e.state.value.indexOf(t.value),r=[].concat(a(e.state.value));n===-1?r.push(t.value):r.splice(n,1),"value"in e.props||e.setState({value:r}),e.props.onChange(r)}},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(34);t["default"]=r.Col,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(49)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(306),p=r(c),f=n(1),d=r(f),h=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return d["default"].createElement(p["default"],this.props)},t}(d["default"].Component),l.Panel=p["default"].Panel,l.defaultProps={prefixCls:"ant-collapse"},u);t["default"]=h,e.exports=t["default"]},[460,429],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(95),d=r(f),h=n(94),y=r(h),v=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(y["default"],this.props)},t}(p["default"].Component),l.defaultProps={locale:d["default"],prefixCls:"ant-calendar"},u);t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(9),y=r(h),v=n(290),m=r(v),g=n(88),b=r(g),P=n(2),O=r(P),C=(u=l=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));c.call(r);var o=r.props,s=o.value,l=o.defaultValue,u=o.parseDateFromValue,p=s&&s[0]||l[0],f=s&&s[1]||l[1];return r.state={value:[u(p),u(f)]},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e){var t=e.value||[],n=e.parseDateFromValue(t[0]),r=e.parseDateFromValue(t[1]);this.setState({value:[n,r]})}},t.prototype.render=function(){var e=this,t=this.props,n=t.locale,r=new y["default"](n);r.setTime(Date.now());var o=this.props,a=o.disabledDate,i=o.showTime,s=o.getCalendarContainer,l=o.transitionName,u=o.disabled,c=o.popupStyle,f=o.align,h=o.style,v=o.onOk,g=this.state,P=(0,O["default"])({"ant-calendar-time":i}),C={onChange:this.handleChange},T={onOk:this.handleChange};t.timePicker?C.onChange=function(t){null!==t&&0!==t.length||e.handleChange(t)}:T={};var w="startPlaceholder"in this.props?t.startPlaceholder:n.lang.rangePlaceholder[0],x="endPlaceholder"in t?t.endPlaceholder:n.lang.rangePlaceholder[1],E=d["default"].createElement(m["default"],p({prefixCls:"ant-calendar",className:P,timePicker:t.timePicker,disabledDate:a,dateInputPlaceholder:[w,x],locale:n.lang,onOk:v,defaultValue:[r,r]},T));return d["default"].createElement("span",{className:t.pickerClass,style:h},d["default"].createElement(b["default"],p({formatter:t.getFormatter(),transitionName:l,disabled:u,calendar:E,value:g.value,prefixCls:"ant-calendar-picker-container",style:c,align:f,getCalendarContainer:s,onOpen:t.toggleOpen,onClose:t.toggleOpen},C),function(e){var n=e.value,r=n[0],o=n[1];return d["default"].createElement("span",{className:t.pickerInputClass,disabled:u},d["default"].createElement("input",{disabled:u,readOnly:!0,value:r?t.getFormatter().format(r):"",placeholder:w,className:"ant-calendar-range-picker-input"}),d["default"].createElement("span",{className:"ant-calendar-range-picker-separator"}," ~ "),d["default"].createElement("input",{disabled:u,readOnly:!0,value:o?t.getFormatter().format(o):"",placeholder:x,className:"ant-calendar-range-picker-input"}),d["default"].createElement("span",{className:"ant-calendar-picker-icon"}))}))},t}(d["default"].Component),l.defaultProps={defaultValue:[]},c=function(){var e=this;this.handleChange=function(t){var n=e.props;"value"in n||e.setState({value:t});var r=t[0]?new Date(t[0].getTime()):null,o=t[1]?new Date(t[1].getTime()):null,a=t[0]?n.getFormatter().format(t[0]):"",i=t[1]?n.getFormatter().format(t[1]):"";n.onChange([r,o],[a,i])}},u);t["default"]=C,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(e){var t,n,r;return n=t=function(t){function n(e){a(this,n);var o=i(this,t.call(this,e));return r.call(o),o.state={value:o.props.parseDateFromValue(o.props.value||o.props.defaultValue)},o}return s(n,t),n.prototype.componentWillReceiveProps=function(e){"value"in e&&this.setState({value:e.parseDateFromValue(e.value)})},n.prototype.render=function(){var t=this.props,n=t.locale,r=new m["default"](n);r.setTime(Date.now());var o="placeholder"in t?t.placeholder:n.lang.placeholder,a=t.showTime?t.disabledTime:null,i=(0,b["default"])({"ant-calendar-time":t.showTime,"ant-calendar-month":d["default"]===e}),s=p["default"].createElement(e,{formatter:t.getFormatter(),disabledDate:t.disabledDate,disabledTime:a,locale:n.lang,timePicker:t.timePicker,defaultValue:r,dateInputPlaceholder:o,prefixCls:"ant-calendar",className:i}),l={};return t.showTime&&(l.width=180),p["default"].createElement("span",{className:t.pickerClass,style:u({},l,t.style)},p["default"].createElement(y["default"],{transitionName:t.transitionName,disabled:t.disabled,calendar:s,value:this.state.value,prefixCls:"ant-calendar-picker-container",style:t.popupStyle,align:t.align,getCalendarContainer:t.getCalendarContainer,open:t.open,onOpen:t.toggleOpen,onClose:t.toggleOpen,onChange:this.handleChange},function(e){var n=e.value;return p["default"].createElement("span",null,p["default"].createElement("input",{disabled:t.disabled,readOnly:!0,value:n?t.getFormatter().format(n):"",placeholder:o,className:t.pickerInputClass}),p["default"].createElement("span",{className:"ant-calendar-picker-icon"}))}))},n}(p["default"].Component),r=function(){var e=this;this.handleChange=function(t){var n=e.props;"value"in n||e.setState({value:t});var r=t?new Date(t.getTime()):null;n.onChange(r,t?n.getFormatter().format(t):"")}},n}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=l;var c=n(1),p=r(c),f=n(87),d=r(f),h=n(88),y=r(h),v=n(9),m=r(v),g=n(2),b=r(g);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(94),a=r(o),i=n(87),s=r(i),l=n(178),u=r(l),c=n(181),p=r(c),f=n(177),d=r(f),h=n(176),y=r(h),v=(0,p["default"])((0,u["default"])(a["default"])),m=(0,p["default"])((0,u["default"])(s["default"]),"yyyy-MM");v.Calendar=y["default"],v.RangePicker=(0,p["default"])(d["default"],"yyyy-MM-dd"),v.MonthPicker=m,t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(430),n(13),n(73)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(e,t){var n,r;return r=n=function(t){function n(){var e,r,o;a(this,n);for(var s=arguments.length,l=Array(s),u=0;u<s;u++)l[u]=arguments[u];return e=r=i(this,t.call.apply(t,[this].concat(l))),r.getFormatter=function(){var e=r.props.format,t=new y["default"](e,r.getLocale().lang.format);return t},r.parseDateFromValue=function(e){if(e){if("string"==typeof e)return r.getFormatter().parse(e,{locale:r.getLocale()});if(e instanceof Date){var t=new m["default"](r.getLocale());return t.setTime(+e),t}}return e},r.toggleOpen=function(e){var t=e.open;r.props.toggleOpen({open:t})},o=e,i(r,o)}return s(n,t),n.prototype.getLocale=function(){var e=this.props,t=O["default"],n=this.context;n.antLocale&&n.antLocale.DatePicker&&(t=n.antLocale.DatePicker);var r=u({},t,e.locale);return r.lang=u({},t.lang,e.locale.lang),r},n.prototype.render=function(){var t=this.props,n=(0,b["default"])({"ant-calendar-picker":!0}),r=(0,b["default"])({"ant-calendar-range-picker":!0,"ant-input":!0,"ant-input-lg":"large"===t.size,"ant-input-sm":"small"===t.size}),o=this.getLocale(),a=t.showTime&&t.showTime.format,i={formatter:new y["default"](a||"HH:mm:ss",o.timePickerLocale.format),showSecond:a&&a.indexOf("ss")>=0,showHour:a&&a.indexOf("HH")>=0},s=t.showTime?p["default"].createElement(d["default"],u({},i,t.showTime,{prefixCls:"ant-time-picker",placeholder:o.timePickerLocale.placeholder,locale:o.timePickerLocale,transitionName:"slide-up"})):null;return p["default"].createElement(e,u({},t,{pickerClass:n,pickerInputClass:r,locale:o,timePicker:s,toggleOpen:this.toggleOpen,getFormatter:this.getFormatter,parseDateFromValue:this.parseDateFromValue}))},n}(p["default"].Component),n.defaultProps={format:t||"yyyy-MM-dd",transitionName:"slide-up",popupStyle:{},onChange:function(){},onOk:function(){},toggleOpen:function(){},locale:{},align:{offset:[0,-9]}},n.contextTypes={antLocale:c.PropTypes.object},r}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=l;var c=n(1),p=r(c),f=n(372),d=r(f),h=n(29),y=r(h),v=n(9),m=r(v),g=n(2),b=r(g),P=n(56),O=r(P);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(16),y=r(h),v=n(6),m=r(v),g=n(57),b=r(g),P=n(2),O=r(P),C=y["default"].Group,T=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.type,n=e.overlay,r=e.trigger,o=e.align,i=e.children,s=e.className,l=e.onClick,u=a(e,["type","overlay","trigger","align","children","className","onClick"]),c=(0,O["default"])({"ant-dropdown-button":!0,className:!!s});return d["default"].createElement(C,p({},u,{className:c}),d["default"].createElement(y["default"],{type:t,onClick:l},i),d["default"].createElement(b["default"],{align:o,overlay:n,trigger:r},d["default"].createElement(y["default"],{type:t},d["default"].createElement(m["default"],{type:"down"}))))},t}(d["default"].Component),u.defaultProps={align:{points:["tr","br"],overlay:{adjustX:1,adjustY:1},offset:[0,4],targetOffset:[0,0]},type:"default"},c);t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(2),y=r(h),v=n(15),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return m["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getChildContext=function(){return{form:this.props.form}},t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.className,o=t.style,i=(0,y["default"])((e={},a(e,n+"-horizontal",this.props.horizontal),a(e,n+"-inline",this.props.inline),a(e,r,!!r),e));return d["default"].createElement("form",p({},this.props,{className:i,style:o}),this.props.children)},t}(d["default"].Component),u.defaultProps={prefixCls:"ant-form",onSubmit:function(e){e.preventDefault()}},u.propTypes={prefixCls:d["default"].PropTypes.string,horizontal:d["default"].PropTypes.bool,inline:d["default"].PropTypes.bool,form:d["default"].PropTypes.object,children:d["default"].PropTypes.any,onSubmit:d["default"].PropTypes.func},u.childContextTypes={form:d["default"].PropTypes.object},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(2),h=r(d),y=n(15),v=r(y),m=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return v["default"].shouldComponentUpdate.apply(this,t)},t.prototype.getLayoutClass=function(e){if(!e)return"";var t=e.span,n=e.offset,r=t?"ant-col-"+t:"",o=n?" ant-col-offset-"+n:"";return r+o},t.prototype.getHelpMsg=function(){var e=this.context,t=this.props;return void 0===t.help&&e.form?this.getId()?(e.form.getFieldError(this.getId())||[]).join(", "):"":t.help},t.prototype.getOnlyControl=function(){var e=f["default"].Children.toArray(this.props.children),t=e.filter(function(e){return e.props&&"__meta"in e.props})[0];return void 0!==t?t:null},t.prototype.getChildProp=function(e){var t=this.getOnlyControl();return t&&t.props&&t.props[e]},t.prototype.getId=function(){return this.getChildProp("id")},t.prototype.getMeta=function(){return this.getChildProp("__meta")},t.prototype.renderHelp=function(){var e=this.props.prefixCls,t=this.getHelpMsg();return t?f["default"].createElement("div",{className:e+"-explain",key:"help"},t):null},t.prototype.renderExtra=function(){var e=this.props,t=e.prefixCls,n=e.extra;return n?f["default"].createElement("span",{className:t+"-extra"},n):null},t.prototype.getValidateStatus=function(){var e=this.context.form,t=e.isFieldValidating,n=e.getFieldError,r=e.getFieldValue,o=this.getId();return o?t(o)?"validating":n(o)?"error":void 0!==r(o)?"success":"":""},t.prototype.renderValidateWrapper=function(e,t,n){var r="",o=this.context.form,a=this.props,i=void 0===a.validateStatus&&o?this.getValidateStatus():a.validateStatus;return i&&(r=(0,h["default"])({"has-feedback":a.hasFeedback,"has-success":"success"===i,"has-warning":"warning"===i,"has-error":"error"===i,"is-validating":"validating"===i})),f["default"].createElement("div",{className:this.props.prefixCls+"-item-control "+r},e,t,n)},t.prototype.renderWrapper=function(e){var t=this.props.wrapperCol;return f["default"].createElement("div",{className:this.getLayoutClass(t),key:"wrapper"},e)},t.prototype.isRequired=function(){if(this.context.form){var e=this.getMeta()||{},t=e.validate||[];return t.filter(function(e){return!!e.rules}).some(function(e){return e.rules.some(function(e){return e.required})})}return!1},t.prototype.renderLabel=function(){var e,t=this.props,n=t.labelCol,r=void 0===t.required?this.isRequired():t.required,o=(0,h["default"])((e={},a(e,this.getLayoutClass(n),!0),a(e,t.prefixCls+"-item-required",r),e)),i=t.label;return"string"==typeof i&&""!==i.trim()&&(i=t.label.replace(/\uff1a|:$/,"")),t.label?f["default"].createElement("label",{htmlFor:t.id||this.getId(),className:o,key:"label"},i):null},t.prototype.renderChildren=function(){var e=this.props,t=f["default"].Children.map(e.children,function(e){return e&&"function"==typeof e.type&&!e.props.size?f["default"].cloneElement(e,{size:"large"}):e});return[this.renderLabel(),this.renderWrapper(this.renderValidateWrapper(t,this.renderHelp(),this.renderExtra()))]},t.prototype.renderFormItem=function(e){var t,n=this.props,r=n.prefixCls,o=n.style,i=(t={},a(t,r+"-item",!0),a(t,r+"-item-with-help",!!this.getHelpMsg()),a(t,""+n.className,!!n.className),t);return f["default"].createElement("div",{className:(0,h["default"])(i),style:o},e)},t.prototype.render=function(){var e=this.renderChildren();return this.renderFormItem(e)},t}(f["default"].Component),u.defaultProps={hasFeedback:!1,prefixCls:"ant-form"},u.propTypes={prefixCls:f["default"].PropTypes.string,label:f["default"].PropTypes.node,labelCol:f["default"].PropTypes.object,help:f["default"].PropTypes.oneOfType([f["default"].PropTypes.node,f["default"].PropTypes.bool]),validateStatus:f["default"].PropTypes.oneOf(["","success","warning","error","validating"]),hasFeedback:f["default"].PropTypes.bool,wrapperCol:f["default"].PropTypes.object,className:f["default"].PropTypes.string,id:f["default"].PropTypes.string,children:f["default"].PropTypes.node},u.contextTypes={form:f["default"].PropTypes.object},c);t["default"]=m,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},r={setValue:function(e,t){var r=t,o=t&&t.target;o&&(r="input"===(""+o.nodeName).toLowerCase()&&"checkbox"===o.type?o.checked:t.target.value);var a={};a[e]=r,this.setState({formData:n({},this.state.formData,a)})}};t["default"]=r,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{ "default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(183),i=r(a),s=n(184),l=r(s),u=n(185),c=r(u),p=n(315),f=r(p);i["default"].create=function(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=o({},e,{fieldNameProp:"id",fieldMetaProp:"__meta"});return(0,f["default"])(t)},i["default"].Item=l["default"],i["default"].ValueMixin=c["default"],t["default"]=i["default"],e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(432),n(61)},function(e,t,n){"use strict";n(3)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=n(318),g=r(m),b=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.className,r=t.size,o=i(t,["className","size"]),s=(0,v["default"])((e={},a(e,this.props.prefixCls+"-lg","large"===r),a(e,this.props.prefixCls+"-sm","small"===r),a(e,n,!!n),e));return h["default"].createElement(g["default"],f({className:s},o))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-input-number",step:1},p);t["default"]=b,e.exports=t["default"]},[460,433],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){var t=(0,u["default"])(o({"ant-input-group":!0,"ant-input-group-lg":"large"===e.size,"ant-input-group-sm":"small"===e.size},e.className,!!e.className));return s["default"].createElement("span",{className:t,style:e.style},e.children)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=a;var i=n(1),s=r(i),l=n(2),u=r(l);a.propTypes={children:s["default"].PropTypes.any},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function u(e){return"undefined"==typeof e||null===e?"":e}function c(e){return window.requestAnimationFrame?window.requestAnimationFrame(e):window.setTimeout(e,1)}function p(e){window.cancelAnimationFrame?window.cancelAnimationFrame(e):window.clearTimeout(e)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var f,d,h=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y=n(1),v=r(y),m=n(2),g=r(m),b=n(193),P=r(b),O=(d=f=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.handleKeyDown=function(e){13===e.keyCode&&r.props.onPressEnter(e),r.props.onKeyDown(e)},r.handleTextareaChange=function(e){r.resizeTextarea(),r.props.onChange&&r.props.onChange(e)},r.resizeTextarea=function(){var e=r.props,t=e.type,n=e.autosize;if("textarea"===t&&n&&r.refs.input){var o=n?n.minRows:null,a=n?n.maxRows:null,i=(0,P["default"])(r.refs.input,!1,o,a);r.setState({textareaStyles:i})}},r.state={textareaStyles:null},r}return l(t,e),t.prototype.componentDidMount=function(){this.resizeTextarea()},t.prototype.componentWillReceiveProps=function(e){this.props.value!==e.value&&(this.nextFrameActionId&&p(this.nextFrameActionId),this.nextFrameActionId=c(this.resizeTextarea))},t.prototype.renderLabledInput=function(e){var t,n=this.props,r=n.prefixCls+"-group",o=r+"-addon",i=n.addonBefore?v["default"].createElement("span",{className:o},n.addonBefore):null,s=n.addonAfter?v["default"].createElement("span",{className:o},n.addonAfter):null,l=(0,g["default"])((t={},a(t,n.prefixCls+"-wrapper",!0),a(t,r,i||s),t));return v["default"].createElement("span",{className:l},i,e,s)},t.prototype.renderInput=function(){var e,t=h({},this.props),n=t.prefixCls;if(!t.type)return t.children;var r=(0,g["default"])((e={},a(e,n,!0),a(e,n+"-sm","small"===t.size),a(e,n+"-lg","large"===t.size),a(e,t.className,!!t.className),e));switch("value"in t&&(t.value=u(t.value),delete t.defaultValue),t.type){case"textarea":return v["default"].createElement("textarea",h({},t,{style:h({},t.style,this.state.textareaStyles),className:r,onKeyDown:this.handleKeyDown,onChange:this.handleTextareaChange,ref:"input"}));default:return v["default"].createElement("input",h({},t,{className:r,onKeyDown:this.handleKeyDown,ref:"input"}))}},t.prototype.render=function(){return this.renderLabledInput(this.renderInput())},t}(y.Component),f.defaultProps={defaultValue:"",disabled:!1,prefixCls:"ant-input",type:"text",onPressEnter:function(){},onKeyDown:function(){},autosize:!1},f.propTypes={type:y.PropTypes.string,id:y.PropTypes.oneOfType([y.PropTypes.string,y.PropTypes.number]),size:y.PropTypes.oneOf(["small","default","large"]),disabled:y.PropTypes.bool,value:y.PropTypes.any,defaultValue:y.PropTypes.any,className:y.PropTypes.string,addonBefore:y.PropTypes.node,addonAfter:y.PropTypes.node,prefixCls:y.PropTypes.string,autosize:y.PropTypes.oneOfType([y.PropTypes.bool,y.PropTypes.object]),onPressEnter:y.PropTypes.func,onKeyDown:y.PropTypes.func},d);t["default"]=O,e.exports=t["default"]},function(e,t){"use strict";function n(e){var t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1],n=e.getAttribute("id")||e.getAttribute("data-reactid")||e.getAttribute("name");if(t&&i[n])return i[n];var r=window.getComputedStyle(e),o=r.getPropertyValue("box-sizing")||r.getPropertyValue("-moz-box-sizing")||r.getPropertyValue("-webkit-box-sizing"),s=parseFloat(r.getPropertyValue("padding-bottom"))+parseFloat(r.getPropertyValue("padding-top")),l=parseFloat(r.getPropertyValue("border-bottom-width"))+parseFloat(r.getPropertyValue("border-top-width")),u=a.map(function(e){return e+":"+r.getPropertyValue(e)}).join(";"),c={sizingStyle:u,paddingSize:s,borderSize:l,boxSizing:o};return t&&n&&(i[n]=c),c}function r(e){var t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1],r=arguments.length<=2||void 0===arguments[2]?null:arguments[2],a=arguments.length<=3||void 0===arguments[3]?null:arguments[3];s||(s=document.createElement("textarea"),document.body.appendChild(s));var i=n(e,t),l=i.paddingSize,u=i.borderSize,c=i.boxSizing,p=i.sizingStyle;s.setAttribute("style",p+";"+o),s.value=e.value||e.placeholder||"";var f=-(1/0),d=1/0,h=s.scrollHeight;if("border-box"===c?h+=u:"content-box"===c&&(h-=l),null!==r||null!==a){s.value="";var y=s.scrollHeight-l;null!==r&&(f=y*r,"border-box"===c&&(f=f+l+u),h=Math.max(f,h)),null!==a&&(d=y*a,"border-box"===c&&(d=d+l+u),h=Math.min(d,h))}return{height:h,minHeight:f,maxHeight:d}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var o="\n min-height:0 !important;\n max-height:none !important;\n height:0 !important;\n visibility:hidden !important;\n overflow:hidden !important;\n position:absolute !important;\n z-index:-1000 !important;\n top:0 !important;\n right:0 !important\n",a=["letter-spacing","line-height","padding-top","padding-bottom","font-family","font-weight","font-size","text-rendering","text-transform","width","text-indent","padding-left","padding-right","border-width","box-sizing"],i={},s=void 0;e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e){var t,n=e.span,r=e.order,i=e.offset,u=e.push,p=e.pull,d=e.className,h=e.children,y=a(e,["span","order","offset","push","pull","className","children"]),v={};["xs","sm","md","lg"].forEach(function(t){var n,r={};"number"==typeof e[t]?r.span=e[t]:"object"===l(e[t])&&(r=e[t]||{}),v=s({},v,(n={},o(n,"ant-col-"+t+"-"+r.span,void 0!==r.span),o(n,"ant-col-"+t+"-order-"+r.order,r.order),o(n,"ant-col-"+t+"-offset-"+r.offset,r.offset),o(n,"ant-col-"+t+"-push-"+r.push,r.push),o(n,"ant-col-"+t+"-pull-"+r.pull,r.pull),n))});var m=(0,f["default"])(s((t={},o(t,"ant-col-"+n,void 0!==n),o(t,"ant-col-order-"+r,r),o(t,"ant-col-offset-"+i,i),o(t,"ant-col-push-"+u,u),o(t,"ant-col-pull-"+p,p),o(t,d,!!d),t),v));return c["default"].createElement("div",s({},y,{className:m}),h)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t["default"]=i;var u=n(1),c=r(u),p=n(2),f=r(p),d=u.PropTypes.oneOfType([u.PropTypes.string,u.PropTypes.number]),h=u.PropTypes.oneOfType([u.PropTypes.object,u.PropTypes.number]);i.propTypes={span:d,order:d,offset:d,push:d,pull:d,className:u.PropTypes.string,children:u.PropTypes.node,xs:h,sm:h,md:h,lg:h},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.type,r=t.justify,o=t.align,s=t.className,l=t.gutter,u=t.style,c=t.children,p=i(t,["type","justify","align","className","gutter","style","children"]),y=(0,v["default"])((e={"ant-row":!n},a(e,"ant-row-"+n,n),a(e,"ant-row-"+n+"-"+r,r),a(e,"ant-row-"+n+"-"+o,o),a(e,s,s),e)),m=l>0?f({marginLeft:l/-2,marginRight:l/-2},u):u,g=d.Children.map(c,function(e){return e?(0,d.cloneElement)(e,{style:l>0?f({paddingLeft:l/2,paddingRight:l/2},e.props.style):e.props.style}):null});return h["default"].createElement("div",f({},p,{className:y,style:m}),g)},t}(h["default"].Component),c.defaultProps={gutter:0},c.propTypes={type:h["default"].PropTypes.string,align:h["default"].PropTypes.string,justify:h["default"].PropTypes.string,className:h["default"].PropTypes.string,children:h["default"].PropTypes.node,gutter:h["default"].PropTypes.number},p);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(63),d=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.getChildContext=function(){return{antLocale:this.props.locale}},t.prototype.componentDidMount=function(){this.componentDidUpdate()},t.prototype.componentDidUpdate=function(){var e=this.props.locale;(0,f.changeConfirmLocale)(e&&e.Modal)},t.prototype.componentWillUnMount=function(){(0,f.changeConfirmLocale)()},t.prototype.render=function(){return p["default"].Children.only(this.props.children)},t}(p["default"].Component),l.propTypes={locale:p["default"].PropTypes.object},l.childContextTypes={antLocale:p["default"].PropTypes.object},u);t["default"]=d,e.exports=t["default"]},function(e,t){"use strict"},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(21),y=r(h),v=n(53),m=r(v),g=(c=u=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.handleClick=function(e){r.setOpenKeys([]),r.props.onClick(e)},r.handleOpenKeys=function(e){var t=e.openKeys;r.setOpenKeys(t),r.props.onOpen(e)},r.handleCloseKeys=function(e){var t=e.openKeys;r.setOpenKeys(t),r.props.onClose(e)},r.state={openKeys:[]},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){"inline"===this.props.mode&&"inline"!==e.mode&&(this.switchModeFromInline=!0),"openKeys"in e&&this.setOpenKeys(e.openKeys)},t.prototype.setOpenKeys=function(e){"openKeys"in this.props||this.setState({openKeys:e})},t.prototype.render=function(){var e=this.props.openAnimation||this.props.openTransitionName;if(!e)switch(this.props.mode){case"horizontal":e="slide-up";break;case"vertical":this.switchModeFromInline?(e="",this.switchModeFromInline=!1):e="zoom-big";break;case"inline":e=m["default"]}var t={},n=this.props.className+" "+this.props.prefixCls+"-"+this.props.theme;return t="inline"!==this.props.mode?{openKeys:this.state.openKeys,onClick:this.handleClick,onOpen:this.handleOpenKeys,onClose:this.handleCloseKeys,openTransitionName:e,className:n}:{openAnimation:e,className:n},d["default"].createElement(y["default"],p({},this.props,t))},t}(d["default"].Component),u.Divider=h.Divider,u.Item=h.Item,u.SubMenu=h.SubMenu,u.ItemGroup=h.ItemGroup,u.defaultProps={prefixCls:"ant-menu",onClick:l,onOpen:l,onClose:l,className:"",theme:"light"},c);t["default"]=g,e.exports=t["default"]},[460,435],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return h=h||u["default"].newInstance({prefixCls:v,transitionName:"move-up",style:{top:d}})}function a(e){var t=arguments.length<=1||void 0===arguments[1]?f:arguments[1],n=arguments[2],r=arguments[3],a={info:"info-circle",success:"check-circle",error:"cross-circle",warning:"exclamation-circle",loading:"loading"}[n],i=o();return i.notice({key:y,duration:t,style:{},content:s["default"].createElement("div",{className:v+"-custom-content "+v+"-"+n},s["default"].createElement(p["default"],{type:a}),s["default"].createElement("span",null,e)),onClose:r}),function(){var e=y++;return function(){i.removeNotice(e)}}()}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(103),u=r(l),c=n(6),p=r(c),f=1.5,d=void 0,h=void 0,y=1,v="ant-message";t["default"]={info:function(e,t,n){return a(e,t,"info",n)},success:function(e,t,n){return a(e,t,"success",n)},error:function(e,t,n){return a(e,t,"error",n)},warn:function(e,t,n){return a(e,t,"warning",n)},warning:function(e,t,n){return a(e,t,"warning",n)},loading:function(e,t,n){return a(e,t,"loading",n)},config:function(e){"top"in e&&(d=e.top),"duration"in e&&(f=e.duration),"prefixCls"in e&&(v=e.prefixCls)},destroy:function(){h&&(h.destroy(),h=null)}},e.exports=t["default"]},[460,436],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){function t(){p.setState({visible:!1}),c["default"].unmountComponentAtNode(u),u.parentNode.removeChild(u)}function n(){var e=s.onCancel;if(e){var n=void 0;e.length?n=e(t):(n=e(),n||t()),n&&n.then&&n.then(t)}else t()}function r(){var e=s.onOk;if(e){var n=void 0;e.length?n=e(t):(n=e(),n||t()),n&&n.then&&n.then(t)}else t()}var a,s=i({},e),u=document.createElement("div");document.body.appendChild(u);var p=void 0;s.iconType=s.iconType||"question-circle";var d=s.width||416,y=s.style||{};"okCancel"in s||(s.okCancel=!0);var m=(0,b.getConfirmLocale)();s.okText=s.okText||(s.okCancel?m.okText:m.justOkText),s.cancelText=s.cancelText||m.cancelText;var P=l["default"].createElement("div",{className:"ant-confirm-body"},l["default"].createElement(h["default"],{type:s.iconType}),l["default"].createElement("span",{className:"ant-confirm-title"},s.title),l["default"].createElement("div",{className:"ant-confirm-content"},s.content)),O=null;O=s.okCancel?l["default"].createElement("div",{className:"ant-confirm-btns"},l["default"].createElement(v["default"],{type:"ghost",size:"large",onClick:n},s.cancelText),l["default"].createElement(v["default"],{type:"primary",size:"large",onClick:r},s.okText)):l["default"].createElement("div",{className:"ant-confirm-btns"},l["default"].createElement(v["default"],{type:"primary",size:"large",onClick:r},s.okText));var C=(0,g["default"])((a={"ant-confirm":!0},o(a,"ant-confirm-"+s.type,!0),o(a,s.className,!!s.className),a));c["default"].render(l["default"].createElement(f["default"],{className:C,visible:!0,closable:!1,title:"",transitionName:"zoom",footer:"",maskTransitionName:"fade",style:y,width:d},l["default"].createElement("div",{style:{zoom:1,overflow:"hidden"}},P," ",O)),u,function(){p=this})}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t["default"]=a;var s=n(1),l=r(s),u=n(4),c=r(u),p=n(62),f=r(p),d=n(6),h=r(d),y=n(16),v=r(y),m=n(2),g=r(m),b=n(63);e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(62),i=r(a),s=n(202),l=r(s);i["default"].info=function(e){var t=o({type:"info",iconType:"info-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].success=function(e){var t=o({type:"success",iconType:"check-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].error=function(e){var t=o({type:"error",iconType:"cross-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].warning=i["default"].warn=function(e){var t=o({type:"warning",iconType:"exclamation-circle",okCancel:!1},e);return(0,l["default"])(t)},i["default"].confirm=function(e){var t=o({type:"confirm",okCancel:!0},e);return(0,l["default"])(t)},t["default"]=i["default"],e.exports=t["default"]},[462,437],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){return h?h:h=c["default"].newInstance({prefixCls:"ant-notification",style:{top:d,right:0}})}function a(e){var t=e.prefixCls||"ant-notification-notice",n=void 0;n=void 0===e.duration?y:e.duration;var r="";switch(e.icon){case"success":r="check-circle-o";break;case"info":r="info-circle-o";break;case"error":r="cross-circle-o";break;case"warning":r="exclamation-circle-o";break;default:r="info-circle"}o().notice({content:l["default"].createElement("div",{className:t+"-content "+(e.icon?t+"-with-icon":"")},e.icon?l["default"].createElement(f["default"],{className:t+"-icon "+t+"-icon-"+e.icon,type:r}):null,l["default"].createElement("div",{className:t+"-message"},e.message),l["default"].createElement("div",{className:t+"-description"},e.description),e.btn?l["default"].createElement("span",{className:t+"-btn"},e.btn):null),duration:n,closable:!0,onClose:e.onClose,key:e.key,style:{}})}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(103),c=r(u),p=n(6),f=r(p),d=24,h=void 0,y=4.5,v={open:function(e){a(e)},close:function(e){h&&h.removeNotice(e)},config:function(e){"top"in e&&(d=e.top),"duration"in e&&(y=e.duration)},destroy:function(){h&&(h.destroy(),h=null)}};["success","info","warning","error"].forEach(function(e){v[e]=function(t){return v.open(i({},t,{icon:e}))}}),v.warn=v.warning,t["default"]=v,e.exports=t["default"]},[460,438],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(27),h=r(d),y=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return f["default"].createElement(h["default"],c({size:"small"},this.props))},t}(f["default"].Component),l.Option=h["default"].Option,u);t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(332),h=r(d),y=n(27),v=r(y),m=n(207),g=r(m),b=n(209),P=r(b),O=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props.className,t=v["default"],n=void 0;return n=this.context.antLocale&&this.context.antLocale.Pagination?this.context.antLocale.Pagination:this.props.locale,"small"===this.props.size&&(e+=" mini",t=g["default"]),f["default"].createElement(h["default"],c({selectComponentClass:t,selectPrefixCls:"ant-select"},this.props,{locale:n,className:e}))},t}(f["default"].Component),l.defaultProps={locale:P["default"],className:"",prefixCls:"ant-pagination"},l.contextTypes={antLocale:f["default"].PropTypes.object},u);t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(105)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(38),y=r(h),v=n(6),m=r(v),g=n(16),b=r(g),P=n(35),O=r(P),C=(0,O["default"])(),T="ant-popover",w=function(){},x=(c=u=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.confirm=function(){r.setVisible(!1),r.props.onConfirm.call(r)},r.cancel=function(){r.setVisible(!1),r.props.onCancel.call(r)},r.onVisibleChange=function(e){r.setVisible(e)},r.state={visible:!1},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){"visible"in e&&this.setState({visible:e.visible})},t.prototype.setVisible=function(e){"visible"in this.props||this.setState({visible:e}),this.props.onVisibleChange(e)},t.prototype.render=function(){var e=this.props,t=e.title,n=e.placement,r=e.overlayStyle,o=e.trigger,i=a(e,["title","placement","overlayStyle","trigger"]),s=this.props,l=s.okText,u=s.cancelText;this.context.antLocale&&this.context.antLocale.Popconfirm&&(l=l||this.context.antLocale.Popconfirm.okText,u=u||this.context.antLocale.Popconfirm.cancelText);var c=d["default"].createElement("div",null,d["default"].createElement("div",{className:T+"-inner-content"},d["default"].createElement("div",{className:T+"-message"},d["default"].createElement(m["default"],{type:"exclamation-circle"}),d["default"].createElement("div",{className:T+"-message-title"},t)),d["default"].createElement("div",{className:T+"-buttons"},d["default"].createElement(b["default"],{onClick:this.cancel,type:"ghost",size:"small"},u||"\u53d6\u6d88"),d["default"].createElement(b["default"],{onClick:this.confirm,type:"primary",size:"small"},l||"\u786e\u5b9a"))));return d["default"].createElement(y["default"],p({},i,{placement:n,builtinPlacements:C,overlayStyle:r,prefixCls:T,onVisibleChange:this.onVisibleChange,transitionName:this.props.transitionName,visible:this.state.visible,trigger:o,overlay:c}),this.props.children)},t}(d["default"].Component),u.defaultProps={transitionName:"zoom-big",placement:"top",trigger:"click",overlayStyle:{},onConfirm:w,onCancel:w,onVisibleChange:w},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=x,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(66)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(38),h=r(d),y=n(35),v=r(y),m=n(17),g=r(m),b=(0,v["default"])(),P=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return f["default"].createElement(h["default"],c({ transitionName:this.props.transitionName,builtinPlacements:b,ref:"tooltip"},this.props,{overlay:this.getOverlay()}),this.props.children)},t.prototype.getPopupDomNode=function(){return this.refs.tooltip.getPopupDomNode()},t.prototype.componentDidMount=function(){"overlay"in this.props&&(0,g["default"])(!1,"`overlay` prop of Popover is deprecated, use `content` instead.")},t.prototype.getOverlay=function(){var e=this.props,t=e.title,n=e.prefixCls,r=e.overlay,o=e.content;return f["default"].createElement("div",null,t&&f["default"].createElement("div",{className:n+"-title"},t),f["default"].createElement("div",{className:n+"-inner-content"},o||r))},t}(f["default"].Component),l.defaultProps={prefixCls:"ant-popover",placement:"top",transitionName:"zoom-big",trigger:"hover",mouseEnterDelay:.1,mouseLeaveDelay:.1,overlayStyle:{}},u);t["default"]=P,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(6),v=r(y),m=n(334),g=n(2),b=r(g),P={normal:"#2db7f5",exception:"#ff5500",success:"#87d068"},O=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.status,o=t.format,s=t.percent,l=t.trailColor,u=t.type,c=t.strokeWidth,p=t.width,d=t.className,y=t.showInfo,g=i(t,["prefixCls","status","format","percent","trailColor","type","strokeWidth","width","className","showInfo"]),O=parseInt(s,10)>=100&&!("status"in this.props)?"success":r||"normal",C=void 0,T=void 0,w=o||function(e){return e+"%"};if(y){var x=void 0,E="circle"===u?"":"-circle";x="exception"===O?o?w(s):h["default"].createElement(v["default"],{type:"cross"+E}):"success"===O?o?w(s):h["default"].createElement(v["default"],{type:"check"+E}):w(s),C=h["default"].createElement("span",{className:n+"-text"},x)}if("line"===u){var S={width:s+"%",height:c||10};T=h["default"].createElement("div",null,h["default"].createElement("div",{className:n+"-outer"},h["default"].createElement("div",{className:n+"-inner"},h["default"].createElement("div",{className:n+"-bg",style:S}))),C)}else if("circle"===u){var k=p||132,j={width:k,height:k,fontSize:.16*k+6};T=h["default"].createElement("div",{className:n+"-inner",style:j},h["default"].createElement(m.Circle,{percent:s,strokeWidth:c||6,strokeColor:P[O],trailColor:l}),C)}var _=(0,b["default"])((e={},a(e,""+n,!0),a(e,n+"-"+u,!0),a(e,n+"-status-"+O,!0),a(e,n+"-show-info",y),a(e,d,!!d),e));return h["default"].createElement("div",f({},g,{className:_}),T)},t}(h["default"].Component),c.defaultProps={type:"line",percent:0,showInfo:!0,trailColor:"#f3f3f3",prefixCls:"ant-progress"},c.propTypes={status:d.PropTypes.oneOf(["normal","exception","active","success"]),type:d.PropTypes.oneOf(["line","circle"]),showInfo:d.PropTypes.bool,percent:d.PropTypes.number,width:d.PropTypes.number,strokeWidth:d.PropTypes.number,trailColor:d.PropTypes.string,format:d.PropTypes.func},p);t["default"]=O,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l=n(1),u=r(l),c=n(337),p=r(c),f=n(17),d=r(f),h=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.componentDidMount=function(){(0,d["default"])(!1,"`QueueAnim` is deprecated, you can import QueueAnim from 'rc-queue-anim' directly.The Demo will be moved to http://motion.ant.design/#/component/queue-anim")},t.prototype.render=function(){return u["default"].createElement(p["default"],this.props)},t}(u["default"].Component);t["default"]=h,e.exports=t["default"]},197,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function u(e){var t=null,n=!1;return h["default"].Children.forEach(e,function(e){e&&e.props&&e.props.checked&&(t=e.props.value,n=!0)}),n?{value:t}:void 0}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=n(36),g=r(m),b=n(69),P=r(b),O=n(15),C=r(O),T=(p=c=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));r.onRadioChange=function(e){"value"in r.props||r.setState({value:e.target.value}),r.props.onChange(e)};var o=void 0;if("value"in n)o=n.value;else if("defaultValue"in n)o=n.defaultValue;else{var a=u(n.children);o=a&&a.value}return r.state={value:o},r}return l(t,e),t.prototype.componentWillReceiveProps=function(e){if("value"in e)this.setState({value:e.value});else{var t=u(e.children);t&&this.setState({value:t.value})}},t.prototype.shouldComponentUpdate=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return C["default"].shouldComponentUpdate.apply(this,t)},t.prototype.render=function(){var e,t=this,n=this.props,r=h["default"].Children.map(n.children,function(e){if(e&&(e.type===g["default"]||e.type===P["default"])&&e.props){var n={};return"key"in e||"string"!=typeof e.props.value||(n.key=e.props.value),h["default"].cloneElement(e,f({},n,e.props,{onChange:t.onRadioChange,checked:t.state.value===e.props.value,disabled:e.props.disabled||t.props.disabled}))}return e}),o=(0,v["default"])((e={},a(e,n.prefixCls,!0),a(e,n.prefixCls+"-"+n.size,n.size),e));return h["default"].createElement("div",{className:o,style:n.style},r)},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-radio-group",disabled:!1,onChange:function(){}},p);t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=n(1),p=r(c),f=n(343),d=r(f),h=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){return p["default"].createElement(d["default"],this.props)},t}(p["default"].Component),l.propTypes={prefixCls:c.PropTypes.string},l.defaultProps={prefixCls:"ant-rate"},u);t["default"]=h,e.exports=t["default"]},[460,443],function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(34);t["default"]=r.Row,e.exports=t["default"]},173,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(356),h=r(d),y=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e=this.props,t=e.isIncluded,n=e.marks,r=e.index,o=e.defaultIndex,i=a(e,["isIncluded","marks","index","defaultIndex"]);return void 0!==t&&(i.included=t),Array.isArray(n)?(i.min=0,i.max=n.length-1,i.step=1,void 0!==r&&(i.value=r),void 0!==o&&(i.defaultValue=o),i.marks={},n.forEach(function(e,t){i.marks[t]=e})):i.marks=n,f["default"].createElement(h["default"],i)},t}(f["default"].Component),u.defaultProps={prefixCls:"ant-slider",tipTransitionName:"zoom-down"},c);t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(445),n(75)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(360),h=r(d),y=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props.maxDescriptionWidth;return"vertical"===this.props.direction&&(e="auto"),f["default"].createElement(h["default"],c({},this.props,{maxDescriptionWidth:e}))},t}(f["default"].Component),l.Step=h["default"].Step,l.defaultProps={prefixCls:"ant-steps",iconPrefix:"ant",maxDescriptionWidth:100,current:0},u);t["default"]=y,e.exports=t["default"]},[460,447],function(e,t,n){"use strict";n(459),n(3)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(362),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.size,o=t.className,i=(0,m["default"])((e={},a(e,o,!!o),a(e,n+"-small","small"===r),e));return y["default"].createElement(d["default"],p({className:i},this.props))},t}(y["default"].Component),u.defaultProps={prefixCls:"ant-switch"},c);t["default"]=g,e.exports=t["default"]},[460,448],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},p=n(1),f=r(p),d=n(21),h=r(d),y=n(58),v=r(y),m=n(6),g=r(m),b=n(18),P=r(b),O=n(26),C=r(O),T=(u=l=function(e){function t(n){a(this,t);var r=i(this,e.call(this,n));return r.setSelectedKeys=function(e){var t=e.selectedKeys;r.setState({selectedKeys:t})},r.handleClearFilters=function(){r.setState({selectedKeys:[]},r.handleConfirm)},r.handleConfirm=function(){r.setState({visible:!1}),r.props.confirmFilter(r.props.column,r.state.selectedKeys)},r.onVisibleChange=function(e){r.setState({visible:e}),e||r.props.confirmFilter(r.props.column,r.state.selectedKeys)},r.handleMenuItemClick=function(e){if(!(e.keyPath.length<=1)){var t=r.state.keyPathOfSelectedItem;r.state.selectedKeys.indexOf(e.key)>=0?delete t[e.key]:t[e.key]=e.keyPath,r.setState({keyPathOfSelectedItem:t})}},r.state={selectedKeys:r.props.selectedKeys,keyPathOfSelectedItem:{},visible:!1},r}return s(t,e),t.prototype.componentWillReceiveProps=function(e){this.setState({selectedKeys:e.selectedKeys})},t.prototype.renderMenuItem=function(e){var t=this.props.column,n=!("filterMultiple"in t)||t.filterMultiple;return f["default"].createElement(d.Item,{key:e.value},n?f["default"].createElement(P["default"],{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0}):f["default"].createElement(C["default"],{checked:this.state.selectedKeys.indexOf(e.value.toString())>=0}),f["default"].createElement("span",null,e.text))},t.prototype.renderMenus=function(e){var t=this;return e.map(function(e){if(e.children&&e.children.length>0){var n=function(){var n=t.state.keyPathOfSelectedItem,r=Object.keys(n).some(function(t){return n[t].indexOf(e.value)>=0}),o=r?"ant-dropdown-submenu-contain-selected":"";return{v:f["default"].createElement(d.SubMenu,{title:e.text,className:o,key:e.value.toString()},e.children.map(function(e){return t.renderMenuItem(e)}))}}();if("object"===("undefined"==typeof n?"undefined":c(n)))return n.v}return t.renderMenuItem(e)})},t.prototype.render=function(){var e=this.props,t=e.column,n=e.locale,r=!("filterMultiple"in t)||t.filterMultiple,o=f["default"].createElement("div",{className:"ant-table-filter-dropdown"},f["default"].createElement(h["default"],{multiple:r,onClick:this.handleMenuItemClick,prefixCls:"ant-dropdown-menu",onSelect:this.setSelectedKeys,onDeselect:this.setSelectedKeys,selectedKeys:this.state.selectedKeys},this.renderMenus(t.filters)),f["default"].createElement("div",{className:"ant-table-filter-dropdown-btns"},f["default"].createElement("a",{className:"ant-table-filter-dropdown-link confirm",onClick:this.handleConfirm},n.filterConfirm),f["default"].createElement("a",{className:"ant-table-filter-dropdown-link clear",onClick:this.handleClearFilters},n.filterReset))),a=this.props.selectedKeys.length>0?"ant-table-filter-selected":"";return f["default"].createElement(v["default"],{trigger:["click"],overlay:o,visible:this.state.visible,onVisibleChange:this.onVisibleChange,closeOnSelect:!1},f["default"].createElement(g["default"],{title:n.filterTitle,type:"filter",className:a}))},t}(f["default"].Component),l.defaultProps={handleFilter:function(){},column:null},u);t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function p(){}function f(e){e.stopPropagation(),e.nativeEvent.stopImmediatePropagation()}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var d,h,y,v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},m=n(1),g=r(m),b=n(365),P=r(b),O=n(18),C=r(O),T=n(26),w=r(T),x=n(228),E=r(x),S=n(64),k=r(S),j=n(6),_=r(j),N=n(70),M=r(N),D=n(2),A=r(D),L=n(231),V={filterTitle:"\u7b5b\u9009",filterConfirm:"\u786e\u5b9a",filterReset:"\u91cd\u7f6e",emptyText:g["default"].createElement("span",null,g["default"].createElement(_["default"],{type:"frown"}),"\u6682\u65e0\u6570\u636e")},F={pageSize:10,onChange:p,onShowSizeChange:p},I=(h=d=function(e){function t(n){l(this,t);var r=u(this,e.call(this,n));y.call(r);var o=n.pagination||{};return r.state=v({selectedRowKeys:(n.rowSelection||{}).selectedRowKeys||[],filters:r.getFiltersFromColumns(),selectionDirty:!1},r.getSortStateFromColumns(),{pagination:r.hasPagination()?v({},F,o,{current:o.defaultCurrent||o.current||1}):{}}),r.CheckboxPropsCache={},r}return c(t,e),t.prototype.getCheckboxPropsByItem=function(e){var t=this.props.rowSelection,n=void 0===t?{}:t;if(!n.getCheckboxProps)return{};var r=this.getRecordKey(e);return this.CheckboxPropsCache[r]||(this.CheckboxPropsCache[r]=n.getCheckboxProps(e)),this.CheckboxPropsCache[r]},t.prototype.getDefaultSelection=function(){var e=this,t=this.props.rowSelection,n=void 0===t?{}:t;return n.getCheckboxProps?this.getFlatCurrentPageData().filter(function(t){return e.getCheckboxPropsByItem(t).defaultChecked}).map(function(t,n){return e.getRecordKey(t,n)}):[]},t.prototype.getLocale=function(){var e={};return this.context.antLocale&&this.context.antLocale.Table&&(e=this.context.antLocale.Table),v({},V,e,this.props.locale)},t.prototype.componentWillReceiveProps=function(e){var t=this;if("pagination"in e&&e.pagination!==!1&&this.setState(function(t){var n=v({},F,t.pagination,e.pagination);return n.current=n.current||1,{pagination:n}}),"dataSource"in e&&e.dataSource!==this.props.dataSource&&(this.setState({selectionDirty:!1}),this.CheckboxPropsCache={}),e.rowSelection&&"selectedRowKeys"in e.rowSelection&&(this.setState({selectedRowKeys:e.rowSelection.selectedRowKeys||[]}),e.rowSelection.getCheckboxProps!==this.props.rowSelection.getCheckboxProps&&(this.CheckboxPropsCache={})),this.getSortOrderColumns(e.columns).length>0){var n=this.getSortStateFromColumns(e.columns);n.sortColumn===this.state.sortColumn&&n.sortOrder===this.state.sortOrder||this.setState(n)}var r=this.getFilteredValueColumns(e.columns);r.length>0&&!function(){var n=t.getFiltersFromColumns(e.columns),r=v({},t.state.filters);Object.keys(n).forEach(function(e){r[e]=n[e]}),t.isFiltersChanged(r)&&t.setState({filters:r})}()},t.prototype.setSelectedRowKeys=function(e){var t=this;if(!this.props.rowSelection||"selectedRowKeys"in this.props.rowSelection||this.setState({selectedRowKeys:e}),this.props.rowSelection&&this.props.rowSelection.onChange){var n=this.getFlatCurrentPageData(),r=n.filter(function(n,r){return e.indexOf(t.getRecordKey(n,r))>=0});this.props.rowSelection.onChange(e,r)}},t.prototype.hasPagination=function(){return this.props.pagination!==!1},t.prototype.isFiltersChanged=function(e){var t=this,n=!1;return Object.keys(e).length!==Object.keys(this.state.filters).length?n=!0:Object.keys(e).forEach(function(r){e[r]!==t.state.filters[r]&&(n=!0)}),n},t.prototype.getSortOrderColumns=function(e){return(e||this.props.columns||[]).filter(function(e){return"sortOrder"in e})},t.prototype.getFilteredValueColumns=function(e){return(e||this.props.columns||[]).filter(function(e){return"filteredValue"in e})},t.prototype.getFiltersFromColumns=function(e){var t=this,n={};return this.getFilteredValueColumns(e).forEach(function(e){n[t.getColumnKey(e)]=e.filteredValue}),n},t.prototype.getSortStateFromColumns=function(e){var t=this.getSortOrderColumns(e).filter(function(e){return e.sortOrder})[0];return t?{sortColumn:t,sortOrder:t.sortOrder}:{sortColumn:null,sortOrder:null}},t.prototype.getSorterFn=function(){var e=this.state,t=e.sortOrder,n=e.sortColumn;if(t&&n&&"function"==typeof n.sorter)return function(e,r){var o=n.sorter(e,r);return 0!==o?"descend"===t?-o:o:e.indexForSort-r.indexForSort}},t.prototype.toggleSortOrder=function(e,t){var n,r=this.state,o=r.sortColumn,a=r.sortOrder,i=this.isSortColumn(t);i?a===e?(a="",o=null):a=e:(a=e,o=t);var l={sortOrder:a,sortColumn:o};0===this.getSortOrderColumns().length&&this.setState(l),(n=this.props).onChange.apply(n,s(this.prepareParamsArguments(v({},this.state,l))))},t.prototype.getRecordKey=function(e,t){return this.props.rowKey?this.props.rowKey(e,t):e.key||t},t.prototype.renderRowSelection=function(){var e=this,t=this.props.columns.concat();if(this.props.rowSelection){var n=this.getFlatCurrentPageData().filter(function(t){return!e.props.rowSelection.getCheckboxProps||!e.getCheckboxPropsByItem(t).disabled}),r=void 0;r=!!n.length&&(this.state.selectionDirty?n.every(function(t,n){return e.state.selectedRowKeys.indexOf(e.getRecordKey(t,n))>=0}):n.every(function(t,n){return e.state.selectedRowKeys.indexOf(e.getRecordKey(t,n))>=0})||n.every(function(t){return e.getCheckboxPropsByItem(t).defaultChecked}));var o=void 0;if("radio"===this.props.rowSelection.type)o={key:"selection-column",render:this.renderSelectionRadio,className:"ant-table-selection-column"};else{var a=n.every(function(t){return e.getCheckboxPropsByItem(t).disabled}),i=g["default"].createElement(C["default"],{checked:r,disabled:a,onChange:this.handleSelectAllRow});o={key:"selection-column",title:i,render:this.renderSelectionCheckBox,className:"ant-table-selection-column"}}t.some(function(e){return"left"===e.fixed||e.fixed===!0})&&(o.fixed="left"),t[0]&&"selection-column"===t[0].key?t[0]=o:t.unshift(o)}return t},t.prototype.getColumnKey=function(e,t){return e.key||e.dataIndex||t},t.prototype.isSortColumn=function(e){var t=this.state.sortColumn;return!(!e||!t)&&this.getColumnKey(t)===this.getColumnKey(e)},t.prototype.renderColumnsDropdown=function(e){var t=this,n=this.state.sortOrder,r=this.getLocale();return e.map(function(e,o){var a=v({},e),i=t.getColumnKey(a,o),s=void 0,l=void 0;if(a.filters&&a.filters.length>0){var u=t.state.filters[i]||[];s=g["default"].createElement(E["default"],{locale:r,column:a,selectedKeys:u,confirmFilter:t.handleFilter})}if(a.sorter){var c=t.isSortColumn(a);c&&(a.className=a.className||"",n&&(a.className+=" ant-table-column-sort"));var p=c&&"ascend"===n,f=c&&"descend"===n;l=g["default"].createElement("div",{className:"ant-table-column-sorter"},g["default"].createElement("span",{className:"ant-table-column-sorter-up "+(p?"on":"off"),title:"\u2191",onClick:function(){return t.toggleSortOrder("ascend",a)}},g["default"].createElement(_["default"],{type:"caret-up"})),g["default"].createElement("span",{className:"ant-table-column-sorter-down "+(f?"on":"off"),title:"\u2193",onClick:function(){return t.toggleSortOrder("descend",a)}},g["default"].createElement(_["default"],{type:"caret-down"})))}return a.title=g["default"].createElement("span",null,a.title,l,s),a})},t.prototype.renderPagination=function(){if(!this.hasPagination())return null;var e="default";this.state.pagination.size?e=this.state.pagination.size:"middle"!==this.props.size&&"small"!==this.props.size||(e="small");var t=this.state.pagination.total||this.getLocalData().length;return t>0?g["default"].createElement(k["default"],v({},this.state.pagination,{className:this.props.prefixCls+"-pagination",onChange:this.handlePageChange,total:t,size:e,onShowSizeChange:this.handleShowSizeChange})):null},t.prototype.prepareParamsArguments=function(e){var t=e.pagination,n=e.filters,r={};return e.sortColumn&&e.sortOrder&&(r.column=e.sortColumn,r.order=e.sortOrder,r.field=e.sortColumn.dataIndex,r.columnKey=this.getColumnKey(e.sortColumn)),[t,n,r]},t.prototype.findColumn=function(e){var t=this;return this.props.columns.filter(function(n){return t.getColumnKey(n)===e})[0]},t.prototype.getCurrentPageData=function(){var e=this.getLocalData(),t=void 0,n=void 0,r=this.state;return this.hasPagination()?(n=r.pagination.pageSize,t=r.pagination.current):(n=Number.MAX_VALUE,t=1),(e.length>n||n===Number.MAX_VALUE)&&(e=e.filter(function(e,r){return r>=(t-1)*n&&r<t*n})),e},t.prototype.getFlatCurrentPageData=function(){return(0,L.flatArray)(this.getCurrentPageData())},t.prototype.getLocalData=function(){var e=this,t=this.state,n=this.props.dataSource||[];n=n.slice(0);for(var r=0;r<n.length;r++)n[r].indexForSort=r;var o=this.getSorterFn();return o&&(n=n.sort(o)),t.filters&&Object.keys(t.filters).forEach(function(r){var o=e.findColumn(r);if(o){var a=t.filters[r]||[];0!==a.length&&(n=o.onFilter?n.filter(function(e){return a.some(function(t){return o.onFilter(t,e)})}):n)}}),n},t.prototype.render=function(){var e,t=this,n=this.props,r=n.style,o=n.className,s=i(n,["style","className"]),l=this.getCurrentPageData(),u=this.renderRowSelection(),c=this.props.expandedRowRender&&this.props.expandIconAsCell!==!1,p=this.getLocale(),f=(0,A["default"])((e={},a(e,"ant-table-"+this.props.size,!0),a(e,"ant-table-bordered",this.props.bordered),e));u=this.renderColumnsDropdown(u),u=u.map(function(e,n){var r=v({},e);return r.key=t.getColumnKey(r,n),r});var d=void 0,h="";l&&0!==l.length||(d=g["default"].createElement("div",{className:"ant-table-placeholder"},p.emptyText),h="ant-table-empty");var y=g["default"].createElement("div",null,g["default"].createElement(P["default"],v({},s,{data:l,columns:u,className:f,expandIconColumnIndex:u[0]&&"selection-column"===u[0].key?1:0,expandIconAsCell:c})),d),m=this.hasPagination()&&l&&0!==l.length?"ant-table-with-pagination":"ant-table-without-pagination",b=this.props.loading?m+" ant-table-spin-holder":"";return y=g["default"].createElement(M["default"],{className:b,spinning:this.props.loading},y),g["default"].createElement("div",{className:h+" "+o+" clearfix",style:r},y,this.renderPagination())},t}(g["default"].Component),d.propTypes={dataSource:g["default"].PropTypes.array,prefixCls:g["default"].PropTypes.string,useFixedHeader:g["default"].PropTypes.bool,rowSelection:g["default"].PropTypes.object,className:g["default"].PropTypes.string,size:g["default"].PropTypes.string,loading:g["default"].PropTypes.bool,bordered:g["default"].PropTypes.bool,onChange:g["default"].PropTypes.func,locale:g["default"].PropTypes.object},d.defaultProps={dataSource:[],prefixCls:"ant-table",useFixedHeader:!1,rowSelection:null,className:"",size:"large",loading:!1,bordered:!1,indentSize:20,onChange:p,locale:{}},d.contextTypes={antLocale:g["default"].PropTypes.object},y=function(){var e=this;this.handleFilter=function(t,n){var r=e.props,o=v({},e.state.pagination),i=v({},e.state.filters,a({},e.getColumnKey(t),n)),l=r.columns.map(function(t){return e.getColumnKey(t)});Object.keys(i).forEach(function(e){l.indexOf(e)<0&&delete i[e]}),r.pagination&&(o.current=1,o.onChange(o.current));var u={selectionDirty:!1,pagination:o},c=v({},i);e.getFilteredValueColumns().forEach(function(t){var n=e.getColumnKey(t);n&&delete c[n]}),Object.keys(c).length>0&&(u.filters=c),r.pagination&&"current"in r.pagination&&(u.pagination=v({},o,{current:e.state.pagination.current})),e.setState(u,function(){r.onChange.apply(r,s(e.prepareParamsArguments(v({},e.state,{selectionDirty:!1,filters:i,pagination:o}))))})},this.handleSelect=function(t,n,r){var o=r.target.checked,a=e.state.selectionDirty?[]:e.getDefaultSelection(),i=e.state.selectedRowKeys.concat(a),s=e.getRecordKey(t,n);if(o?i.push(e.getRecordKey(t,n)):i=i.filter(function(e){ return s!==e}),e.setState({selectionDirty:!0}),e.setSelectedRowKeys(i),e.props.rowSelection.onSelect){var l=e.getFlatCurrentPageData(),u=l.filter(function(t,n){return i.indexOf(e.getRecordKey(t,n))>=0});e.props.rowSelection.onSelect(t,o,u)}},this.handleRadioSelect=function(t,n,r){var o=r.target.checked,a=e.state.selectionDirty?[]:e.getDefaultSelection(),i=e.state.selectedRowKeys.concat(a),s=e.getRecordKey(t,n);if(i=[s],e.setState({selectionDirty:!0}),e.setSelectedRowKeys(i),e.props.rowSelection.onSelect){var l=e.getFlatCurrentPageData(),u=l.filter(function(t,n){return i.indexOf(e.getRecordKey(t,n))>=0});e.props.rowSelection.onSelect(t,o,u)}},this.handleSelectAllRow=function(t){var n=t.target.checked,r=e.getFlatCurrentPageData(),o=e.state.selectionDirty?[]:e.getDefaultSelection(),a=e.state.selectedRowKeys.concat(o),i=r.filter(function(t){return!e.getCheckboxPropsByItem(t).disabled}).map(function(t,n){return e.getRecordKey(t,n)}),s=[];if(n?i.forEach(function(e){a.indexOf(e)<0&&(a.push(e),s.push(e))}):i.forEach(function(e){a.indexOf(e)>=0&&(a.splice(a.indexOf(e),1),s.push(e))}),e.setState({selectionDirty:!0}),e.setSelectedRowKeys(a),e.props.rowSelection.onSelectAll){var l=r.filter(function(t,n){return a.indexOf(e.getRecordKey(t,n))>=0}),u=r.filter(function(t,n){return s.indexOf(e.getRecordKey(t,n))>=0});e.props.rowSelection.onSelectAll(n,l,u)}},this.handlePageChange=function(t){var n,r=e.props,o=v({},e.state.pagination);t?o.current=t:o.current=o.current||1,o.onChange(o.current);var a={selectionDirty:!1,pagination:o};r.pagination&&"current"in r.pagination&&(a.pagination=v({},o,{current:e.state.pagination.current})),e.setState(a),(n=e.props).onChange.apply(n,s(e.prepareParamsArguments(v({},e.state,{selectionDirty:!1,pagination:o}))))},this.renderSelectionRadio=function(t,n,r){var o=e.getRecordKey(n,r),a=e.getCheckboxPropsByItem(n),i=void 0;return i=e.state.selectionDirty?e.state.selectedRowKeys.indexOf(o)>=0:e.state.selectedRowKeys.indexOf(o)>=0||e.getDefaultSelection().indexOf(o)>=0,g["default"].createElement("span",{onClick:f},g["default"].createElement(w["default"],{disabled:a.disabled,onChange:function(t){return e.handleRadioSelect(n,o,t)},value:o,checked:i}))},this.renderSelectionCheckBox=function(t,n,r){var o=e.getRecordKey(n,r),a=void 0;a=e.state.selectionDirty?e.state.selectedRowKeys.indexOf(o)>=0:e.state.selectedRowKeys.indexOf(o)>=0||e.getDefaultSelection().indexOf(o)>=0;var i=e.getCheckboxPropsByItem(n);return g["default"].createElement("span",{onClick:f},g["default"].createElement(C["default"],{checked:a,disabled:i.disabled,onChange:function(t){return e.handleSelect(n,o,t)}}))},this.handleShowSizeChange=function(t,n){var r,o=e.state.pagination;o.onShowSizeChange(t,n);var a=v({},o,{pageSize:n,current:t});e.setState({pagination:a}),(r=e.props).onChange.apply(r,s(e.prepareParamsArguments(v({},e.state,{pagination:a}))))}},h);t["default"]=I,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(449),n(37),n(19),n(59),n(71),n(65)},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],t=arguments.length<=1||void 0===arguments[1]?"children":arguments[1],n=[],o=function a(e){e.forEach(function(e){var o=r({},e);delete o[t],n.push(o),e[t]&&e[t].length>0&&a(e[t])})};return o(e),n}Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.flatArray=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(371),d=r(f),h=n(1),y=r(h),v=n(2),m=r(v),g=n(6),b=r(g),P=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var a=arguments.length,l=Array(a),u=0;u<a;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.createNewTab=function(e){r.props.onEdit(e,"add")},r.removeTab=function(e,t){t.stopPropagation(),e&&r.props.onEdit(e,"remove")},r.handleChange=function(e){r.props.onChange(e)},o=n,s(r,o)}return l(t,e),t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.size,i=n.tabPosition,s=n.animation,l=n.type,u=n.children,c=n.tabBarExtraContent,f=n.hideAdd,v=(0,m["default"])((e={},a(e,this.props.className,!!this.props.className),a(e,r+"-mini","small"===o||"mini"===o),a(e,r+"-vertical","left"===i||"right"===i),a(e,r+"-card",l.indexOf("card")>=0),a(e,r+"-"+l,!0),e));return("left"===i||"right"===i||l.indexOf("card")>=0)&&(s=null),"editable-card"===l&&(u=u.map(function(e,n){return(0,h.cloneElement)(e,{tab:y["default"].createElement("div",null,e.props.tab,y["default"].createElement(b["default"],{type:"cross",onClick:function(n){return t.removeTab(e.key,n)}})),key:e.key||n})}),f||(c=y["default"].createElement("span",null,y["default"].createElement(b["default"],{type:"plus",className:r+"-new-tab",onClick:this.createNewTab}),c))),c=c?y["default"].createElement("div",{className:r+"-extra-content"},c):null,y["default"].createElement(d["default"],p({},this.props,{className:v,tabBarExtraContent:c,onChange:this.handleChange,animation:s}),u)},t}(y["default"].Component),u.TabPane=d["default"].TabPane,u.defaultProps={prefixCls:"ant-tabs",animation:"slide-horizontal",type:"line",onChange:function(){},onEdit:function(){},hideAdd:!1},c);t["default"]=P,e.exports=t["default"]},[460,450],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(4),v=r(y),m=n(8),g=r(m),b=n(6),P=r(b),O=n(2),C=r(O),T=(p=c=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.close=function(e){if(r.props.onClose(e),!e.defaultPrevented){var t=v["default"].findDOMNode(r),n=t.getBoundingClientRect().width;t.style.width=n+"px",t.style.width=n+"px",r.setState({closing:!0})}},r.animationEnd=function(e,t){t||r.state.closed||(r.setState({closed:!0,closing:!1}),r.props.afterClose())},r.state={closing:!1,closed:!1},r}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.closable,o=t.color,s=t.className,l=t.children,u=i(t,["prefixCls","closable","color","className","children"]),c=r?h["default"].createElement(P["default"],{type:"cross",onClick:this.close}):"",p=(0,C["default"])((e={},a(e,n,!0),a(e,n+"-"+o,!!o),a(e,n+"-close",this.state.closing),a(e,s,!!s),e));return h["default"].createElement(g["default"],{component:"",showProp:"data-show",transitionName:n+"-zoom",transitionAppear:!0,onEnd:this.animationEnd},this.state.closed?null:h["default"].createElement("div",f({"data-show":!this.state.closing},u,{className:p}),h["default"].createElement("span",{className:n+"-text"},l),c))},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-tag",closable:!1,onClose:function(){},afterClose:function(){}},p);t["default"]=T,e.exports=t["default"]},[460,451],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(29),y=r(h),v=n(109),m=r(v),g=n(72),b=r(g),P=n(2),O=r(P),C=n(9),T=r(C),w=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var a=arguments.length,l=Array(a),u=0;u<a;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.handleChange=function(e){r.props.onChange(e?new Date(e.getTime()):null,e?r.getFormatter().format(e):"")},o=n,s(r,o)}return l(t,e),t.prototype.getFormatter=function(){return new y["default"](this.props.format,this.getLocale().format)},t.prototype.getSizeClass=function(){var e="";return"large"===this.props.size?e=" ant-input-lg":"small"===this.props.size&&(e=" ant-input-sm"),e},t.prototype.parseTimeFromValue=function(e){if(e){if("string"==typeof e)return this.getFormatter().parse(e,{locale:this.getLocale().calendar,obeyCount:!0});if(e instanceof Date){var t=new T["default"](this.getLocale().calendar);return t.setTime(+e),t}}return e},t.prototype.getLocale=function(){var e=b["default"];return this.context.antLocale&&this.context.antLocale.TimePicker&&(e=this.context.antLocale.TimePicker),p({},e,this.props.locale)},t.prototype.render=function(){var e,t=this.getLocale(),n=p({},this.props);n.placeholder="placeholder"in this.props?n.placeholder:t.placeholder,n.defaultValue?n.defaultValue=this.parseTimeFromValue(n.defaultValue):delete n.defaultValue,n.value&&(n.value=this.parseTimeFromValue(n.value));var r=(0,O["default"])((e={},a(e,n.className,!!n.className),a(e,n.prefixCls+"-"+n.size,!!n.size),e));return n.format.indexOf("ss")<0&&(n.showSecond=!1),n.format.indexOf("HH")<0&&(n.showHour=!1),d["default"].createElement(m["default"],p({},n,{className:r,locale:t,formatter:this.getFormatter(),onChange:this.handleChange}))},t}(d["default"].Component),u.defaultProps={format:"HH:mm:ss",prefixCls:"ant-time-picker",onChange:function(){},locale:{},align:{offset:[0,-2]},disabled:!1,disabledHours:void 0,disabledMinutes:void 0,disabledSeconds:void 0,hideDisabledOptions:!1,placement:"bottomLeft",transitionName:"slide-up"},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var c,p,f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=n(1),h=r(d),y=n(2),v=r(y),m=n(74),g=r(m),b=(p=c=function(e){function t(){return s(this,t),l(this,e.apply(this,arguments))}return u(t,e),t.prototype.render=function(){var e,t=this.props,n=t.prefixCls,r=t.children,o=t.pending,s=t.className,l=i(t,["prefixCls","children","pending","className"]),u="boolean"==typeof o?null:o,c=(0,v["default"])((e={},a(e,n,!0),a(e,n+"-pending",!!o),a(e,s,s),e));return h["default"].createElement("ul",f({},l,{className:c}),h["default"].Children.map(r,function(e,t){return h["default"].cloneElement(e,{last:t===r.length-1})}),o?h["default"].createElement(g["default"],{pending:!!o},u):null)},t}(h["default"].Component),c.defaultProps={prefixCls:"ant-timeline"},p);t["default"]=b,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(237),a=r(o),i=n(74),s=r(i);a["default"].Item=s["default"],t["default"]=a["default"],e.exports=t["default"]},[460,453],function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function c(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d=n(1),h=r(d),y=n(241),v=r(y),m=n(242),g=r(m),b=n(76),P=r(b),O=n(2),C=r(O),T=(f=p=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.moveTo=function(e){var t=r.props.targetKeys,n=r.state,o=n.leftCheckedKeys,a=n.rightCheckedKeys,s="right"===e?o:a,l="right"===e?s.concat(t):t.filter(function(e){return!s.some(function(t){return e===t})});r.setState(i({},"right"===e?"leftCheckedKeys":"rightCheckedKeys",[])),r.props.onChange(l,e,s)},r.moveToLeft=function(){return r.moveTo("left")},r.moveToRight=function(){return r.moveTo("right")},r.handleSelectAll=function(e){var t=r.splitDataSource(r.props),n=t.leftDataSource,o=t.rightDataSource,a=r.state,s=a.leftFilter,l=a.rightFilter,u="left"===e?n:o,c="left"===e?s:l,p=r.getGlobalCheckStatus(e),f="all"===p?[]:r.filterDataSource(u,c).map(function(e){return e.key});r.setState(i({},e+"CheckedKeys",f))},r.handleLeftSelectAll=function(){return r.handleSelectAll("left")},r.handleRightSelectAll=function(){return r.handleSelectAll("right")},r.handleFilter=function(e,t){var n;r.setState((n={},i(n,e+"CheckedKeys",[]),i(n,e+"Filter",t.target.value),n))},r.handleLeftFilter=function(e){return r.handleFilter("left",e)},r.handleRightFilter=function(e){return r.handleFilter("right",e)},r.handleClear=function(e){r.setState(i({},e+"Filter",""))},r.handleLeftClear=function(){return r.handleClear("left")},r.handleRightClear=function(){return r.handleClear("right")},r.handleSelect=function(e,t,n){var o=r.state,a=o.leftCheckedKeys,s=o.rightCheckedKeys,l="left"===e?a:s,u=void 0;l.forEach(function(e,n){e===t.key&&(u=n)}),u>-1&&l.splice(u,1),n&&l.push(t.key),r.setState(i({},e+"CheckedKeys",l))},r.handleLeftSelect=function(e,t){return r.handleSelect("left",e,t)},r.handleRightSelect=function(e,t){return r.handleSelect("right",e,t)},r.state={leftFilter:"",rightFilter:"",leftCheckedKeys:[],rightCheckedKeys:[]},r}return u(t,e),t.prototype.componentWillReceiveProps=function(e){var t=this.state,n=t.leftCheckedKeys,r=t.rightCheckedKeys,o=this.splitDataSource(e),a=o.leftDataSource,i=o.rightDataSource;this.setState({leftCheckedKeys:n.filter(function(e){return a.filter(function(t){return t.key===e}).length}),rightCheckedKeys:r.filter(function(e){return i.filter(function(t){return t.key===e}).length})})},t.prototype.splitDataSource=function(e){var t=e.targetKeys,n=e.dataSource;e.rowKey&&(n=n.map(function(t){return t.key=e.rowKey(t),t}));var r=[].concat(a(n)),o=[];return t.length>0&&t.forEach(function(e){o.push(r.filter(function(t,n){return t.key===e&&(r.splice(n,1),!0)})[0])}),{leftDataSource:r,rightDataSource:o}},t.prototype.getGlobalCheckStatus=function(e){var t=this.splitDataSource(this.props),n=t.leftDataSource,r=t.rightDataSource,o=this.state,a=o.leftFilter,i=o.rightFilter,s=o.leftCheckedKeys,l=o.rightCheckedKeys,u="left"===e?n:r,c="left"===e?a:i,p="left"===e?s:l,f=this.filterDataSource(u,c),d=void 0;return d=p.length>0?p.length<f.length?"part":"all":"none"},t.prototype.filterDataSource=function(e,t){var n=this;return e.filter(function(e){var r=n.props.render(e),o=void 0;return o=(0,y.isRenderResultPlainObject)(r)?r.value:r,n.matchFilter(o,t)})},t.prototype.matchFilter=function(e,t){var n=new RegExp(t);return e.match(n)},t.prototype.render=function n(){var e,t=this.props,r=t.prefixCls,o=t.titles,a=t.operations,s=t.showSearch,l=t.notFoundContent,u=t.searchPlaceholder,c=t.body,p=t.footer,f=t.listStyle,d=t.className,n=t.render,y=this.state,m=y.leftFilter,b=y.rightFilter,P=y.leftCheckedKeys,O=y.rightCheckedKeys,T=this.splitDataSource(this.props),w=T.leftDataSource,x=T.rightDataSource,E=O.length>0,S=P.length>0,k=this.getGlobalCheckStatus("left"),j=this.getGlobalCheckStatus("right"),_=(0,C["default"])((e={},i(e,d,!!d),i(e,r,!0),e));return h["default"].createElement("div",{className:_},h["default"].createElement(v["default"],{titleText:o[0],dataSource:w,filter:m,style:f,checkedKeys:P,checkStatus:k,handleFilter:this.handleLeftFilter,handleClear:this.handleLeftClear,handleSelect:this.handleLeftSelect,handleSelectAll:this.handleLeftSelectAll,position:"left",render:n,showSearch:s,searchPlaceholder:u,notFoundContent:l,body:c,footer:p,prefixCls:r+"-list"}),h["default"].createElement(g["default"],{rightActive:S,rightArrowText:a[0],moveToRight:this.moveToRight,leftActive:E,leftArrowText:a[1],moveToLeft:this.moveToLeft,className:r+"-operation"}),h["default"].createElement(v["default"],{titleText:o[1],dataSource:x,filter:b,style:f,checkedKeys:O,checkStatus:j,handleFilter:this.handleRightFilter,handleClear:this.handleRightClear,handleSelect:this.handleRightSelect,handleSelectAll:this.handleRightSelectAll,position:"right",render:n,showSearch:s,searchPlaceholder:u,notFoundContent:l,body:c,footer:p,prefixCls:r+"-list"}))},t}(h["default"].Component),p.List=v["default"],p.Operation=g["default"],p.Search=P["default"],p.defaultProps={prefixCls:"ant-transfer",dataSource:[],render:c,targetKeys:[],onChange:c,titles:["\u6e90\u5217\u8868","\u76ee\u7684\u5217\u8868"],operations:[],showSearch:!1,body:c,footer:c},p.propTypes={prefixCls:d.PropTypes.string,dataSource:d.PropTypes.array,render:d.PropTypes.func,targetKeys:d.PropTypes.array,onChange:d.PropTypes.func,height:d.PropTypes.number,listStyle:d.PropTypes.object,className:d.PropTypes.string,titles:d.PropTypes.array,operations:d.PropTypes.array,showSearch:d.PropTypes.bool,searchPlaceholder:d.PropTypes.string,notFoundContent:d.PropTypes.node,body:d.PropTypes.func,footer:d.PropTypes.func,rowKey:d.PropTypes.func},f);t["default"]=T,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function u(){}function c(e){return e&&!y["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var p,f,d=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.isRenderResultPlainObject=c;var h=n(1),y=r(h),v=n(18),m=r(v),g=n(76),b=r(g),P=n(2),O=r(P),C=n(8),T=r(C),w=(f=p=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.handleSelectAll=function(){r.props.handleSelectAll()},r.handleSelect=function(e){var t=r.props.checkedKeys,n=t.some(function(t){return t===e.key});r.props.handleSelect(e,!n)},r.handleFilter=function(e){r.props.handleFilter(e)},r.handleClear=function(){r.props.handleClear()},r.state={mounted:!1},r}return l(t,e),t.prototype.componentDidMount=function(){var e=this;setTimeout(function(){e.setState({mounted:!0})},0)},t.prototype.renderCheckbox=function(e){var t,n=e.prefixCls,r=(0,O["default"])((t={},a(t,n+"-checkbox",!0),a(t,n+"-checkbox-indeterminate",e.checkPart),a(t,n+"-checkbox-checked",!e.checkPart&&e.checked),a(t,n+"-checkbox-disabled",!!e.disabled),t)),o=null;return"boolean"!=typeof e.checkable&&(o=e.checkable),y["default"].createElement("span",{ref:"checkbox",className:r,onClick:!e.disabled&&this.handleSelectAll},o)},t.prototype.matchFilter=function(e,t){var n=new RegExp(t);return e.match(n)},t.prototype.render=function n(){var e,t=this,r=this.props,o=r.prefixCls,i=r.dataSource,s=r.titleText,l=r.filter,u=r.checkedKeys,p=r.checkStatus,f=r.body,h=r.footer,v=r.showSearch,n=r.render,g=this.props,P=g.searchPlaceholder,C=g.notFoundContent,w=h(d({},this.props)),x=f(d({},this.props)),E=(0,O["default"])((e={},a(e,o,!0),a(e,o+"-with-footer",!!w),e)),S=i.filter(function(e){var r=n(e),o=void 0;o=c(r)?r.value:r;var a=t.matchFilter(o,l);return!!a}).map(function(e){var r=n(e),o=void 0,a=void 0;return c(r)?(o=r.value,a=r.label):(o=r,a=r),y["default"].createElement("li",{onClick:function(){t.handleSelect(e)},key:e.key,title:o},y["default"].createElement(m["default"],{checked:u.some(function(t){return t===e.key})}),y["default"].createElement("span",null,a))}),k="\u6761";return this.context.antLocale&&this.context.antLocale.Transfer&&(k=i.length>1?this.context.antLocale.Transfer.itemsUnit:this.context.antLocale.Transfer.itemUnit,P=P||this.context.antLocale.Transfer.searchPlaceholder,C=C||this.context.antLocale.Transfer.notFoundContent),y["default"].createElement("div",d({className:E},this.props),y["default"].createElement("div",{className:o+"-header"},this.renderCheckbox({prefixCls:"ant-transfer",checked:"all"===p,checkPart:"part"===p,checkable:y["default"].createElement("span",{className:"ant-transfer-checkbox-inner"})}),y["default"].createElement("span",{className:o+"-header-selected"},y["default"].createElement("span",null,(u.length>0?u.length+"/":"")+i.length," ",k),y["default"].createElement("span",{className:o+"-header-title"},s))),x||y["default"].createElement("div",{className:v?o+"-body "+o+"-body-with-search":o+"-body"},v?y["default"].createElement("div",{className:o+"-body-search-wrapper"},y["default"].createElement(b["default"],{prefixCls:o+"-search",onChange:this.handleFilter,handleClear:this.handleClear,placeholder:P||"\u8bf7\u8f93\u5165\u641c\u7d22\u5185\u5bb9",value:l})):null,y["default"].createElement(T["default"],{component:"ul",transitionName:this.state.mounted?o+"-highlight":"",transitionLeave:!1},S.length>0?S:y["default"].createElement("div",{className:o+"-body-not-found"},C||"\u5217\u8868\u4e3a\u7a7a"))),w?y["default"].createElement("div",{className:o+"-footer"},w):null)},t}(y["default"].Component),p.defaultProps={dataSource:[],titleText:"",showSearch:!1,handleFilter:u,handleSelect:u,handleSelectAll:u,render:u,body:u,footer:u},p.propTypes={prefixCls:h.PropTypes.string,dataSource:h.PropTypes.array,showSearch:h.PropTypes.bool,searchPlaceholder:h.PropTypes.string,titleText:h.PropTypes.string,style:h.PropTypes.object,handleFilter:h.PropTypes.func,handleSelect:h.PropTypes.func,handleSelectAll:h.PropTypes.func,render:h.PropTypes.func,body:h.PropTypes.func,footer:h.PropTypes.func},p.contextTypes={antLocale:y["default"].PropTypes.object},f);t["default"]=w},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=n(1),f=r(p),d=n(16),h=r(d),y=n(6),v=r(y),m=(c=u=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.moveToLeft,n=e.moveToRight,r=e.leftArrowText,o=e.rightArrowText,a=e.leftActive,i=e.rightActive,s=e.className,l=f["default"].createElement(h["default"],{type:"primary",size:"small",disabled:!a,onClick:t},f["default"].createElement("span",null,f["default"].createElement(v["default"],{type:"left"}),r)),u=f["default"].createElement(h["default"],{type:"primary",size:"small",disabled:!i,onClick:n},f["default"].createElement("span",null,o,f["default"].createElement(v["default"],{type:"right"})));return f["default"].createElement("div",{className:s},l,u)},t}(f["default"].Component),u.defaultProps={leftArrowText:"",rightArrowText:"",moveToLeft:l,moveToRight:l},u.propTypes={className:p.PropTypes.string,leftArrowText:p.PropTypes.string,rightArrowText:p.PropTypes.string,moveToLeft:p.PropTypes.func,moveToRight:p.PropTypes.func},c);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(455),n(19),n(25),n(13)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(386),y=r(h),v=n(2),m=r(v),g=(c=u=function(e){function t(){return i(this,t),s(this,e.apply(this,arguments))}return l(t,e),t.prototype.render=function(){var e,t=this.props,n=this.props,r=n.size,o=n.className,i=n.combobox,s=n.notFoundContent,l=n.prefixCls,u=(0,m["default"])((e={},a(e,l+"-lg","large"===r),a(e,l+"-sm","small"===r),a(e,o,!!o),e)),c=this.context.antLocale;c&&c.Select&&(s=s||c.Select.notFoundContent),i&&(s=null);var f=t.treeCheckable;return f&&(f=d["default"].createElement("span",{className:l+"-tree-checkbox-inner"})),d["default"].createElement(y["default"],p({},this.props,{treeCheckable:f,className:u,notFoundContent:s}))},t}(d["default"].Component),u.TreeNode=h.TreeNode,u.SHOW_ALL=h.SHOW_ALL,u.SHOW_PARENT=h.SHOW_PARENT,u.SHOW_CHILD=h.SHOW_CHILD,u.defaultProps={prefixCls:"ant-select",transitionName:"slide-up",choiceTransitionName:"zoom",showSearch:!1,dropdownClassName:"ant-select-tree-dropdown"},u.contextTypes={antLocale:d["default"].PropTypes.object},c);t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(456),n(28),n(19)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l,u,c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){ var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(114),h=r(d),y=n(53),v=r(y),m=(u=l=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){var e=this.props,t=e.checkable;return t&&(t=f["default"].createElement("span",{className:e.prefixCls+"-checkbox-inner"})),f["default"].createElement(h["default"],c({},e,{checkable:t}),this.props.children)},t}(f["default"].Component),l.TreeNode=h["default"].TreeNode,l.defaultProps={prefixCls:"ant-tree",checkable:!1,showIcon:!1,openAnimation:v["default"]},u);t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(457),n(19)},function(e,t){"use strict";function n(e,t){var n=e.uid?"byUid":"byName",r=t.filter(function(t){return"byName"===n?t.name===e.name:t.uid===e.uid})[0];return r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function u(){}function c(){return!0}function p(e){return{lastModified:e.lastModified,lastModifiedDate:e.lastModifiedDate,name:e.filename||e.name,size:e.size,type:e.type,uid:e.uid,response:e.response,error:e.error,percent:0,originFileObj:e}}function f(){var e=.1,t=.01,n=.98;return function(r){var o=r;return o>=n?o:(o+=e,e-=t,e<.001&&(e=.001),100*o)}}function d(e){return g["default"].createElement(k,v({},e,{type:"drag",style:{height:e.height}}))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var h,y,v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},m=n(1),g=r(m),b=n(396),P=r(b),O=n(251),C=r(O),T=n(248),w=r(T),x=n(2),E=r(x),S="ant-upload",k=(y=h=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.onStart=function(e){if(r.recentUploadStatus!==!1){var t=void 0,n=r.state.fileList.concat();e.length>0?(t=e.map(function(e){var t=p(e);return t.status="uploading",t}),n=n.concat(t)):(t=p(e),t.status="uploading",n.push(t)),r.onChange({file:t,fileList:n}),window.FormData||r.autoUpdateProgress(0,t)}},r.onSuccess=function(e,t){r.clearProgressTimer();try{"string"==typeof e&&(e=JSON.parse(e))}catch(n){}var o=r.state.fileList,a=(0,w["default"])(t,o);a&&(a.status="done",a.response=e,r.onChange({file:a,fileList:o}))},r.onProgress=function(e,t){var n=r.state.fileList,o=(0,w["default"])(t,n);o&&(o.percent=e.percent,r.onChange({event:e,file:o,fileList:r.state.fileList}))},r.onError=function(e,t,n){r.clearProgressTimer();var o=r.state.fileList,a=(0,w["default"])(n,o);a.error=e,a.response=t,a.status="error",r.handleRemove(a)},r.beforeUpload=function(e){return r.recentUploadStatus=r.props.beforeUpload(e),r.recentUploadStatus},r.handlePreview=function(e){"onPreview"in r.props&&r.props.onPreview(e)},r.handleManualRemove=function(e){e.status="removed","onRemove"in r.props?r.props.onRemove(e):r.handleRemove(e)},r.onChange=function(e){r.setState({fileList:e.fileList}),r.props.onChange(e)},r.onFileDrop=function(e){r.setState({dragState:e.type})},r.state={fileList:r.props.fileList||r.props.defaultFileList||[],dragState:"drop"},r}return l(t,e),t.prototype.autoUpdateProgress=function(e,t){var n=this,r=f(),o=0;this.progressTimer=setInterval(function(){o=r(o),n.onProgress({percent:o},t)},200)},t.prototype.removeFile=function(e){var t=this.state.fileList,n=(0,w["default"])(e,t),r=t.indexOf(n);return r!==-1?(t.splice(r,1),t):null},t.prototype.handleRemove=function(e){var t=this.removeFile(e);t&&this.onChange({file:e,fileList:t})},t.prototype.componentWillReceiveProps=function(e){"fileList"in e&&this.setState({fileList:e.fileList||[]})},t.prototype.clearProgressTimer=function(){clearInterval(this.progressTimer)},t.prototype.render=function(){var e,t=this.props.type||"select",n=v({},this.props,{onStart:this.onStart,onError:this.onError,onProgress:this.onProgress,onSuccess:this.onSuccess,beforeUpload:this.beforeUpload}),r=void 0;if(this.props.showUploadList&&(r=g["default"].createElement(C["default"],{listType:this.props.listType,items:this.state.fileList,onPreview:this.handlePreview,onRemove:this.handleManualRemove})),"drag"===t){var o=this.state.fileList.some(function(e){return"uploading"===e.status})?S+"-drag-uploading":"",i="dragover"===this.state.dragState?S+"-drag-hover":"";return g["default"].createElement("span",{className:this.props.className},g["default"].createElement("div",{className:S+" "+S+"-drag "+o+" "+i,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,onDragLeave:this.onFileDrop},g["default"].createElement(P["default"],n,g["default"].createElement("div",{className:S+"-drag-container"},this.props.children))),r)}var s=(0,E["default"])((e={},a(e,S,!0),a(e,S+"-select",!0),a(e,S+"-select-"+this.props.listType,!0),e)),l=this.props.children?g["default"].createElement("div",{className:s},g["default"].createElement(P["default"],n)):null;return"picture-card"===this.props.listType?g["default"].createElement("span",{className:this.props.className},r,l):g["default"].createElement("span",{className:this.props.className},l,r)},t}(g["default"].Component),h.Dragger=d,h.defaultProps={type:"select",multiple:!1,action:"",data:{},accept:"",onChange:u,beforeUpload:c,showUploadList:!0,listType:"text",className:""},y);t["default"]=k,e.exports=t["default"]},function(e,t,n){"use strict";n(3),n(458),n(68)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var u,c,p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},f=n(1),d=r(f),h=n(8),y=r(h),v=n(6),m=r(v),g=n(67),b=r(g),P=n(2),O=r(P),C="ant-upload",T=function(e,t){var n=new FileReader;n.onloadend=function(){return t(n.result)},n.readAsDataURL(e)},w=(c=u=function(e){function t(){var n,r,o;i(this,t);for(var a=arguments.length,l=Array(a),u=0;u<a;u++)l[u]=arguments[u];return n=r=s(this,e.call.apply(e,[this].concat(l))),r.handleClose=function(e){r.props.onRemove(e)},r.handlePreview=function(e,t){return t.preventDefault(),r.props.onPreview(e)},o=n,s(r,o)}return l(t,e),t.prototype.componentDidUpdate=function(){var e=this;"picture"!==this.props.listType&&"picture-card"!==this.props.listType||this.props.items.forEach(function(t){"undefined"!=typeof document&&"undefined"!=typeof window&&window.FileReader&&window.File&&t.originFileObj instanceof File&&void 0===t.thumbUrl&&(t.thumbUrl="",T(t.originFileObj,function(n){t.thumbUrl=n,e.forceUpdate()}))})},t.prototype.render=function(){var e,t=this,n=this.props.items.map(function(e){var n,r=void 0,o=d["default"].createElement(m["default"],{type:"paper-clip"});"picture"!==t.props.listType&&"picture-card"!==t.props.listType||(o="uploading"===e.status||!e.thumbUrl&&!e.url?"picture-card"===t.props.listType?d["default"].createElement("div",{className:C+"-list-item-uploading-text"},"\u6587\u4ef6\u4e0a\u4f20\u4e2d"):d["default"].createElement(m["default"],{className:C+"-list-item-thumbnail",type:"picture"}):d["default"].createElement("a",{className:C+"-list-item-thumbnail",onClick:function(n){return t.handlePreview(e,n)},href:e.url,target:"_blank"},d["default"].createElement("img",{src:e.thumbUrl||e.url,alt:e.name}))),"uploading"===e.status&&(r=d["default"].createElement("div",{className:C+"-list-item-progress"},d["default"].createElement(b["default"],p({type:"line"},t.props.progressAttr,{percent:e.percent}))));var i=(0,O["default"])((n={},a(n,C+"-list-item",!0),a(n,C+"-list-item-"+e.status,!0),n));return d["default"].createElement("div",{className:i,key:e.uid},d["default"].createElement("div",{className:C+"-list-item-info"},o,e.url?d["default"].createElement("a",{onClick:function(n){return t.handlePreview(e,n)},href:e.url,target:"_blank",className:C+"-list-item-name"},e.name):d["default"].createElement("span",{className:C+"-list-item-name"},e.name),"picture-card"===t.props.listType&&"uploading"!==e.status?d["default"].createElement("span",null,d["default"].createElement("a",{onClick:function(n){return t.handlePreview(e,n)},href:e.url,target:"_blank",style:{pointerEvents:e.url?"":"none"}},d["default"].createElement(m["default"],{type:"eye-o"})),d["default"].createElement(m["default"],{type:"delete",onClick:function(){return t.handleClose(e)}})):d["default"].createElement(m["default"],{type:"cross",onClick:function(){return t.handleClose(e)}})),r)}),r=(0,O["default"])((e={},a(e,C+"-list",!0),a(e,C+"-list-"+this.props.listType,!0),e));return d["default"].createElement("div",{className:r},d["default"].createElement(y["default"],{transitionName:C+"-margin-top"},n))},t}(d["default"].Component),u.defaultProps={listType:"text",items:[],progressAttr:{strokeWidth:3,showInfo:!1}},c);t["default"]=w,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=void 0;var l=n(1),u=r(l),c=n(17),p=r(c),f=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.componentDidMount=function(){(0,p["default"])(!1,"`Validation` is removed, please use `Form` which has supported validation after antd@0.12.0, or you can just import Validation from 'rc-form-validation' for compatibility")},t.prototype.render=function(){return null},t}(u["default"].Component);t["default"]=f,f.Validator=function(){},f.FieldMixin={setField:function(){}},e.exports=t["default"]},197,function(e,t,n){"use strict";function r(e){return e.charAt(0).toUpperCase()+e.slice(1).replace(/-(\w)/g,function(e,t){return t.toUpperCase()})}var o=n(125);o.keys().forEach(function(e){var n=o(e),a=e.match(/^\.\/([^_][\w-]+)\/index\.jsx?$/);a&&a[1]&&("message"===a[1]||"notification"===a[1]?t[a[1]]=n:t[r(a[1])]=n)})},function(e,t){var n=!("undefined"==typeof window||!window.document||!window.document.createElement);e.exports=n},function(e,t){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete a.animationend.animation,"TransitionEvent"in window||delete a.transitionend.transition;for(var n in a)if(a.hasOwnProperty(n)){var r=a[n];for(var o in r)if(o in t){i.push(r[o]);break}}}function r(e,t,n){e.addEventListener(t,n,!1)}function o(e,t,n){e.removeEventListener(t,n,!1)}Object.defineProperty(t,"__esModule",{value:!0});var a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},i=[];"undefined"!=typeof window&&"undefined"!=typeof document&&n();var s={addEndEventListener:function(e,t){return 0===i.length?void window.setTimeout(t,0):void i.forEach(function(n){r(e,n,t)})},endEvents:i,removeEndEventListener:function(e,t){0!==i.length&&i.forEach(function(n){o(e,n,t)})}};t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r){var o=i["default"].clone(e),a={width:t.width,height:t.height};return r.adjustX&&o.left<n.left&&(o.left=n.left),r.resizeWidth&&o.left>=n.left&&o.left+a.width>n.right&&(a.width-=o.left+a.width-n.right),r.adjustX&&o.left+a.width>n.right&&(o.left=Math.max(n.right-a.width,n.left)),r.adjustY&&o.top<n.top&&(o.top=n.top),r.resizeHeight&&o.top>=n.top&&o.top+a.height>n.bottom&&(a.height-=o.top+a.height-n.bottom),r.adjustY&&o.top+a.height>n.bottom&&(o.top=Math.max(n.bottom-a.height,n.top)),i["default"].mix(o,a)}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=t.charAt(0),r=t.charAt(1),o=e.width,a=e.height,i=void 0,s=void 0;return i=e.left,s=e.top,"c"===n?s+=a/2:"b"===n&&(s+=a),"c"===r?i+=o/2:"r"===r&&(i+=o),{left:i,top:s}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r,o){var a=void 0,s=void 0,l=void 0,u=void 0;return a={left:e.left,top:e.top},l=(0,i["default"])(t,n[1]),u=(0,i["default"])(e,n[0]),s=[u.left-l.left,u.top-l.top],{left:a.left-s[0]+r[0]-o[0],top:a.top-s[1]+r[1]-o[1]}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(258),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0,n=void 0,r=void 0;if(i["default"].isWindow(e)||9===e.nodeType){var o=i["default"].getWindow(e);t={left:i["default"].getWindowScrollLeft(o),top:i["default"].getWindowScrollTop(o)},n=i["default"].viewportWidth(o),r=i["default"].viewportHeight(o)}else t=i["default"].offset(e),n=i["default"].outerWidth(e),r=i["default"].outerHeight(e);return t.width=n,t.height=r,t}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){for(var t={left:0,right:1/0,top:0,bottom:1/0},n=(0,l["default"])(e),r=void 0,o=void 0,a=void 0,s=e.ownerDocument,u=s.defaultView||s.parentWindow,c=s.body,p=s.documentElement;n;){if(navigator.userAgent.indexOf("MSIE")!==-1&&0===n.clientWidth||n===c||n===p||"visible"===i["default"].css(n,"overflow")){if(n===c||n===p)break}else{var f=i["default"].offset(n);f.left+=n.clientLeft,f.top+=n.clientTop,t.top=Math.max(t.top,f.top),t.right=Math.min(t.right,f.left+n.clientWidth),t.bottom=Math.min(t.bottom,f.top+n.clientHeight),t.left=Math.max(t.left,f.left)}n=(0,l["default"])(n)}return r=i["default"].getWindowScrollLeft(u),o=i["default"].getWindowScrollTop(u),t.left=Math.max(t.left,r),t.top=Math.max(t.top,o),a={width:i["default"].viewportWidth(u),height:i["default"].viewportHeight(u)},t.right=Math.min(t.right,r+a.width),t.bottom=Math.min(t.bottom,o+a.height),t.top>=0&&t.left>=0&&t.bottom>t.top&&t.right>t.left?t:null}Object.defineProperty(t,"__esModule",{value:!0});var a=n(20),i=r(a),s=n(79),l=r(s);t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return e.left<n.left||e.left+t.width>n.right}function a(e,t,n){return e.top<n.top||e.top+t.height>n.bottom}function i(e,t,n){return e.left>n.right||e.left+t.width<n.left}function s(e,t,n){return e.top>n.bottom||e.top+t.height<n.top}function l(e,t,n){var r=[];return h["default"].each(e,function(e){r.push(e.replace(t,function(e){return n[e]}))}),r}function u(e,t){return e[t]=-e[t],e}function c(e,t){var n=void 0;return n=/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10),n||0}function p(e,t){e[0]=c(e[0],t.width),e[1]=c(e[1],t.height)}function f(e,t,n){var r=n.points,c=n.offset||[0,0],f=n.targetOffset||[0,0],d=n.overflow,y=n.target||t,v=n.source||e;c=[].concat(c),f=[].concat(f),d=d||{};var m={},b=0,O=(0,g["default"])(v),T=(0,C["default"])(v),x=(0,C["default"])(y);p(c,T),p(f,x);var E=(0,w["default"])(T,x,r,c,f),S=h["default"].merge(T,E);if(O&&(d.adjustX||d.adjustY)){if(d.adjustX&&o(E,T,O)){var k=l(r,/[lr]/gi,{l:"r",r:"l"}),j=u(c,0),_=u(f,0),N=(0,w["default"])(T,x,k,j,_);i(N,T,O)||(b=1,r=k,c=j,f=_)}if(d.adjustY&&a(E,T,O)){var k=l(r,/[tb]/gi,{t:"b",b:"t"}),j=u(c,1),_=u(f,1),N=(0,w["default"])(T,x,k,j,_);s(N,T,O)||(b=1,r=k,c=j,f=_)}b&&(E=(0,w["default"])(T,x,r,c,f),h["default"].mix(S,E)),m.adjustX=d.adjustX&&o(E,T,O),m.adjustY=d.adjustY&&a(E,T,O),(m.adjustX||m.adjustY)&&(S=(0,P["default"])(E,T,O,m))}return S.width!==T.width&&h["default"].css(v,"width",v.width()+S.width-T.width),S.height!==T.height&&h["default"].css(v,"height",v.height()+S.height-T.height),h["default"].offset(v,{left:S.left,top:S.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom}),{points:r,offset:c,targetOffset:f,overflow:m}}Object.defineProperty(t,"__esModule",{value:!0});var d=n(20),h=r(d),y=n(79),v=r(y),m=n(261),g=r(m),b=n(257),P=r(b),O=n(260),C=r(O),T=n(259),w=r(T);f.__getOffsetParent=v["default"],f.__getVisibleRectForElement=g["default"],t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e,t,n){n=n||{},9===t.nodeType&&(t=o.getWindow(t));var r=n.allowHorizontalScroll,a=n.onlyScrollIfNeeded,i=n.alignWithTop,s=n.alignWithLeft,l=n.offsetTop||0,u=n.offsetLeft||0,c=n.offsetBottom||0,p=n.offsetRight||0;r=void 0===r||r;var f=o.isWindow(t),d=o.offset(e),h=o.outerHeight(e),y=o.outerWidth(e),v=void 0,m=void 0,g=void 0,b=void 0,P=void 0,O=void 0,C=void 0,T=void 0,w=void 0,x=void 0;f?(C=t,x=o.height(C),w=o.width(C),T={left:o.scrollLeft(C),top:o.scrollTop(C)},P={left:d.left-T.left-u,top:d.top-T.top-l},O={left:d.left+y-(T.left+w)+p,top:d.top+h-(T.top+x)+c},b=T):(v=o.offset(t),m=t.clientHeight,g=t.clientWidth,b={left:t.scrollLeft,top:t.scrollTop},P={left:d.left-(v.left+(parseFloat(o.css(t,"borderLeftWidth"))||0))-u,top:d.top-(v.top+(parseFloat(o.css(t,"borderTopWidth"))||0))-l},O={left:d.left+y-(v.left+g+(parseFloat(o.css(t,"borderRightWidth"))||0))+p,top:d.top+h-(v.top+m+(parseFloat(o.css(t,"borderBottomWidth"))||0))+c}),P.top<0||O.top>0?i===!0?o.scrollTop(t,b.top+P.top):i===!1?o.scrollTop(t,b.top+O.top):P.top<0?o.scrollTop(t,b.top+P.top):o.scrollTop(t,b.top+O.top):a||(i=void 0===i||!!i,i?o.scrollTop(t,b.top+P.top):o.scrollTop(t,b.top+O.top)),r&&(P.left<0||O.left>0?s===!0?o.scrollLeft(t,b.left+P.left):s===!1?o.scrollLeft(t,b.left+O.left):P.left<0?o.scrollLeft(t,b.left+P.left):o.scrollLeft(t,b.left+O.left):a||(s=void 0===s||!!s,s?o.scrollLeft(t,b.left+P.left):o.scrollLeft(t,b.left+O.left)))}var o=n(264);e.exports=r},function(e,t){"use strict";function n(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,a=o.body,i=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=i.clientLeft||a.clientLeft||0,r-=i.clientTop||a.clientTop||0,{left:n,top:r}}function r(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function o(e){return r(e)}function a(e){return r(e,!0)}function i(e){var t=n(e),r=e.ownerDocument,i=r.defaultView||r.parentWindow;return t.left+=o(i),t.top+=a(i),t}function s(e,t,n){var r="",o=e.ownerDocument,a=n||o.defaultView.getComputedStyle(e,null);return a&&(r=a.getPropertyValue(t)||a[t]),r}function l(e,t){var n=e[T]&&e[T][t];if(O.test(n)&&!C.test(t)){var r=e.style,o=r[x],a=e[w][x];e[w][x]=e[T][x],r[x]="fontSize"===t?"1em":n||0,n=r.pixelLeft+E,r[x]=o,e[w][x]=a}return""===n?"auto":n}function u(e,t){for(var n=0;n<e.length;n++)t(e[n])}function c(e){return"border-box"===S(e,"boxSizing")}function p(e,t,n){var r={},o=e.style,a=void 0;for(a in t)t.hasOwnProperty(a)&&(r[a]=o[a],o[a]=t[a]);n.call(e);for(a in t)t.hasOwnProperty(a)&&(o[a]=r[a])}function f(e,t,n){var r=0,o=void 0,a=void 0,i=void 0;for(a=0;a<t.length;a++)if(o=t[a])for(i=0;i<n.length;i++){var s=void 0;s="border"===o?o+n[i]+"Width":o+n[i],r+=parseFloat(S(e,s))||0}return r}function d(e){return null!=e&&e==e.window}function h(e,t,n){if(d(e))return"width"===t?D.viewportWidth(e):D.viewportHeight(e);if(9===e.nodeType)return"width"===t?D.docWidth(e):D.docHeight(e);var r="width"===t?["Left","Right"]:["Top","Bottom"],o="width"===t?e.offsetWidth:e.offsetHeight,a=S(e),i=c(e,a),s=0;(null==o||o<=0)&&(o=void 0,s=S(e,t),(null==s||Number(s)<0)&&(s=e.style[t]||0),s=parseFloat(s)||0),void 0===n&&(n=i?N:j);var l=void 0!==o||i,u=o||s;if(n===j)return l?u-f(e,["border","padding"],r,a):s;if(l){var p=n===_?-f(e,["border"],r,a):f(e,["margin"],r,a);return u+(n===N?0:p)}return s+f(e,k.slice(n),r,a)}function y(e){var t=void 0,n=arguments;return 0!==e.offsetWidth?t=h.apply(void 0,n):p(e,A,function(){t=h.apply(void 0,n)}),t}function v(e,t,n){var r=n;{if("object"!==("undefined"==typeof t?"undefined":b(t)))return"undefined"!=typeof r?("number"==typeof r&&(r+="px"),void(e.style[t]=r)):S(e,t);for(var o in t)t.hasOwnProperty(o)&&v(e,o,t[o])}}function m(e,t){"static"===v(e,"position")&&(e.style.position="relative");var n=i(e),r={},o=void 0,a=void 0;for(a in t)t.hasOwnProperty(a)&&(o=parseFloat(v(e,a))||0,r[a]=o+t[a]-n[a]);v(e,r)}var g=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},P=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,O=new RegExp("^("+P+")(?!px)[a-z%]+$","i"),C=/^(top|right|bottom|left)$/,T="currentStyle",w="runtimeStyle",x="left",E="px",S=void 0;"undefined"!=typeof window&&(S=window.getComputedStyle?s:l);var k=["margin","border","padding"],j=-1,_=2,N=1,M=0,D={};u(["Width","Height"],function(e){D["doc"+e]=function(t){var n=t.document;return Math.max(n.documentElement["scroll"+e],n.body["scroll"+e],D["viewport"+e](n))},D["viewport"+e]=function(t){var n="client"+e,r=t.document,o=r.body,a=r.documentElement,i=a[n];return"CSS1Compat"===r.compatMode&&i||o&&o[n]||i}});var A={position:"absolute",visibility:"hidden",display:"block"};u(["width","height"],function(e){var t=e.charAt(0).toUpperCase()+e.slice(1);D["outer"+t]=function(t,n){return t&&y(t,e,n?M:N)};var n="width"===e?["Left","Right"]:["Top","Bottom"];D[e]=function(t,r){if(void 0===r)return t&&y(t,e,j);if(t){var o=S(t),a=c(t);return a&&(r+=f(t,["padding","border"],n,o)),v(t,e,r)}}}),e.exports=g({getWindow:function(e){var t=e.ownerDocument||e;return t.defaultView||t.parentWindow},offset:function(e,t){return"undefined"==typeof t?i(e):void m(e,t)},isWindow:d,each:u,css:v,clone:function(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);var r=e.overflow;if(r)for(var n in e)e.hasOwnProperty(n)&&(t.overflow[n]=e.overflow[n]);return t},scrollLeft:function(e,t){if(d(e)){if(void 0===t)return o(e);window.scrollTo(t,a(e))}else{if(void 0===t)return e.scrollLeft;e.scrollLeft=t}},scrollTop:function(e,t){if(d(e)){if(void 0===t)return a(e);window.scrollTo(o(e),t)}else{if(void 0===t)return e.scrollTop;e.scrollTop=t}},viewportWidth:0,viewportHeight:0},D)},function(e,t,n){var r;!function(o,a,i){var s=window.matchMedia;"undefined"!=typeof e&&e.exports?e.exports=i(s):(r=function(){return a[o]=i(s)}.call(t,n,t,e),!(void 0!==r&&(e.exports=r)))}("enquire",this,function(e){"use strict";function t(e,t){var n,r=0,o=e.length;for(r;r<o&&(n=t(e[r],r),n!==!1);r++);}function n(e){return"[object Array]"===Object.prototype.toString.apply(e)}function r(e){return"function"==typeof e}function o(e){this.options=e,!e.deferSetup&&this.setup()}function a(t,n){this.query=t,this.isUnconditional=n,this.handlers=[],this.mql=e(t);var r=this;this.listener=function(e){r.mql=e,r.assess()},this.mql.addListener(this.listener)}function i(){if(!e)throw new Error("matchMedia not present, legacy browsers require a polyfill");this.queries={},this.browserIsIncapable=!e("only all").matches}return o.prototype={setup:function(){this.options.setup&&this.options.setup(),this.initialised=!0},on:function(){!this.initialised&&this.setup(),this.options.match&&this.options.match()},off:function(){this.options.unmatch&&this.options.unmatch()},destroy:function(){this.options.destroy?this.options.destroy():this.off()},equals:function(e){return this.options===e||this.options.match===e}},a.prototype={addHandler:function(e){var t=new o(e);this.handlers.push(t),this.matches()&&t.on()},removeHandler:function(e){var n=this.handlers;t(n,function(t,r){if(t.equals(e))return t.destroy(),!n.splice(r,1)})},matches:function(){return this.mql.matches||this.isUnconditional},clear:function(){t(this.handlers,function(e){e.destroy()}),this.mql.removeListener(this.listener),this.handlers.length=0},assess:function(){var e=this.matches()?"on":"off";t(this.handlers,function(t){t[e]()})}},i.prototype={register:function(e,o,i){var s=this.queries,l=i&&this.browserIsIncapable;return s[e]||(s[e]=new a(e,l)),r(o)&&(o={match:o}),n(o)||(o=[o]),t(o,function(t){s[e].addHandler(t)}),this},unregister:function(e,t){var n=this.queries[e];return n&&(t?n.removeHandler(t):(n.clear(),delete this.queries[e])),this}},new i})},function(e,t){"use strict";function n(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function r(e,t){if(n(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var r=Object.keys(e),a=Object.keys(t);if(r.length!==a.length)return!1;for(var i=0;i<r.length;i++)if(!o.call(t,r[i])||!n(e[r[i]],t[r[i]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=r},17,function(e,t,n){"use strict";function r(e,t,n){return n+(h.isLeapYear(e)?u[t]:l[t])}function o(e){return e>=0?e%7:h.mod(e,7)}function a(e){var t=void 0,n=void 0,r=void 0,o=void 0,a=void 0,i=void 0,l=void 0,u=void 0,y=void 0;return t=e-1,a=s(t/d),n=h.mod(t,d),i=s(n/f),r=h.mod(n,f),l=s(r/p),o=h.mod(r,p),u=s(o/c),y=400*a+100*i+4*l+u,4!==i&&4!==u&&++y,y}var i=n(82),s=Math.floor,l=[0,31,59,90,120,151,181,212,243,273,304,334],u=[0,31,60,91,121,152,182,213,244,274,305,335],c=365,p=1461,f=25*p-1,d=4*f+1,h={};h=e.exports={each:function(e,t){for(var n=0,r=e.length;n<r&&t(e[n],n,e)!==!1;n++);},mix:function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},isLeapYear:function(e){return 0===(3&e)&&(e%100!==0||e%400===0)},mod:function(e,t){return e-t*s(e/t)},getFixedDate:function(e,t,n){var o=e-1;return c*o+s(o/4)-s(o/100)+s(o/400)+r(e,t,n)},getGregorianDateFromFixedDate:function(e){for(var t=a(e),n=h.getFixedDate(t,i.JANUARY,1),r=h.isLeapYear(t),s=r?u:l,c=e-n,p=void 0,f=0;f<s.length&&s[f]<=c;f++)p=f;var d=e-n-s[p]+1,y=o(e);return{year:t,month:p,dayOfMonth:d,dayOfWeek:y,isLeap:r}}}},function(e,t){"use strict";var n={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},r={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,a){if("string"!=typeof t){var i=Object.getOwnPropertyNames(t);o&&(i=i.concat(Object.getOwnPropertySymbols(t)));for(var s=0;s<i.length;++s)if(!(n[i[s]]||r[i[s]]||a&&a[i[s]]))try{e[i[s]]=t[i[s]]}catch(l){}}return e}},function(e,t,n){(function(e,n){function r(e,t){return e.set(t[0],t[1]),e}function o(e,t){return e.add(t),e}function a(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}function i(e,t){for(var n=-1,r=t.length,o=e.length;++n<r;)e[o+n]=t[n];return e}function s(e,t,n,r){var o=-1,a=e.length;for(r&&a&&(n=e[++o]);++o<a;)n=t(n,e[o],o,e);return n}function l(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function u(e){return e&&e.Object===Object?e:null}function c(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function p(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}function f(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}function d(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function h(){this.__data__=Rt?Rt(null):{}}function y(e){return this.has(e)&&delete this.__data__[e]}function v(e){var t=this.__data__;if(Rt){var n=t[e];return n===_e?void 0:n}return Ct.call(t,e)?t[e]:void 0}function m(e){var t=this.__data__;return Rt?void 0!==t[e]:Ct.call(t,e)}function g(e,t){var n=this.__data__;return n[e]=Rt&&void 0===t?_e:t,this}function b(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function P(){this.__data__=[]}function O(e){var t=this.__data__,n=I(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Nt.call(t,n,1),!0}function C(e){var t=this.__data__,n=I(t,e);return n<0?void 0:t[n][1]}function T(e){return I(this.__data__,e)>-1}function w(e,t){var n=this.__data__,r=I(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}function x(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function E(){this.__data__={hash:new d,map:new(Lt||b),string:new d}}function S(e){return oe(this,e)["delete"](e)}function k(e){return oe(this,e).get(e)}function j(e){return oe(this,e).has(e)}function _(e,t){return oe(this,e).set(e,t),this}function N(e){this.__data__=new b(e)}function M(){this.__data__=new b}function D(e){return this.__data__["delete"](e)}function A(e){return this.__data__.get(e)}function L(e){return this.__data__.has(e)}function V(e,t){var n=this.__data__;return n instanceof b&&n.__data__.length==je&&(n=this.__data__=new x(n.__data__)),n.set(e,t),this}function F(e,t,n){var r=e[t];Ct.call(e,t)&&me(r,n)&&(void 0!==n||t in e)||(e[t]=n)}function I(e,t){for(var n=e.length;n--;)if(me(e[n][0],t))return n;return-1}function R(e,t){return e&&te(t,Se(t),e)}function K(e,t,n,r,o,i,s){var l;if(r&&(l=i?r(e,o,i,s):r(e)),void 0!==l)return l;if(!Te(e))return e;var u=Gt(e);if(u){if(l=ue(e),!t)return ee(e,l)}else{var p=le(e),f=p==Fe||p==Ie;if(Xt(e))return Y(e,t);if(p==We||p==Me||f&&!i){if(c(e))return i?e:{};if(l=ce(f?{}:e),!t)return ne(e,R(l,e))}else{if(!ut[p])return i?e:{};l=pe(e,p,K,t)}}s||(s=new N);var d=s.get(e);if(d)return d;if(s.set(e,l),!u)var h=n?re(e):Se(e);return a(h||e,function(o,a){h&&(a=o,o=e[a]),F(l,a,K(o,t,n,r,a,e,s))}),l}function W(e){return Te(e)?jt(e):{}}function H(e,t,n){var r=t(e);return Gt(e)?r:i(r,n(e))}function B(e,t){return Ct.call(e,t)||"object"==typeof e&&t in e&&null===ie(e)}function z(e){ return Dt(Object(e))}function U(e){return function(t){return null==t?void 0:t[e]}}function Y(e,t){if(t)return e.slice();var n=new e.constructor(e.length);return e.copy(n),n}function q(e){var t=new e.constructor(e.byteLength);return new St(t).set(new St(e)),t}function G(e,t){var n=t?q(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.byteLength)}function X(e,t,n){var o=t?n(p(e),!0):p(e);return s(o,r,new e.constructor)}function $(e){var t=new e.constructor(e.source,it.exec(e));return t.lastIndex=e.lastIndex,t}function Q(e,t,n){var r=t?n(f(e),!0):f(e);return s(r,o,new e.constructor)}function Z(e){return Yt?Object(Yt.call(e)):{}}function J(e,t){var n=t?q(e.buffer):e.buffer;return new e.constructor(n,e.byteOffset,e.length)}function ee(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}function te(e,t,n,r){n||(n={});for(var o=-1,a=t.length;++o<a;){var i=t[o],s=r?r(n[i],e[i],i,n,e):e[i];F(n,i,s)}return n}function ne(e,t){return te(e,se(e),t)}function re(e){return H(e,Se,se)}function oe(e,t){var n=e.__data__;return he(t)?n["string"==typeof t?"string":"hash"]:n.map}function ae(e,t){var n=e[t];return xe(n)?n:void 0}function ie(e){return Mt(Object(e))}function se(e){return kt(Object(e))}function le(e){return Tt.call(e)}function ue(e){var t=e.length,n=e.constructor(t);return t&&"string"==typeof e[0]&&Ct.call(e,"index")&&(n.index=e.index,n.input=e.input),n}function ce(e){return"function"!=typeof e.constructor||ye(e)?{}:W(ie(e))}function pe(e,t,n,r){var o=e.constructor;switch(t){case Ge:return q(e);case Ae:case Le:return new o((+e));case Xe:return G(e,r);case $e:case Qe:case Ze:case Je:case et:case tt:case nt:case rt:case ot:return J(e,r);case Re:return X(e,r,n);case Ke:case Ue:return new o(e);case Be:return $(e);case ze:return Q(e,r,n);case Ye:return Z(e)}}function fe(e){var t=e?e.length:void 0;return Ce(t)&&(Gt(e)||Ee(e)||ge(e))?l(t,String):null}function de(e,t){return t=null==t?Ne:t,!!t&&("number"==typeof e||lt.test(e))&&e>-1&&e%1==0&&e<t}function he(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}function ye(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||Pt;return e===n}function ve(e){if(null!=e){try{return Ot.call(e)}catch(t){}try{return e+""}catch(t){}}return""}function me(e,t){return e===t||e!==e&&t!==t}function ge(e){return Pe(e)&&Ct.call(e,"callee")&&(!_t.call(e,"callee")||Tt.call(e)==Me)}function be(e){return null!=e&&Ce(qt(e))&&!Oe(e)}function Pe(e){return we(e)&&be(e)}function Oe(e){var t=Te(e)?Tt.call(e):"";return t==Fe||t==Ie}function Ce(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=Ne}function Te(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function we(e){return!!e&&"object"==typeof e}function xe(e){if(!Te(e))return!1;var t=Oe(e)||c(e)?wt:st;return t.test(ve(e))}function Ee(e){return"string"==typeof e||!Gt(e)&&we(e)&&Tt.call(e)==Ue}function Se(e){var t=ye(e);if(!t&&!be(e))return z(e);var n=fe(e),r=!!n,o=n||[],a=o.length;for(var i in e)!B(e,i)||r&&("length"==i||de(i,a))||t&&"constructor"==i||o.push(i);return o}function ke(e){return function(){return e}}var je=200,_e="__lodash_hash_undefined__",Ne=9007199254740991,Me="[object Arguments]",De="[object Array]",Ae="[object Boolean]",Le="[object Date]",Ve="[object Error]",Fe="[object Function]",Ie="[object GeneratorFunction]",Re="[object Map]",Ke="[object Number]",We="[object Object]",He="[object Promise]",Be="[object RegExp]",ze="[object Set]",Ue="[object String]",Ye="[object Symbol]",qe="[object WeakMap]",Ge="[object ArrayBuffer]",Xe="[object DataView]",$e="[object Float32Array]",Qe="[object Float64Array]",Ze="[object Int8Array]",Je="[object Int16Array]",et="[object Int32Array]",tt="[object Uint8Array]",nt="[object Uint8ClampedArray]",rt="[object Uint16Array]",ot="[object Uint32Array]",at=/[\\^$.*+?()[\]{}|]/g,it=/\w*$/,st=/^\[object .+?Constructor\]$/,lt=/^(?:0|[1-9]\d*)$/,ut={};ut[Me]=ut[De]=ut[Ge]=ut[Xe]=ut[Ae]=ut[Le]=ut[$e]=ut[Qe]=ut[Ze]=ut[Je]=ut[et]=ut[Re]=ut[Ke]=ut[We]=ut[Be]=ut[ze]=ut[Ue]=ut[Ye]=ut[tt]=ut[nt]=ut[rt]=ut[ot]=!0,ut[Ve]=ut[Fe]=ut[qe]=!1;var ct={"function":!0,object:!0},pt=ct[typeof t]&&t&&!t.nodeType?t:void 0,ft=ct[typeof e]&&e&&!e.nodeType?e:void 0,dt=ft&&ft.exports===pt?pt:void 0,ht=u(pt&&ft&&"object"==typeof n&&n),yt=u(ct[typeof self]&&self),vt=u(ct[typeof window]&&window),mt=u(ct[typeof this]&&this),gt=ht||vt!==(mt&&mt.window)&&vt||yt||mt||Function("return this")(),bt=Array.prototype,Pt=Object.prototype,Ot=Function.prototype.toString,Ct=Pt.hasOwnProperty,Tt=Pt.toString,wt=RegExp("^"+Ot.call(Ct).replace(at,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),xt=dt?gt.Buffer:void 0,Et=gt.Symbol,St=gt.Uint8Array,kt=Object.getOwnPropertySymbols,jt=Object.create,_t=Pt.propertyIsEnumerable,Nt=bt.splice,Mt=Object.getPrototypeOf,Dt=Object.keys,At=ae(gt,"DataView"),Lt=ae(gt,"Map"),Vt=ae(gt,"Promise"),Ft=ae(gt,"Set"),It=ae(gt,"WeakMap"),Rt=ae(Object,"create"),Kt=ve(At),Wt=ve(Lt),Ht=ve(Vt),Bt=ve(Ft),zt=ve(It),Ut=Et?Et.prototype:void 0,Yt=Ut?Ut.valueOf:void 0;d.prototype.clear=h,d.prototype["delete"]=y,d.prototype.get=v,d.prototype.has=m,d.prototype.set=g,b.prototype.clear=P,b.prototype["delete"]=O,b.prototype.get=C,b.prototype.has=T,b.prototype.set=w,x.prototype.clear=E,x.prototype["delete"]=S,x.prototype.get=k,x.prototype.has=j,x.prototype.set=_,N.prototype.clear=M,N.prototype["delete"]=D,N.prototype.get=A,N.prototype.has=L,N.prototype.set=V;var qt=U("length");kt||(se=function(){return[]}),(At&&le(new At(new ArrayBuffer(1)))!=Xe||Lt&&le(new Lt)!=Re||Vt&&le(Vt.resolve())!=He||Ft&&le(new Ft)!=ze||It&&le(new It)!=qe)&&(le=function(e){var t=Tt.call(e),n=t==We?e.constructor:void 0,r=n?ve(n):void 0;if(r)switch(r){case Kt:return Xe;case Wt:return Re;case Ht:return He;case Bt:return ze;case zt:return qe}return t});var Gt=Array.isArray,Xt=xt?function(e){return e instanceof xt}:ke(!1);e.exports=K}).call(t,n(48)(e),function(){return this}())},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return i(n)?n:void 0}function o(e){return a(e)&&f.call(e)==s}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function i(e){return null!=e&&(o(e)?d.test(c.call(e)):n(e)&&l.test(e))}var s="[object Function]",l=/^\[object .+?Constructor\]$/,u=Object.prototype,c=Function.prototype.toString,p=u.hasOwnProperty,f=u.toString,d=RegExp("^"+c.call(p).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=r},function(e,t,n){(function(e,n){function r(e){return e&&e.Object===Object?e:null}var o={"function":!0,object:!0},a=o[typeof t]&&t&&!t.nodeType?t:void 0,i=o[typeof e]&&e&&!e.nodeType?e:void 0,s=r(a&&i&&"object"==typeof n&&n),l=r(o[typeof self]&&self),u=r(o[typeof window]&&window),c=r(o[typeof this]&&this),p=s||u!==(c&&c.window)&&u||l||c||Function("return this")();e.exports=p}).call(t,n(48)(e),function(){return this}())},function(e,t){function n(e){return function(t){return null==t?void 0:t[e]}}function r(e){return a(e)&&y.call(e,"callee")&&(!m.call(e,"callee")||v.call(e)==p)}function o(e){return null!=e&&s(g(e))&&!i(e)}function a(e){return u(e)&&o(e)}function i(e){var t=l(e)?v.call(e):"";return t==f||t==d}function s(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=c}function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){return!!e&&"object"==typeof e}var c=9007199254740991,p="[object Arguments]",f="[object Function]",d="[object GeneratorFunction]",h=Object.prototype,y=h.hasOwnProperty,v=h.toString,m=h.propertyIsEnumerable,g=n("length");e.exports=r},function(e,t){function n(e){return!!e&&"object"==typeof e}function r(e,t){var n=null==e?void 0:e[t];return s(n)?n:void 0}function o(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=m}function a(e){return i(e)&&h.call(e)==u}function i(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function s(e){return null!=e&&(a(e)?y.test(f.call(e)):n(e)&&c.test(e))}var l="[object Array]",u="[object Function]",c=/^\[object .+?Constructor\]$/,p=Object.prototype,f=Function.prototype.toString,d=p.hasOwnProperty,h=p.toString,y=RegExp("^"+f.call(d).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),v=r(Array,"isArray"),m=9007199254740991,g=v||function(e){return n(e)&&o(e.length)&&h.call(e)==l};e.exports=g},function(e,t){function n(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function r(e){return f(Object(e))}function o(e){return!!e&&"object"==typeof e}function a(e){if(!o(e)||p.call(e)!=i||n(e))return!1;var t=r(e);if(null===t)return!0;var a=u.call(t,"constructor")&&t.constructor;return"function"==typeof a&&a instanceof a&&l.call(a)==c}var i="[object Object]",s=Object.prototype,l=Function.prototype.toString,u=s.hasOwnProperty,c=l.call(Object),p=s.toString,f=Object.getPrototypeOf;e.exports=a},function(e,t,n){function r(e){return function(t){return null==t?void 0:t[e]}}function o(e){return null!=e&&i(g(e))}function a(e,t){return e="number"==typeof e||d.test(e)?+e:-1,t=null==t?m:t,e>-1&&e%1==0&&e<t}function i(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=m}function s(e){for(var t=u(e),n=t.length,r=n&&e.length,o=!!r&&i(r)&&(f(e)||p(e)),s=-1,l=[];++s<n;){var c=t[s];(o&&a(c,r)||y.call(e,c))&&l.push(c)}return l}function l(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function u(e){if(null==e)return[];l(e)||(e=Object(e));var t=e.length;t=t&&i(t)&&(f(e)||p(e))&&t||0;for(var n=e.constructor,r=-1,o="function"==typeof n&&n.prototype===e,s=Array(t),u=t>0;++r<t;)s[r]=r+"";for(var c in e)u&&a(c,t)||"constructor"==c&&(o||!y.call(e,c))||s.push(c);return s}var c=n(271),p=n(273),f=n(274),d=/^\d+$/,h=Object.prototype,y=h.hasOwnProperty,v=c(Object,"keys"),m=9007199254740991,g=r("length"),b=v?function(e){var t=null==e?void 0:e.constructor;return"function"==typeof t&&t.prototype===e||"function"!=typeof e&&o(e)?s(e):l(e)?v(e):[]}:s;e.exports=b},function(e,t,n){(function(e,n){function r(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}function o(e){return e&&e.Object===Object?e:null}function a(e){for(var t,n=[];!(t=e.next()).done;)n.push(t.value);return n}function i(e){e=null==e?e:Object(e);var t=[];for(var n in e)t.push(n);return t}function s(e){return function(t){return null==t?void 0:t[e]}}function l(e){var t=e?e.length:void 0;return y(t)&&(W(e)||g(e)||p(e))?r(t,String):null}function u(e,t){return t=null==t?P:t,!!t&&("number"==typeof e||x.test(e))&&e>-1&&e%1==0&&e<t}function c(e){var t=e&&e.constructor,n="function"==typeof t&&t.prototype||A;return e===n}function p(e){return d(e)&&L.call(e,"callee")&&(!R.call(e,"callee")||V.call(e)==O)}function f(e){return null!=e&&y(K(e))&&!h(e)}function d(e){return m(e)&&f(e)}function h(e){var t=v(e)?V.call(e):"";return t==C||t==T}function y(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=P}function v(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function m(e){return!!e&&"object"==typeof e}function g(e){return"string"==typeof e||!W(e)&&m(e)&&V.call(e)==w}function b(e){for(var t=-1,n=c(e),r=i(e),o=r.length,a=l(e),s=!!a,p=a||[],f=p.length;++t<o;){var d=r[t];s&&("length"==d||u(d,f))||"constructor"==d&&(n||!L.call(e,d))||p.push(d)}return p}var P=9007199254740991,O="[object Arguments]",C="[object Function]",T="[object GeneratorFunction]",w="[object String]",x=/^(?:0|[1-9]\d*)$/,E={"function":!0,object:!0},S=E[typeof t]&&t&&!t.nodeType?t:void 0,k=E[typeof e]&&e&&!e.nodeType?e:void 0,j=o(S&&k&&"object"==typeof n&&n),_=o(E[typeof self]&&self),N=o(E[typeof window]&&window),M=o(E[typeof this]&&this),D=j||N!==(M&&M.window)&&N||_||M||Function("return this")(),A=Object.prototype,L=A.hasOwnProperty,V=A.toString,F=D.Reflect,I=F?F.enumerate:void 0,R=A.propertyIsEnumerable;I&&!R.call({valueOf:1},"valueOf")&&(i=function(e){return a(I(e))});var K=s("length"),W=Array.isArray;e.exports=b}).call(t,n(48)(e),function(){return this}())},function(e,t,n){function r(e,t){for(var n=-1,r=e.length;++n<r&&t(e[n],n,e)!==!1;);return e}function o(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(n){}return t}function a(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function i(){this.__data__=qe?qe(null):{}}function s(e){return this.has(e)&&delete this.__data__[e]}function l(e){var t=this.__data__;if(qe){var n=t[e];return n===se?void 0:n}return We.call(t,e)?t[e]:void 0}function u(e){var t=this.__data__;return qe?void 0!==t[e]:We.call(t,e)}function c(e,t){var n=this.__data__;return n[e]=qe&&void 0===t?se:t,this}function p(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function f(){this.__data__=[]}function d(e){var t=this.__data__,n=N(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Ue.call(t,n,1),!0}function h(e){var t=this.__data__,n=N(t,e);return n<0?void 0:t[n][1]}function y(e){return N(this.__data__,e)>-1}function v(e,t){var n=this.__data__,r=N(n,e);return r<0?n.push([e,t]):n[r][1]=t,this}function m(e){var t=-1,n=e?e.length:0;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}function g(){this.__data__={hash:new a,map:new(Ye||p),string:new a}}function b(e){return I(this,e)["delete"](e)}function P(e){return I(this,e).get(e)}function O(e){return I(this,e).has(e)}function C(e,t){return I(this,e).set(e,t),this}function T(e){this.__data__=new p(e)}function w(){this.__data__=new p}function x(e){return this.__data__["delete"](e)}function E(e){return this.__data__.get(e)}function S(e){return this.__data__.has(e)}function k(e,t){var n=this.__data__;return n instanceof p&&n.__data__.length==ie&&(n=this.__data__=new m(n.__data__)),n.set(e,t),this}function j(e,t,n){(void 0===n||z(e[t],n))&&("number"!=typeof t||void 0!==n||t in e)||(e[t]=n)}function _(e,t,n){var r=e[t];We.call(e,t)&&z(r,n)&&(void 0!==n||t in e)||(e[t]=n)}function N(e,t){for(var n=e.length;n--;)if(z(e[n][0],t))return n;return-1}function M(e,t,n,o,a){if(e!==t){if(!Xe(t)&&!J(t))var i=re(t);r(i||t,function(r,s){if(i&&(s=r,r=t[s]),$(r))a||(a=new T),D(e,t,s,n,M,o,a);else{var l=o?o(e[s],r,s+"",e,t,a):void 0;void 0===l&&(l=r),j(e,s,l)}})}}function D(e,t,n,r,o,a,i){var s=e[n],l=t[n],u=i.get(l);if(u)return void j(e,n,u);var c=a?a(s,l,n+"",e,t,i):void 0,p=void 0===c;p&&(c=l,Xe(l)||J(l)?Xe(s)?c=s:q(s)?c=L(s):(p=!1,c=te(l,!0)):ne(l)||U(l)?U(s)?c=ee(s):!$(s)||r&&G(s)?(p=!1,c=te(l,!0)):c=s:p=!1),i.set(l,c),p&&o(c,l,r,a,i),i["delete"](l),j(e,n,c)}function A(e){return function(t){return null==t?void 0:t[e]}}function L(e,t){var n=-1,r=e.length;for(t||(t=Array(r));++n<r;)t[n]=e[n];return t}function V(e,t,n,r){n||(n={});for(var o=-1,a=t.length;++o<a;){var i=t[o],s=r?r(n[i],e[i],i,n,e):e[i];_(n,i,s)}return n}function F(e){return oe(function(t,n){var r=-1,o=n.length,a=o>1?n[o-1]:void 0,i=o>2?n[2]:void 0;for(a=e.length>3&&"function"==typeof a?(o--,a):void 0,i&&W(n[0],n[1],i)&&(a=o<3?void 0:a,o=1),t=Object(t);++r<o;){var s=n[r];s&&e(t,s,r,a)}return t})}function I(e,t){var n=e.__data__;return H(t)?n["string"==typeof t?"string":"hash"]:n.map}function R(e,t){var n=e[t];return Z(n)?n:void 0}function K(e,t){return t=null==t?le:t,!!t&&("number"==typeof e||Ve.test(e))&&e>-1&&e%1==0&&e<t}function W(e,t,n){if(!$(n))return!1;var r=typeof t;return!!("number"==r?Y(n)&&K(t,n.length):"string"==r&&t in n)&&z(n[t],e)}function H(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}function B(e){if(null!=e){try{return Ke.call(e)}catch(t){}try{return e+""}catch(t){}}return""}function z(e,t){return e===t||e!==e&&t!==t}function U(e){return q(e)&&We.call(e,"callee")&&(!ze.call(e,"callee")||He.call(e)==ue)}function Y(e){return null!=e&&X(Ge(e))&&!G(e)}function q(e){return Q(e)&&Y(e)}function G(e){var t=$(e)?He.call(e):"";return t==he||t==ye}function X(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=le}function $(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function Q(e){return!!e&&"object"==typeof e}function Z(e){if(!$(e))return!1;var t=G(e)||o(e)?Be:Le;return t.test(B(e))}function J(e){return Q(e)&&X(e.length)&&!!Fe[He.call(e)]}function ee(e){return V(e,re(e))}var te=n(270),ne=n(275),re=n(277),oe=n(279),ae=n(272),ie=200,se="__lodash_hash_undefined__",le=9007199254740991,ue="[object Arguments]",ce="[object Array]",pe="[object Boolean]",fe="[object Date]",de="[object Error]",he="[object Function]",ye="[object GeneratorFunction]",ve="[object Map]",me="[object Number]",ge="[object Object]",be="[object RegExp]",Pe="[object Set]",Oe="[object String]",Ce="[object WeakMap]",Te="[object ArrayBuffer]",we="[object DataView]",xe="[object Float32Array]",Ee="[object Float64Array]",Se="[object Int8Array]",ke="[object Int16Array]",je="[object Int32Array]",_e="[object Uint8Array]",Ne="[object Uint8ClampedArray]",Me="[object Uint16Array]",De="[object Uint32Array]",Ae=/[\\^$.*+?()[\]{}|]/g,Le=/^\[object .+?Constructor\]$/,Ve=/^(?:0|[1-9]\d*)$/,Fe={};Fe[xe]=Fe[Ee]=Fe[Se]=Fe[ke]=Fe[je]=Fe[_e]=Fe[Ne]=Fe[Me]=Fe[De]=!0,Fe[ue]=Fe[ce]=Fe[Te]=Fe[pe]=Fe[we]=Fe[fe]=Fe[de]=Fe[he]=Fe[ve]=Fe[me]=Fe[ge]=Fe[be]=Fe[Pe]=Fe[Oe]=Fe[Ce]=!1;var Ie=Array.prototype,Re=Object.prototype,Ke=Function.prototype.toString,We=Re.hasOwnProperty,He=Re.toString,Be=RegExp("^"+Ke.call(We).replace(Ae,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),ze=Re.propertyIsEnumerable,Ue=Ie.splice,Ye=R(ae,"Map"),qe=R(Object,"create");a.prototype.clear=i,a.prototype["delete"]=s,a.prototype.get=l,a.prototype.has=u,a.prototype.set=c,p.prototype.clear=f,p.prototype["delete"]=d,p.prototype.get=h,p.prototype.has=y,p.prototype.set=v,m.prototype.clear=g,m.prototype["delete"]=b,m.prototype.get=P,m.prototype.has=O,m.prototype.set=C,T.prototype.clear=w,T.prototype["delete"]=x,T.prototype.get=E,T.prototype.has=S,T.prototype.set=k;var Ge=A("length"),Xe=Array.isArray,$e=F(function(e,t,n,r){M(e,t,n,r)});e.exports=$e},function(e,t){function n(e,t,n){var r=n.length;switch(r){case 0:return e.call(t);case 1:return e.call(t,n[0]);case 2:return e.call(t,n[0],n[1]);case 3:return e.call(t,n[0],n[1],n[2])}return e.apply(t,n)}function r(e,t){if("function"!=typeof e)throw new TypeError(p);return t=x(void 0===t?e.length-1:u(t),0),function(){for(var r=arguments,o=-1,a=x(r.length-t,0),i=Array(a);++o<a;)i[o]=r[t+o];switch(t){case 0:return e.call(this,i);case 1:return e.call(this,r[0],i);case 2:return e.call(this,r[0],r[1],i)}var s=Array(t+1);for(o=-1;++o<t;)s[o]=r[o];return s[t]=i,n(e,this,s)}}function o(e){var t=a(e)?w.call(e):"";return t==y||t==v}function a(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}function i(e){return!!e&&"object"==typeof e}function s(e){return"symbol"==typeof e||i(e)&&w.call(e)==m}function l(e){if(!e)return 0===e?e:0;if(e=c(e),e===f||e===-f){var t=e<0?-1:1;return t*d}return e===e?e:0}function u(e){var t=l(e),n=t%1;return t===t?n?t-n:t:0}function c(e){if("number"==typeof e)return e;if(s(e))return h;if(a(e)){var t=o(e.valueOf)?e.valueOf():e;e=a(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(g,"");var n=P.test(e);return n||O.test(e)?C(e.slice(2),n?2:8):b.test(e)?h:+e}var p="Expected a function",f=1/0,d=1.7976931348623157e308,h=NaN,y="[object Function]",v="[object GeneratorFunction]",m="[object Symbol]",g=/^\s+|\s+$/g,b=/^[-+]0x[0-9a-f]+$/i,P=/^0b[01]+$/i,O=/^0o[0-7]+$/i,C=parseInt,T=Object.prototype,w=T.toString,x=Math.max;e.exports=r},function(e,t,n){var r,o,a;!function(n,i){"use strict";"object"==typeof e&&"object"==typeof e.exports?e.exports=i():(o=[],r=i,a="function"==typeof r?r.apply(t,o):r,!(void 0!==a&&(e.exports=a)))}(this,function(){"use strict";function e(e){if(!e)return!0;if(a(e)&&0===e.length)return!0;if(!r(e)){for(var t in e)if(p.call(e,t))return!1;return!0}return!1}function t(e){return c.call(e)}function n(e){return"number"==typeof e||"[object Number]"===t(e)}function r(e){return"string"==typeof e||"[object String]"===t(e)}function o(e){return"object"==typeof e&&"[object Object]"===t(e)}function a(e){return"object"==typeof e&&"number"==typeof e.length&&"[object Array]"===t(e)}function i(e){return"boolean"==typeof e||"[object Boolean]"===t(e)}function s(e){var t=parseInt(e);return t.toString()===e?t:e}function l(t,o,a,i){if(n(o)&&(o=[o]),e(o))return t;if(r(o))return l(t,o.split(".").map(s),a,i);var u=o[0];if(1===o.length){var c=t[u];return void 0!==c&&i||(t[u]=a),c}return void 0===t[u]&&(n(o[1])?t[u]=[]:t[u]={}),l(t[u],o.slice(1),a,i)}function u(t,o){if(n(o)&&(o=[o]),!e(t)){if(e(o))return t;if(r(o))return u(t,o.split("."));var i=s(o[0]),l=t[i];if(1===o.length)void 0!==l&&(a(t)?t.splice(i,1):delete t[i]);else if(void 0!==t[i])return u(t[i],o.slice(1));return t}}var c=Object.prototype.toString,p=Object.prototype.hasOwnProperty,f=function(e){return Object.keys(f).reduce(function(t,n){return"function"==typeof f[n]&&(t[n]=f[n].bind(f,e)),t},{})};return f.has=function(t,i){if(e(t))return!1;if(n(i)?i=[i]:r(i)&&(i=i.split(".")),e(i)||0===i.length)return!1;for(var s=0;s<i.length;s++){var l=i[s];if(!o(t)&&!a(t)||!p.call(t,l))return!1;t=t[l]}return!0},f.ensureExists=function(e,t,n){return l(e,t,n,!0)},f.set=function(e,t,n,r){return l(e,t,n,r)},f.insert=function(e,t,n,r){var o=f.get(e,t);r=~~r,a(o)||(o=[],f.set(e,t,o)),o.splice(r,0,n)},f.empty=function(t,s){if(e(s))return t;if(!e(t)){var l,u;if(!(l=f.get(t,s)))return t;if(r(l))return f.set(t,s,"");if(i(l))return f.set(t,s,!1);if(n(l))return f.set(t,s,0);if(a(l))l.length=0;else{if(!o(l))return f.set(t,s,null);for(u in l)p.call(l,u)&&delete l[u]}}},f.push=function(e,t){var n=f.get(e,t);a(n)||(n=[],f.set(e,t,n)),n.push.apply(n,Array.prototype.slice.call(arguments,2))},f.coalesce=function(e,t,n){for(var r,o=0,a=t.length;o<a;o++)if(void 0!==(r=f.get(e,t[o])))return r;return n},f.get=function(t,o,a){if(n(o)&&(o=[o]),e(o))return t;if(e(t))return a;if(r(o))return f.get(t,o.split("."),a);var i=s(o[0]);return 1===o.length?void 0===t[i]?a:t[i]:f.get(t[i],o.slice(1),a)},f.del=function(e,t){return u(e,t)},f})},function(e,t){function n(){p&&u&&(p=!1,u.length?c=u.concat(c):f=-1,c.length&&r())}function r(){if(!p){var e=i(n);p=!0;for(var t=c.length;t;){for(u=c,c=[];++f<t;)u&&u[f].run();f=-1,t=c.length}u=null,p=!1,s(e)}}function o(e,t){this.fun=e,this.array=t}function a(){}var i,s,l=e.exports={};!function(){try{i=setTimeout}catch(e){i=function(){throw new Error("setTimeout is not defined")}}try{s=clearTimeout}catch(e){s=function(){throw new Error("clearTimeout is not defined")}}}();var u,c=[],p=!1,f=-1;l.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];c.push(new o(e,t)),1!==c.length||p||i(r,0)},o.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=a,l.addListener=a,l.once=a,l.off=a,l.removeListener=a,l.removeAllListeners=a,l.emit=a,l.binding=function(e){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(e){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=void 0;return function(){n&&clearTimeout(n),n=setTimeout(e,t)}}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(4),l=r(s),u=n(262),c=r(u),p=n(23),f=r(p),d=n(284),h=r(d),y=i["default"].createClass({displayName:"Align",propTypes:{childrenProps:a.PropTypes.object,align:a.PropTypes.object.isRequired,target:a.PropTypes.func,onAlign:a.PropTypes.func,monitorBufferTime:a.PropTypes.number,monitorWindowResize:a.PropTypes.bool,disabled:a.PropTypes.bool,children:a.PropTypes.any},getDefaultProps:function(){return{target:function(){return window},onAlign:function(){},monitorBufferTime:50,monitorWindowResize:!1,disabled:!1}},componentDidMount:function(){var e=this.props;this.forceAlign(),!e.disabled&&e.monitorWindowResize&&this.startMonitorWindowResize()},componentDidUpdate:function(e){var t=!1,n=this.props;if(!n.disabled)if(e.disabled||e.align!==n.align)t=!0;else{var r=e.target(),o=n.target();(0,h["default"])(r)&&(0,h["default"])(o)?t=!1:r!==o&&(t=!0)}t&&this.forceAlign(),n.monitorWindowResize&&!n.disabled?this.startMonitorWindowResize():this.stopMonitorWindowResize()},componentWillUnmount:function(){this.stopMonitorWindowResize()},startMonitorWindowResize:function(){this.resizeHandler||(this.resizeHandler=(0,f["default"])(window,"resize",o(this.forceAlign,this.props.monitorBufferTime)))},stopMonitorWindowResize:function(){this.resizeHandler&&(this.resizeHandler.remove(),this.resizeHandler=null)},forceAlign:function(){var e=this.props;if(!e.disabled){var t=l["default"].findDOMNode(this);e.onAlign(t,(0,c["default"])(t,e.target(),e.align))}},render:function(){var e=this.props,t=e.childrenProps,n=e.children,r=i["default"].Children.only(n);if(t){var o={};for(var a in t)t.hasOwnProperty(a)&&(o[a]=this.props[t[a]]);return i["default"].cloneElement(r,o)}return r}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(282),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e){return null!=e&&e==e.window}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e){var t=e.children;return l["default"].isValidElement(t)&&!t.key?l["default"].cloneElement(t,{key:h}):t}function i(){}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=r(s),u=n(287),c=n(286),p=r(c),f=n(86),d=r(f),h="rc_animate_"+Date.now(),y=l["default"].createClass({displayName:"Animate",propTypes:{component:l["default"].PropTypes.any,animation:l["default"].PropTypes.object,transitionName:l["default"].PropTypes.string,transitionEnter:l["default"].PropTypes.bool,transitionAppear:l["default"].PropTypes.bool,exclusive:l["default"].PropTypes.bool,transitionLeave:l["default"].PropTypes.bool,onEnd:l["default"].PropTypes.func,onEnter:l["default"].PropTypes.func,onLeave:l["default"].PropTypes.func,onAppear:l["default"].PropTypes.func,showProp:l["default"].PropTypes.string},getDefaultProps:function(){return{animation:{},component:"span",transitionEnter:!0,transitionLeave:!0,transitionAppear:!1,onEnd:i,onEnter:i,onLeave:i,onAppear:i}},getInitialState:function(){return this.currentlyAnimatingKeys={},this.keysToEnter=[],this.keysToLeave=[],{children:(0,u.toArrayChildren)(a(this.props))}},componentDidMount:function(){var e=this,t=this.props.showProp,n=this.state.children;t&&(n=n.filter(function(e){return!!e.props[t]})),n.forEach(function(t){e.performAppear(t.key)})},componentWillReceiveProps:function(e){var t=this;this.nextProps=e;var n=(0,u.toArrayChildren)(a(e)),r=this.props;r.exclusive&&Object.keys(this.currentlyAnimatingKeys).forEach(function(e){t.stop(e)});var i=r.showProp,s=this.currentlyAnimatingKeys,c=r.exclusive?(0,u.toArrayChildren)(a(r)):this.state.children,p=[];i?(c.forEach(function(e){var t=(0,u.findChildInChildrenByKey)(n,e.key),r=void 0;r=t&&t.props[i]||!e.props[i]?t:l["default"].cloneElement(t||e,o({},i,!0)),r&&p.push(r)}),n.forEach(function(e){(0,u.findChildInChildrenByKey)(c,e.key)||p.push(e)})):p=(0,u.mergeChildren)(c,n),this.setState({children:p}),n.forEach(function(e){var n=e.key;if(!s[n]){var r=(0,u.findChildInChildrenByKey)(c,n);if(i){var o=e.props[i];if(r){var a=(0,u.findShownChildInChildrenByKey)(c,n,i);!a&&o&&t.keysToEnter.push(n)}else o&&t.keysToEnter.push(n)}else r||t.keysToEnter.push(n)}}),c.forEach(function(e){var r=e.key;if(!s[r]){var o=(0,u.findChildInChildrenByKey)(n,r);if(i){var a=e.props[i];if(o){var l=(0,u.findShownChildInChildrenByKey)(n,r,i);!l&&a&&t.keysToLeave.push(r)}else a&&t.keysToLeave.push(r)}else o||t.keysToLeave.push(r)}})},componentDidUpdate:function(){var e=this.keysToEnter;this.keysToEnter=[],e.forEach(this.performEnter);var t=this.keysToLeave;this.keysToLeave=[],t.forEach(this.performLeave)},performEnter:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillEnter(this.handleDoneAdding.bind(this,e,"enter")))},performAppear:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillAppear(this.handleDoneAdding.bind(this,e,"appear")))},handleDoneAdding:function(e,t){var n=this.props;if(delete this.currentlyAnimatingKeys[e],!n.exclusive||n===this.nextProps){var r=(0,u.toArrayChildren)(a(n));this.isValidChildByKey(r,e)?"appear"===t?d["default"].allowAppearCallback(n)&&(n.onAppear(e),n.onEnd(e,!0)):d["default"].allowEnterCallback(n)&&(n.onEnter(e),n.onEnd(e,!0)):this.performLeave(e)}},performLeave:function(e){this.refs[e]&&(this.currentlyAnimatingKeys[e]=!0,this.refs[e].componentWillLeave(this.handleDoneLeaving.bind(this,e)))},handleDoneLeaving:function(e){var t=this.props;if(delete this.currentlyAnimatingKeys[e],!t.exclusive||t===this.nextProps){var n=(0,u.toArrayChildren)(a(t));this.isValidChildByKey(n,e)?this.performEnter(e):(this.isMounted()&&!(0,u.isSameChildren)(this.state.children,n,t.showProp)&&this.setState({children:n}),d["default"].allowLeaveCallback(t)&&(t.onLeave(e),t.onEnd(e,!1)))}},isValidChildByKey:function(e,t){var n=this.props.showProp;return n?(0,u.findShownChildInChildrenByKey)(e,t,n):(0,u.findChildInChildrenByKey)(e,t)},stop:function(e){delete this.currentlyAnimatingKeys[e];var t=this.refs[e];t&&t.stop()},render:function(){var e=this.props;this.nextProps=e;var t=this.state.children,n=null;t&&(n=t.map(function(t){if(null===t)return t;if(!t.key)throw new Error("must set key for <rc-animate> children");return l["default"].createElement(p["default"],{key:t.key,ref:t.key,animation:e.animation,transitionName:e.transitionName,transitionEnter:e.transitionEnter,transitionAppear:e.transitionAppear,transitionLeave:e.transitionLeave},t)}));var r=e.component;return r?l["default"].createElement(r,this.props,n):n[0]||null}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(4),s=r(i),l=n(39),u=r(l),c=n(86),p=r(c),f={enter:"transitionEnter",appear:"transitionAppear",leave:"transitionLeave"},d=a["default"].createClass({displayName:"AnimateChild",propTypes:{children:a["default"].PropTypes.any},componentWillUnmount:function(){this.stop()},componentWillEnter:function(e){p["default"].isEnterSupported(this.props)?this.transition("enter",e):setTimeout(e,0)},componentWillAppear:function(e){p["default"].isAppearSupported(this.props)?this.transition("appear",e):setTimeout(e,0)},componentWillLeave:function(e){p["default"].isLeaveSupported(this.props)?this.transition("leave",e):setTimeout(e,0)},transition:function(e,t){var n=this,r=s["default"].findDOMNode(this),o=this.props,a=o.transitionName;this.stop();var i=function(){n.stopper=null,t()};(l.isCssAnimationSupported||!o.animation[e])&&a&&o[f[e]]?this.stopper=(0,u["default"])(r,a+"-"+e,i):this.stopper=o.animation[e](r,i)},stop:function(){var e=this.stopper;e&&(this.stopper=null,e.stop())},render:function(){return this.props.children}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=[];return p["default"].Children.forEach(e,function(e){t.push(e)}),t}function a(e,t){var n=null;return e&&e.forEach(function(e){n||e.key===t&&(n=e)}),n}function i(e,t,n){var r=null;return e&&e.forEach(function(e){if(e.key===t&&e.props[n]){if(r)throw new Error("two child with same key for <rc-animate> children");r=e}}),r}function s(e,t,n){var r=0;return e&&e.forEach(function(e){r||(r=e.key===t&&!e.props[n])}),r}function l(e,t,n){var r=e.length===t.length;return r&&e.forEach(function(e,o){var a=t[o];e.key!==a.key?r=!1:n&&e.props[n]!==a.props[n]&&(r=!1)}),r}function u(e,t){var n=[],r={},o=[]; return e.forEach(function(e){a(t,e.key)?o.length&&(r[e.key]=o,o=[]):o.push(e)}),t.forEach(function(e){r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e)}),n=n.concat(o)}Object.defineProperty(t,"__esModule",{value:!0}),t.toArrayChildren=o,t.findChildInChildrenByKey=a,t.findShownChildInChildrenByKey=i,t.findHiddenChildInChildrenByKey=s,t.isSameChildren=l,t.mergeChildren=u;var c=n(1),p=r(c)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(){var e=this.state.value.clone();e.setDayOfMonth(1),this.setValue(e)}function i(){var e=this.state.value.clone();e.setDayOfMonth(e.getActualMaximum(v["default"].MONTH)),this.setValue(e)}function s(e){var t=this.state.value.clone();t.addMonth(e),this.setValue(t)}function l(e){var t=this.state.value.clone();t.addYear(e),this.setValue(t)}function u(e){var t=this.state.value.clone();t.addWeekOfYear(e),this.setValue(t)}function c(e){var t=this.state.value.clone();t.addDayOfMonth(e),this.setValue(t)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(4),h=r(d),y=n(9),v=r(y),m=n(24),g=r(m),b=n(42),P=r(b),O=n(89),C=r(O),T=n(291),w=r(T),x=n(43),E=r(x),S=n(30),k=r(S),j=n(93),_=r(j),N=f["default"].createClass({displayName:"Calendar",propTypes:{disabledDate:p.PropTypes.func,disabledTime:p.PropTypes.any,value:p.PropTypes.object,selectedValue:p.PropTypes.object,defaultValue:p.PropTypes.object,className:p.PropTypes.string,locale:p.PropTypes.object,showWeekNumber:p.PropTypes.bool,style:p.PropTypes.object,showToday:p.PropTypes.bool,showDateInput:p.PropTypes.bool,visible:p.PropTypes.bool,onSelect:p.PropTypes.func,onOk:p.PropTypes.func,showOk:p.PropTypes.bool,prefixCls:p.PropTypes.string,onKeyDown:p.PropTypes.func,timePicker:p.PropTypes.element,dateInputPlaceholder:p.PropTypes.any,onClear:p.PropTypes.func,onChange:p.PropTypes.func},mixins:[k["default"],E["default"]],getDefaultProps:function(){return{showToday:!0,showDateInput:!0,timePicker:null,onOk:o}},getInitialState:function(){return this.nextMonth=s.bind(this,1),this.previousMonth=s.bind(this,-1),this.nextYear=l.bind(this,1),this.previousYear=l.bind(this,-1),{}},onKeyDown:function(e){if("input"!==e.target.nodeName.toLowerCase()){var t=e.keyCode,n=e.ctrlKey||e.metaKey;switch(t){case g["default"].DOWN:return u.call(this,1),e.preventDefault(),1;case g["default"].UP:return u.call(this,-1),e.preventDefault(),1;case g["default"].LEFT:return n?this.previousYear():c.call(this,-1),e.preventDefault(),1;case g["default"].RIGHT:return n?this.nextYear():c.call(this,1),e.preventDefault(),1;case g["default"].HOME:return a.call(this),e.preventDefault(),1;case g["default"].END:return i.call(this),e.preventDefault(),1;case g["default"].PAGE_DOWN:return this.nextMonth(),e.preventDefault(),1;case g["default"].PAGE_UP:return this.previousMonth(),e.preventDefault(),1;case g["default"].ENTER:return this.onSelect(this.state.value),e.preventDefault(),1;default:return this.props.onKeyDown(e),1}}},onClear:function(){this.onSelect(null),this.props.onClear()},onOk:function(){var e=this.state.selectedValue;this.isAllowedDate(e)&&this.props.onOk(e)},onDateInputChange:function(e){this.onSelect(e,{source:"dateInput"})},onDateTableSelect:function(e){this.onSelect(e)},chooseToday:function(){var e=this.state.value.clone();e.setTime(Date.now()),this.onSelect(e,{source:"todayButton"})},focus:function(){this.props.showDateInput?this.refs.dateInput.focus():h["default"].findDOMNode(this).focus()},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.disabledDate,o=e.dateInputPlaceholder,a=e.timePicker,i=e.disabledTime,s=this.state,l=s.value,u=s.selectedValue,c=e.showDateInput?f["default"].createElement(_["default"],{ref:"dateInput",formatter:this.getFormatter(),key:"date-input",timePicker:a,gregorianCalendarLocale:l.locale,locale:t,placeholder:o,showClear:!0,disabledTime:i,disabledDate:r,onClear:this.onClear,prefixCls:n,selectedValue:u,onChange:this.onDateInputChange}):null,p=[c,f["default"].createElement("div",{key:"date-panel",className:n+"-date-panel"},f["default"].createElement(C["default"],{locale:t,onValueChange:this.setValue,value:l,prefixCls:n}),f["default"].createElement("div",{className:n+"-calendar-body"},f["default"].createElement(P["default"],{locale:t,value:l,selectedValue:u,prefixCls:n,dateRender:e.dateRender,onSelect:this.onDateTableSelect,disabledDate:r,showWeekNumber:e.showWeekNumber})),f["default"].createElement(w["default"],{showOk:e.showOk,locale:t,prefixCls:n,showToday:e.showToday,disabledTime:i,gregorianCalendarLocale:l.locale,showDateInput:e.showDateInput,timePicker:a,selectedValue:u,value:l,disabledDate:r,onOk:this.onOk,onSelect:this.onSelect,onToday:this.chooseToday}))];return this.renderRoot({children:p,className:e.showWeekNumber?n+"-week-number":""})}});t["default"]=N,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(42),l=r(s),u=n(97),c=r(u),p=n(43),f=r(p),d=n(30),h=r(d),y=n(295),v=r(y),m=i["default"].createClass({displayName:"FullCalendar",propTypes:{defaultType:a.PropTypes.string,type:a.PropTypes.string,prefixCls:a.PropTypes.string,locale:a.PropTypes.object,onTypeChange:a.PropTypes.func,fullscreen:a.PropTypes.bool,monthCellRender:a.PropTypes.func,dateCellRender:a.PropTypes.func,showTypeSwitch:a.PropTypes.bool,Select:a.PropTypes.func.isRequired,headerComponents:a.PropTypes.array,headerComponent:a.PropTypes.object,headerRender:a.PropTypes.func,showHeader:a.PropTypes.bool},mixins:[h["default"],f["default"]],getDefaultProps:function(){return{defaultType:"date",fullscreen:!1,showTypeSwitch:!0,showHeader:!0,onTypeChange:function(){}}},getInitialState:function(){var e=void 0;return e="type"in this.props?this.props.type:this.props.defaultType,{type:e}},componentWillReceiveProps:function(e){"type"in e&&this.setState({type:e.type})},onMonthSelect:function(e){this.onSelect(e,{target:"month"})},setType:function(e){"type"in this.props||this.setState({type:e}),this.props.onTypeChange(e)},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.fullscreen,a=e.showHeader,s=e.headerComponent,u=e.headerRender,p=this.state,f=p.value,d=p.type,h=null;if(a)if(u)h=u(f,d,t);else{var y=s||v["default"];h=i["default"].createElement(y,o({key:"calendar-header"},e,{prefixCls:n+"-full",type:d,value:f,onTypeChange:this.setType,onValueChange:this.setValue}))}var m="date"===d?i["default"].createElement(l["default"],{dateRender:e.dateCellRender,contentRender:e.dateCellContentRender,locale:t,prefixCls:n,onSelect:this.onSelect,value:f}):i["default"].createElement(c["default"],{cellRender:e.monthCellRender,contentRender:e.monthCellContentRender,locale:t,onSelect:this.onMonthSelect,prefixCls:n+"-month-panel",value:f}),g=[h,i["default"].createElement("div",{key:"calendar-body",className:n+"-calendar-body"},m)],b=[n+"-full"];return r&&b.push(n+"-fullscreen"),this.renderRoot({children:g,className:b.join(" ")})}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}function i(){var e=new y["default"];return e.setTime(Date.now()),e}function s(e,t){var n=void 0;n=t,"right"===e&&n.addMonth(-1),this.fireValueChange(n)}function l(e,t){var n=e.selectedValue||t&&e.defaultSelectedValue||[],r=e.value;Array.isArray(r)&&(r=r[0]);var o=e.defaultValue;return Array.isArray(o)&&(o=o[0]),r||t&&o||n[0]||t&&i()}function u(e,t){if(t){var n=this.state.selectedValue,r=n.concat(),o="left"===e?0:1;r[o]=t,r[0]&&r[1]&&this.compare(r[0],r[1])>0&&(r[1-o]=void 0),this.fireSelectValueChange(r)}}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=function(){function e(e,t){var n=[],r=!0,o=!1,a=void 0;try{for(var i,s=e[Symbol.iterator]();!(r=(i=s.next()).done)&&(n.push(i.value),!t||n.length!==t);r=!0);}catch(l){o=!0,a=l}finally{try{!r&&s["return"]&&s["return"]()}finally{if(o)throw a}}return n}return function(t,n){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,n);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=n(1),d=r(f),h=n(9),y=r(h),v=n(2),m=r(v),g=n(298),b=r(g),P=n(12),O=n(91),C=r(O),T=n(90),w=r(T),x=n(30),E=r(x),S=d["default"].createClass({displayName:"RangeCalendar",propTypes:{prefixCls:f.PropTypes.string,dateInputPlaceholder:f.PropTypes.any,defaultValue:f.PropTypes.any,timePicker:f.PropTypes.any,value:f.PropTypes.any,showOk:f.PropTypes.bool,selectedValue:f.PropTypes.array,defaultSelectedValue:f.PropTypes.array,onOk:f.PropTypes.func,locale:f.PropTypes.object,onChange:f.PropTypes.func,onSelect:f.PropTypes.func,onValueChange:f.PropTypes.func,formatter:f.PropTypes.oneOfType([f.PropTypes.object,f.PropTypes.string]),onClear:f.PropTypes.func},mixins:[E["default"]],getDefaultProps:function(){return{defaultSelectedValue:[],onValueChange:a}},getInitialState:function(){var e=this.props,t=e.selectedValue||e.defaultSelectedValue,n=l(e,1);return{selectedValue:t,value:n}},componentWillReceiveProps:function(e){var t={};"value"in e&&(e.value?t.value=e.value:t.value=l(e,0),this.setState(t)),"selectedValue"in e&&(t.selectedValue=e.selectedValue,this.setState(t))},onSelect:function(e){var t=this.state.selectedValue,n=t.concat(),r=!1;!n.length||2===n.length&&!t.hovering?(n.length=1,n[0]=e,r=!0):this.compare(n[0],e)<=0?(n[1]=e,r=!0):this.compare(n[0],e)>0&&(n.length=1,n[0]=e,r=!0),r&&this.fireSelectValueChange(n)},onDayHover:function(e){var t=this.state.selectedValue;t.length&&(2!==t.length||t.hovering)&&(this.compare(e,t[0])<0||(t=t.concat(),t[1]=e,t.hovering=1,this.fireSelectValueChange(t)))},onToday:function(){this.setState({value:(0,P.getTodayTime)(this.state.value)})},onOk:function(){this.props.onOk(this.state.selectedValue)},getStartValue:function(){var e=this.state.value,t=this.state.selectedValue;return t[0]&&this.props.timePicker&&(e=e.clone(),(0,P.syncTime)(t[0],e)),e},getEndValue:function(){var e=this.state.value.clone();e.addMonth(1);var t=this.state.selectedValue;return t[1]&&this.props.timePicker&&(0,P.syncTime)(t[1],e),e},compare:function(e,t){return this.props.timePicker?e.getTime()-t.getTime():e.compareToDay(t)},fireSelectValueChange:function(e,t){"selectedValue"in this.props||this.setState({selectedValue:e}),this.props.onChange(e),(t||e[0]&&e[1]&&!e.hovering)&&this.props.onSelect(e)},fireValueChange:function(e){var t=this.props;"value"in t||this.setState({value:e}),t.onValueChange(e)},clear:function(){this.fireSelectValueChange([],!0),this.props.onClear()},render:function(){var e,t=this.props,n=this.state,r=t.prefixCls,a=t.dateInputPlaceholder,i=t.timePicker,l=t.showOk,f=t.locale,h=(e={},o(e,t.className,!!t.className),o(e,r,1),o(e,r+"-hidden",!t.visible),o(e,r+"-range",1),o(e,r+"-week-number",t.showWeekNumber),e),y=(0,m["default"])(h),v={selectedValue:n.selectedValue,onSelect:this.onSelect,onDayHover:this.onDayHover},g=void 0,P=void 0;if(a)if(Array.isArray(a)){var O=p(a,2);g=O[0],P=O[1]}else g=P=a;return d["default"].createElement("div",{className:y,style:t.style,tabIndex:"0"},d["default"].createElement("a",{className:r+"-clear-btn",role:"button",title:f.clear,onClick:this.clear}),d["default"].createElement(b["default"],c({},t,v,{direction:"left",formatter:this.getFormatter(),value:this.getStartValue(),placeholder:g,onInputSelect:u.bind(this,"left"),onValueChange:s.bind(this,"left")})),d["default"].createElement("span",{className:r+"-range-middle"},"~"),d["default"].createElement(b["default"],c({},t,v,{direction:"right",formatter:this.getFormatter(),placeholder:P,value:this.getEndValue(),onInputSelect:u.bind(this,"right"),onValueChange:s.bind(this,"right")})),d["default"].createElement("div",{className:r+"-range-bottom"},d["default"].createElement(C["default"],c({},t,{value:n.value,onToday:this.onToday,text:f.backToToday})),l===!0||l!==!1&&i?d["default"].createElement(w["default"],c({},t,{value:n.value,onOk:this.onOk,okDisabled:2!==n.selectedValue.length||n.selectedValue.hovering})):null))}});t["default"]=S,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(4),l=r(s),u=n(45),c=r(u),p=n(91),f=r(p),d=n(90),h=r(d),y=n(12),v=i["default"].createClass({displayName:"CalendarFooter",propTypes:{prefixCls:a.PropTypes.string,showDateInput:a.PropTypes.bool,disabledTime:a.PropTypes.any,gregorianCalendarLocale:a.PropTypes.object,selectedValue:a.PropTypes.any,showOk:a.PropTypes.bool,onSelect:a.PropTypes.func,value:a.PropTypes.object,defaultValue:a.PropTypes.object},onSelect:function(e){this.props.onSelect(e)},getRootDOMNode:function(){return l["default"].findDOMNode(this)},render:function(){var e=this.props,t=e.value,n=e.prefixCls,r=e.showDateInput,a=e.disabledTime,s=e.gregorianCalendarLocale,l=e.selectedValue,u=e.showOk,p=!r&&e.timePicker||null,d=a&&p?(0,y.getTimeConfig)(l,a):null,v=null;if(e.showToday||p){var m=void 0;e.showToday&&(m=i["default"].createElement(f["default"],o({},e,{value:t})));var g=void 0;(u===!0||u!==!1&&e.timePicker)&&(g=i["default"].createElement(h["default"],e));var b=void 0;(m||g)&&(b=i["default"].createElement("span",{className:n+"-footer-btn"},(0,c["default"])([m,g]))),p&&(p=i["default"].cloneElement(p,o({onChange:this.onSelect,allowEmpty:!1,gregorianCalendarLocale:s},d,{getPopupContainer:this.getRootDOMNode,value:l}))),v=i["default"].createElement("div",{className:n+"-footer"},p,b)}return v}});t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return e&&t&&0===e.compareToDay(t)}function a(e,t){return e.getYear()<t.getYear()?1:e.getYear()===t.getYear()&&e.getMonth()<t.getMonth()}function i(e,t){return e.getYear()>t.getYear()?1:e.getYear()===t.getYear()&&e.getMonth()>t.getMonth()}function s(e){return"rc-calendar-"+e.getYear()+"-"+e.getMonth()+"-"+e.getDayOfMonth()}function l(){}function u(e){this.props.onSelect(e)}function c(e){this.props.onDayHover(e)}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(92),h=r(d),y=n(12),v=f["default"].createClass({displayName:"DateTBody",propTypes:{contentRender:p.PropTypes.func,dateRender:p.PropTypes.func,disabledDate:p.PropTypes.func,prefixCls:p.PropTypes.string,selectedValue:p.PropTypes.oneOfType([p.PropTypes.object,p.PropTypes.arrayOf(p.PropTypes.object)]),value:p.PropTypes.object,showWeekNumber:p.PropTypes.bool},getDefaultProps:function(){return{onDayHover:l}},render:function(){var e=this.props,t=e.contentRender,n=e.prefixCls,r=e.selectedValue,p=e.value,d=e.showWeekNumber,v=e.dateRender,m=e.disabledDate,g=void 0,b=void 0,P=void 0,O=[],C=p.clone(),T=n+"-cell",w=n+"-week-number-cell",x=n+"-date",E=n+"-today",S=n+"-selected-day",k=n+"-in-range-cell",j=n+"-last-month-cell",_=n+"-next-month-btn-day",N=n+"-disabled-cell",M=n+"-disabled-cell-first-of-row",D=n+"-disabled-cell-last-of-row";C.setTime(Date.now());var A=p.clone();A.set(p.getYear(),p.getMonth(),1);var L=A.getDayOfWeek(),V=(L+7-p.getFirstDayOfWeek())%7,F=A.clone();F.addDayOfMonth(0-V);var I=0;for(g=0;g<h["default"].DATE_ROW_COUNT;g++)for(b=0;b<h["default"].DATE_COL_COUNT;b++)P=F,I&&(P=P.clone(),P.addDayOfMonth(I)),O.push(P),I++;var R=[];for(I=0,g=0;g<h["default"].DATE_ROW_COUNT;g++){var K=void 0,W=[];for(d&&(K=f["default"].createElement("td",{key:O[I].getWeekOfYear(),role:"gridcell",className:w},O[I].getWeekOfYear())),b=0;b<h["default"].DATE_COL_COUNT;b++){var H=null,B=null;P=O[I],b<h["default"].DATE_COL_COUNT-1&&(H=O[I+1]),b>0&&(B=O[I-1]);var z=T,U=!1,Y=!1;o(P,C)&&(z+=" "+E);var q=a(P,p),G=i(P,p);if(r&&Array.isArray(r)){if(!q&&!G){var X=r[0],$=r[1];X&&o(P,X)&&(Y=!0),X&&$&&(o(P,$)&&!r.hovering?Y=!0:P.compareToDay(X)>0&&P.compareToDay($)<0&&(z+=" "+k))}}else o(P,r)&&(Y=!0);q&&(z+=" "+j),G&&(z+=" "+_),m&&m(P,p)&&(U=!0,B&&m(B,p)||(z+=" "+M),H&&m(H,p)||(z+=" "+D)),Y&&(z+=" "+S),U&&(z+=" "+N);var Q=void 0;if(v)Q=v(P,p);else{var Z=t?t(P,p):P.getDayOfMonth();Q=f["default"].createElement("div",{key:s(P),className:x,"aria-selected":Y,"aria-disabled":U},Z)}W.push(f["default"].createElement("td",{key:I,onClick:U?l:u.bind(this,P),onMouseEnter:U?l:c.bind(this,P),role:"gridcell",title:(0,y.getTitleString)(P),className:z},Q)),I++}R.push(f["default"].createElement("tr",{key:g,role:"row"},K,W))}return f["default"].createElement("tbody",{className:n+"tbody"},R)}});t["default"]=v,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var l=n(1),u=r(l),c=n(92),p=r(c),f=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.render=function(){for(var e=this.props,t=e.value,n=e.locale,r=e.prefixCls,o=[],a=[],i=t.getFirstDayOfWeek(),s=void 0,l=0;l<p["default"].DATE_COL_COUNT;l++){var c=(i+l)%p["default"].DATE_COL_COUNT;o[l]=n.format.veryShortWeekdays[c],a[l]=n.format.weekdays[c]}e.showWeekNumber&&(s=u["default"].createElement("th",{role:"columnheader",className:r+"-column-header "+r+"-week-number-header"},u["default"].createElement("span",{className:r+"-column-header-inner"},"x")));var f=a.map(function(e,t){return u["default"].createElement("th",{key:t,role:"columnheader",title:e,className:r+"-column-header"},u["default"].createElement("span",{className:r+"-column-header-inner"},o[t]))});return u["default"].createElement("thead",null,u["default"].createElement("tr",{role:"row"},s,f))},t}(u["default"].Component);t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function u(e){var t=this.state.value.clone();t.addYear(e),this.setState({value:t})}function c(e,t){var n=this.state.value.clone();n.setYear(e),n.rollSetMonth(this.state.value.getMonth()),this.props.onSelect(n),t.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var p=n(1),f=r(p),d=n(2),h=r(d),y=4,v=3,m=function(e){function t(n){i(this,t);var r=s(this,e.call(this,n));return r.state={value:n.value||n.defaultValue},r.prefixCls=n.rootPrefixCls+"-decade-panel",r.nextCentury=u.bind(r,100),r.previousCentury=u.bind(r,-100),r}return l(t,e),t.prototype.render=function(){for(var e=this,t=this.state.value,n=this.props.locale,r=t.getYear(),o=100*parseInt(r/100,10),i=o-10,s=o+99,l=[],u=0,p=this.prefixCls,d=0;d<y;d++){l[d]=[];for(var m=0;m<v;m++){var g=i+10*u,b=i+10*u+9;l[d][m]={startDecade:g,endDecade:b},u++}}var P=l.map(function(t,n){var i=t.map(function(t){var n,i=t.startDecade,l=t.endDecade,u=i<o,d=l>s,y=(n={},a(n,p+"-cell",1),a(n,p+"-selected-cell",i<=r&&r<=l),a(n,p+"-last-century-cell",u),a(n,p+"-next-century-cell",d),n),v=void 0,m=void 0;return u?m=e.previousCentury:d?m=e.nextCentury:(v=i+"-"+l,m=c.bind(e,i)),f["default"].createElement("td",{key:i,onClick:m,role:"gridcell",className:(0,h["default"])(y)},f["default"].createElement("a",{className:p+"-decade"},v))});return f["default"].createElement("tr",{key:n,role:"row"},i)});return f["default"].createElement("div",{className:this.prefixCls},f["default"].createElement("div",{className:p+"-header"},f["default"].createElement("a",{className:p+"-prev-century-btn",role:"button",onClick:this.previousCentury,title:n.previousCentury},"\xab"),f["default"].createElement("div",{className:p+"-century"},o,"-",s),f["default"].createElement("a",{className:p+"-next-century-btn",role:"button",onClick:this.nextCentury,title:n.nextCentury},"\xbb")),f["default"].createElement("div",{className:p+"-body"},f["default"].createElement("table",{className:p+"-table",cellSpacing:"0",role:"grid"},f["default"].createElement("tbody",{className:p+"-tbody"},P))))},t}(f["default"].Component);t["default"]=m,m.propTypes={locale:p.PropTypes.object,value:p.PropTypes.object,defaultValue:p.PropTypes.object,rootPrefixCls:p.PropTypes.string},m.defaultProps={onSelect:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}function l(){}Object.defineProperty(t,"__esModule",{value:!0});var u=n(1),c=r(u),p=function(e){function t(){return a(this,t),i(this,e.apply(this,arguments))}return s(t,e),t.prototype.onYearChange=function(e){var t=this.props.value.clone();t.setYear(parseInt(e,10)),this.props.onValueChange(t)},t.prototype.onMonthChange=function(e){var t=this.props.value.clone();t.setMonth(parseInt(e,10)),this.props.onValueChange(t)},t.prototype.getYearSelectElement=function(e){for(var t=this.props,n=t.yearSelectOffset,r=t.yearSelectTotal,o=t.locale,a=t.prefixCls,i=t.Select,s=e-n,l=s+r,u="\u5e74"===o.year?"\u5e74":"",p=[],f=s;f<l;f++)p.push(c["default"].createElement(i.Option,{key:""+f},f+u));return c["default"].createElement(i,{className:a+"-header-year-select",onChange:this.onYearChange.bind(this),dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1},p)},t.prototype.getMonthSelectElement=function(e){for(var t=this.props,n=t.locale.format.months,r=t.prefixCls,o=[],a=t.Select,i=0;i<12;i++)o.push(c["default"].createElement(a.Option,{key:""+i},n[i]));return c["default"].createElement(a,{className:r+"-header-month-select",dropdownStyle:{zIndex:2e3},dropdownMenuStyle:{maxHeight:250,overflow:"auto",overflowX:"hidden",fontSize:12},optionLabelProp:"children",value:String(e),showSearch:!1,onChange:this.onMonthChange.bind(this)},o)},t.prototype.changeTypeToDate=function(){this.props.onTypeChange("date")},t.prototype.changeTypeToMonth=function(){this.props.onTypeChange("month")},t.prototype.render=function(){var e=this.props,t=e.value,n=e.locale,r=e.prefixCls,o=e.type,a=e.showTypeSwitch,i=e.headerComponents,s=t.getYear(),l=t.getMonth(),u=this.getYearSelectElement(s),p="month"===o?null:this.getMonthSelectElement(l),f=r+"-header-switcher",d=a?c["default"].createElement("span",{className:f},"date"===o?c["default"].createElement("span",{className:f+"-focus"},n.month):c["default"].createElement("span",{onClick:this.changeTypeToDate.bind(this),className:f+"-normal"},n.month),"month"===o?c["default"].createElement("span",{className:f+"-focus"},n.year):c["default"].createElement("span",{onClick:this.changeTypeToMonth.bind(this),className:f+"-normal"},n.year)):null;return c["default"].createElement("div",{className:r+"-header"},d,p,u,i)},t}(u.Component);p.propTypes={value:u.PropTypes.object,locale:u.PropTypes.object,yearSelectOffset:u.PropTypes.number,yearSelectTotal:u.PropTypes.number,onValueChange:u.PropTypes.func,onTypeChange:u.PropTypes.func,Select:u.PropTypes.func,prefixCls:u.PropTypes.string,type:u.PropTypes.string,showTypeSwitch:u.PropTypes.bool,headerComponents:u.PropTypes.array},p.defaultProps={yearSelectOffset:10,yearSelectTotal:20,onValueChange:l,onTypeChange:l},t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(41),a=r(o);t["default"]={today:"Today",now:"Now",backToToday:"Back to today",ok:"Ok",clear:"Clear",month:"Month",year:"Year",monthSelect:"Choose a month",yearSelect:"Choose a year",decadeSelect:"Choose a decade",yearFormat:"yyyy",dateFormat:"M/d/yyyy",monthFormat:"MMMM",monthBeforeYear:!0,previousMonth:"Previous month (PageUp)",nextMonth:"Next month (PageDown)",previousYear:"Last year (Control + left)",nextYear:"Next year (Control + right)",previousDecade:"Last decade",nextDecade:"Next decade",previousCentury:"Last century",nextCentury:"Next century",format:a["default"]},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o={bottomLeft:{points:["tl","tl"],overflow:n,offset:[0,-3],targetOffset:r},bottomRight:{points:["tr","tr"],overflow:n,offset:[0,-3],targetOffset:r},topRight:{points:["br","br"],overflow:n,offset:[0,3],targetOffset:r},topLeft:{points:["bl","bl"],overflow:n,offset:[0,3],targetOffset:r}};t["default"]=o,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(89),l=r(s),u=n(42),c=r(u),p=n(93),f=r(p),d=i["default"].createClass({displayName:"CalendarPart",propTypes:{value:a.PropTypes.any,direction:a.PropTypes.any,prefixCls:a.PropTypes.any,locale:a.PropTypes.any,selectedValue:a.PropTypes.any,formatter:a.PropTypes.any,placeholder:a.PropTypes.any,disabledDate:a.PropTypes.any,timePicker:a.PropTypes.any,disabledTime:a.PropTypes.any},render:function(){var e=this.props,t=e.value,n=e.direction,r=e.prefixCls,a=e.locale,s=e.selectedValue,u=e.formatter,p=e.placeholder,d=e.disabledDate,h=e.timePicker,y=e.disabledTime,v=r+"-range",m={locale:a,value:t,prefixCls:r},g="left"===n?0:1;return i["default"].createElement("div",{className:v+"-part "+v+"-"+n},i["default"].createElement(f["default"],{formatter:u,locale:a,prefixCls:r,timePicker:h,disabledDate:d,placeholder:p,disabledTime:y,gregorianCalendarLocale:t.locale,showClear:!1,selectedValue:s[g],onChange:e.onInputSelect}),i["default"].createElement("div",{style:{outline:"none"}},i["default"].createElement(l["default"],o({},m,{enableNext:"right"===n,enablePrev:"left"===n,onValueChange:e.onValueChange})),i["default"].createElement("div",{className:r+"-calendar-body"},i["default"].createElement(c["default"],o({},m,{selectedValue:s,dateRender:e.dateRender,onSelect:e.onSelect,onDayHover:e.onDayHover,disabledDate:d,showWeekNumber:e.showWeekNumber})))))}});t["default"]=d,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},c=n(1),p=r(c),f=n(14),d=r(f),h=n(300),y=r(h),v={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}},bottomRight:{points:["tr","br"],offset:[0,4],overflow:{adjustX:1,adjustY:1}},topRight:{points:["br","tr"],offset:[0,-4],overflow:{adjustX:1,adjustY:1}}},m=function(e){function t(e){var n=this;a(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e);var r=[];"value"in e?r=e.value||[]:"defaultValue"in e&&(r=e.defaultValue||[]),this.state={popupVisible:e.popupVisible,activeValue:r,value:r},["handleChange","handleSelect","handlePopupVisibleChange","setPopupVisible","getPopupDOMNode"].forEach(function(e){return n[e]=n[e].bind(n)})}return i(t,e),l(t,[{key:"componentWillReceiveProps",value:function(e){"value"in e&&this.setState({value:e.value||[],activeValue:e.value||[]}),"popupVisible"in e&&this.setState({popupVisible:e.popupVisible})}},{key:"getPopupDOMNode",value:function(){return this.refs.trigger.getPopupDomNode()}},{key:"setPopupVisible",value:function(e){"popupVisible"in this.props||this.setState({popupVisible:e}),e&&!this.state.visible&&this.setState({activeValue:this.state.value}),this.props.onPopupVisibleChange(e)}},{key:"handleChange",value:function(e,t){this.props.onChange(e.map(function(e){return e.value}),e),this.setPopupVisible(t.visible)}},{key:"handlePopupVisibleChange",value:function(e){this.setPopupVisible(e)}},{key:"handleSelect",value:function(e){var t=o(e,[]);"value"in this.props&&delete t.value,this.setState(t)}},{key:"render",value:function(){var e=this.props,t=e.prefixCls,n=e.transitionName,r=e.popupClassName,a=e.popupPlacement,i=o(e,["prefixCls","transitionName","popupClassName","popupPlacement"]),l=p["default"].createElement("div",null),u="";return e.options&&e.options.length>0?l=p["default"].createElement(y["default"],s({},e,{value:this.state.value,activeValue:this.state.activeValue,onSelect:this.handleSelect,onChange:this.handleChange, visible:this.state.popupVisible})):u=" "+t+"-menus-empty",p["default"].createElement(d["default"],s({ref:"trigger"},i,{popupPlacement:a,builtinPlacements:v,popupTransitionName:n,action:e.disabled?[]:["click"],popupVisible:!e.disabled&&this.state.popupVisible,onPopupVisibleChange:this.handlePopupVisibleChange,prefixCls:t+"-menus",popupClassName:r+u,popup:l}),e.children)}}]),t}(p["default"].Component);m.defaultProps={options:[],onChange:function(){},onPopupVisibleChange:function(){},disabled:!1,transitionName:"",prefixCls:"rc-cascader",popupClassName:"",popupPlacement:"bottomLeft"},m.propTypes={value:p["default"].PropTypes.array,defaultValue:p["default"].PropTypes.array,options:p["default"].PropTypes.array.isRequired,onChange:p["default"].PropTypes.func,onPopupVisibleChange:p["default"].PropTypes.func,popupVisible:p["default"].PropTypes.bool,disabled:p["default"].PropTypes.bool,transitionName:p["default"].PropTypes.string,popupClassName:p["default"].PropTypes.string,popupPlacement:p["default"].PropTypes.string,prefixCls:p["default"].PropTypes.string},t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),l=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},u=n(1),c=r(u),p=n(50),f=r(p),d=n(4),h=function(e){function t(){o(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return a(t,e),s(t,[{key:"componentDidMount",value:function(){this.scrollActiveItemToView()}},{key:"componentDidUpdate",value:function(e){!e.visible&&this.props.visible&&this.scrollActiveItemToView()}},{key:"onSelect",value:function(e,t){if(e&&!e.disabled){var n=this.props.activeValue;n=n.slice(0,t+1),n[t]=e.value;var r=this.getActiveOptions(n);if(e.isLeaf===!1&&!e.children&&this.props.loadData)return this.props.onSelect({activeValue:n}),void this.props.loadData(r);var o={};e.children&&e.children.length?this.props.changeOnSelect&&(this.props.onChange(r,{visible:!0}),o.value=n):(this.props.onChange(r,{visible:!1}),o.value=n),o.activeValue=n,this.props.onSelect(o)}}},{key:"getOption",value:function(e,t){var n=this.props,r=n.prefixCls,o=n.expandTrigger,a=this.onSelect.bind(this,e,t),s={onClick:a},l=r+"-menu-item";"hover"===o&&e.children&&e.children.length>0&&(s={onMouseEnter:this.delayOnSelect.bind(this,a),onMouseLeave:this.delayOnSelect.bind(this)},l+=" "+r+"-menu-item-expand"),this.isActiveOption(e)&&(l+=" "+r+"-menu-item-active",s.ref="activeItem"+t),e.disabled&&(l+=" "+r+"-menu-item-disabled");var u="";return e.title?u=e.title:"string"==typeof e.label&&(u=e.label),c["default"].createElement("li",i({key:e.value,className:l,title:u},s),e.label)}},{key:"getActiveOptions",value:function(e){var t=e||this.props.activeValue,n=this.props.options;return(0,f["default"])(n,function(e,n){return e.value===t[n]})}},{key:"getShowOptions",value:function(){var e=this.props.options,t=this.getActiveOptions().map(function(e){return e.children}).filter(function(e){return!!e});return t.unshift(e),t}},{key:"delayOnSelect",value:function(e){var t=this;this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null),"function"==typeof e&&(this.delayTimer=setTimeout(function(){e(),t.delayTimer=null},150))}},{key:"scrollActiveItemToView",value:function(){for(var e=this.getShowOptions().length,t=0;t<e;t++){var n=this.refs["activeItem"+t];if(n){var r=(0,d.findDOMNode)(n);r.parentNode.scrollTop=r.offsetTop}}}},{key:"isActiveOption",value:function(e){return this.props.activeValue.some(function(t){return t===e.value})}},{key:"render",value:function(){var e=this,t=this.props.prefixCls;return c["default"].createElement("div",null,this.getShowOptions().map(function(n,r){return c["default"].createElement("ul",{className:t+"-menu",key:r},n.map(function(t){return e.getOption(t,r)}))}))}}]),t}(c["default"].Component);h.defaultProps={options:[],value:[],activeValue:[],onChange:function(){},onSelect:function(){},prefixCls:"rc-cascader-menus",visible:!1,expandTrigger:"click",changeOnSelect:!1},h.propTypes={value:c["default"].PropTypes.array,activeValue:c["default"].PropTypes.array,options:c["default"].PropTypes.array.isRequired,prefixCls:c["default"].PropTypes.string,expandTrigger:c["default"].PropTypes.string,onChange:c["default"].PropTypes.func,onSelect:c["default"].PropTypes.func,loadData:c["default"].PropTypes.func,visible:c["default"].PropTypes.bool,changeOnSelect:c["default"].PropTypes.bool},t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(299),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=n(1),p=r(c),f=n(15),d=r(f),h=n(2),y=r(h),v=function(e){function t(e){a(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));m.call(n);var r=!1;return r="checked"in e?e.checked:e.defaultChecked,n.state={checked:r,focus:!1},n}return s(t,e),u(t,[{key:"componentWillReceiveProps",value:function(e){"checked"in e&&this.setState({checked:e.checked})}},{key:"shouldComponentUpdate",value:function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return d["default"].shouldComponentUpdate.apply(this,t)}},{key:"render",value:function(){var e,t=l({},this.props);delete t.defaultChecked;var n=this.state,r=t.prefixCls,a=n.checked;"boolean"==typeof a&&(a=a?1:0);var i=(0,y["default"])((e={},o(e,t.className,!!t.className),o(e,r,1),o(e,r+"-checked",a),o(e,r+"-checked-"+a,!!a),o(e,r+"-focused",n.focus),o(e,r+"-disabled",t.disabled),e));return p["default"].createElement("span",{className:i,style:t.style},p["default"].createElement("span",{className:r+"-inner"}),p["default"].createElement("input",{name:t.name,type:t.type,readOnly:t.readOnly,disabled:t.disabled,className:r+"-input",checked:!!a,onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange}))}}]),t}(p["default"].Component),m=function(){var e=this;this.handleFocus=function(t){e.setState({focus:!0}),e.props.onFocus(t)},this.handleBlur=function(t){e.setState({focus:!1}),e.props.onBlur(t)},this.handleChange=function(t){var n=e.state.checked;"checked"in e.props||e.setState({checked:!n}),e.props.onChange({target:l({},e.props,{checked:!n}),stopPropagation:function(){t.stopPropagation()},preventDefault:function(){t.preventDefault()}})}};t["default"]=v,v.propTypes={name:p["default"].PropTypes.string,prefixCls:p["default"].PropTypes.string,style:p["default"].PropTypes.object,type:p["default"].PropTypes.string,className:p["default"].PropTypes.string,defaultChecked:p["default"].PropTypes.oneOfType([p["default"].PropTypes.number,p["default"].PropTypes.bool]),checked:p["default"].PropTypes.oneOfType([p["default"].PropTypes.number,p["default"].PropTypes.bool]),onFocus:p["default"].PropTypes.func,onBlur:p["default"].PropTypes.func,onChange:p["default"].PropTypes.func},v.defaultProps={prefixCls:"rc-checkbox",style:{},type:"checkbox",className:"",defaultChecked:!1,onFocus:function(){},onBlur:function(){},onChange:function(){}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e){var t=e;return Array.isArray(t)||(t=t?[t]:[]),t}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(304),u=r(l),c=n(307),p=r(c),f=s["default"].createClass({displayName:"Collapse",propTypes:{children:i.PropTypes.any,prefixCls:i.PropTypes.string,activeKey:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.arrayOf(i.PropTypes.string)]),defaultActiveKey:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.arrayOf(i.PropTypes.string)]),openAnimation:i.PropTypes.object,onChange:i.PropTypes.func,accordion:i.PropTypes.bool},statics:{Panel:u["default"]},getDefaultProps:function(){return{prefixCls:"rc-collapse",onChange:function(){},accordion:!1}},getInitialState:function(){var e=this.props,t=e.activeKey,n=e.defaultActiveKey,r=n;return"activeKey"in this.props&&(r=t),{openAnimation:this.props.openAnimation||(0,p["default"])(this.props.prefixCls),activeKey:a(r)}},componentWillReceiveProps:function(e){"activeKey"in e&&this.setState({activeKey:a(e.activeKey)}),"openAnimation"in e&&this.setState({openAnimation:e.openAnimation})},onClickItem:function(e){var t=this;return function(){var n=t.state.activeKey;if(t.props.accordion)n=n[0]===e?[]:[e];else{n=[].concat(o(n));var r=n.indexOf(e),a=r>-1;a?n.splice(r,1):n.push(e)}t.setActiveKey(n)}},getItems:function(){var e=this,t=this.state.activeKey,n=this.props,r=n.prefixCls,o=n.accordion;return i.Children.map(this.props.children,function(n,a){var i=n.key||String(a),l=n.props.header,c=!1;c=o?t[0]===i:t.indexOf(i)>-1;var p={key:i,header:l,isActive:c,prefixCls:r,openAnimation:e.state.openAnimation,children:n.props.children,onItemClick:e.onClickItem(i).bind(e)};return s["default"].createElement(u["default"],p)})},setActiveKey:function(e){"activeKey"in this.props||this.setState({activeKey:e}),this.props.onChange(this.props.accordion?e[0]:e)},render:function(){var e=this.props.prefixCls;return s["default"].createElement("div",{className:e},this.getItems())}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(305),s=r(i),l=n(8),u=r(l),c=a["default"].createClass({displayName:"CollapsePanel",propTypes:{children:o.PropTypes.any,openAnimation:o.PropTypes.object,prefixCls:o.PropTypes.string,header:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.node]),isActive:o.PropTypes.bool,onItemClick:o.PropTypes.func},getDefaultProps:function(){return{isActive:!1,onItemClick:function(){}}},handleItemClick:function(){this.props.onItemClick()},render:function(){var e=this.props,t=e.prefixCls,n=e.header,r=e.children,o=e.isActive,i=t+"-header";return a["default"].createElement("div",{className:t+"-item"},a["default"].createElement("div",{className:i,onClick:this.handleItemClick,role:"tab","aria-expanded":o},a["default"].createElement("i",{className:"arrow"}),n),a["default"].createElement(u["default"],{showProp:"isActive",exclusive:!0,component:"",animation:this.props.openAnimation},a["default"].createElement(s["default"],{prefixCls:t,isActive:o},r)))}});t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"PanelContent",propTypes:{prefixCls:a.PropTypes.string,isActive:a.PropTypes.bool,children:a.PropTypes.any},shouldComponentUpdate:function(e){return this.props.isActive||e.isActive},render:function(){var e;if(this._isActived=this._isActived||this.props.isActive,!this._isActived)return null;var t=this.props,n=t.prefixCls,r=t.isActive,a=t.children,s=(0,l["default"])((e={},o(e,n+"-content",!0),o(e,n+"-content-active",r),o(e,n+"-content-inactive",!r),e));return i["default"].createElement("div",{className:s,role:"tabpanel"},i["default"].createElement("div",{className:n+"-content-box"},a))}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(303),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n,r){var o=void 0;return(0,s["default"])(e,n,{start:function(){t?(o=e.offsetHeight,e.style.height=0):e.style.height=e.offsetHeight+"px"},active:function(){e.style.height=(t?o:0)+"px"},end:function(){e.style.height="",r()}})}function a(e){return{enter:function(t,n){return o(t,!0,e+"-anim",n)},leave:function(t,n){return o(t,!1,e+"-anim",n)}}}Object.defineProperty(t,"__esModule",{value:!0});var i=n(39),s=r(i);t["default"]=a,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t){var n=e["page"+(t?"Y":"X")+"Offset"],r="scroll"+(t?"Top":"Left");if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function i(e,t){var n=e.style;["Webkit","Moz","Ms","ms"].forEach(function(e){n[e+"TransformOrigin"]=t}),n.transformOrigin=t}function s(e){var t=e.getBoundingClientRect(),n={left:t.left,top:t.top},r=e.ownerDocument,o=r.defaultView||r.parentWindow;return n.left+=a(o),n.top+=a(o,1),n}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),c=r(u),p=n(4),f=r(p),d=n(24),h=r(d),y=n(8),v=r(y),m=n(310),g=r(m),b=0,P=0,O={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"},C=c["default"].createClass({displayName:"Dialog",propTypes:{onAfterClose:u.PropTypes.func,onClose:u.PropTypes.func,closable:u.PropTypes.bool,maskClosable:u.PropTypes.bool,visible:u.PropTypes.bool,mousePosition:u.PropTypes.object,wrapStyle:u.PropTypes.object,prefixCls:u.PropTypes.string,wrapClassName:u.PropTypes.string},getDefaultProps:function(){return{onAfterClose:o,onClose:o}},componentWillMount:function(){this.titleId="rcDialogTitle"+b++},componentDidMount:function(){this.componentDidUpdate({})},componentDidUpdate:function(e){var t=this.props,n=this.props.mousePosition;if(t.visible){if(!e.visible){this.lastOutSideFocusNode=document.activeElement,this.addScrollingEffect(),this.refs.wrap.focus();var r=f["default"].findDOMNode(this.refs.dialog);if(n){var o=s(r);i(r,n.x-o.left+"px "+(n.y-o.top)+"px")}else i(r,"")}}else if(e.visible&&t.mask&&this.lastOutSideFocusNode){try{this.lastOutSideFocusNode.focus()}catch(a){this.lastOutSideFocusNode=null}this.lastOutSideFocusNode=null}},onAnimateLeave:function(){this.refs.wrap&&(this.refs.wrap.style.display="none"),this.removeScrollingEffect(),this.props.onAfterClose()},onMaskClick:function(e){e.target===e.currentTarget&&this.props.closable&&this.props.maskClosable&&this.close(e)},onKeyDown:function(e){var t=this.props;if(t.closable&&t.keyboard&&e.keyCode===h["default"].ESC&&this.close(e),t.visible&&e.keyCode===h["default"].TAB){var n=document.activeElement,r=this.refs.wrap,o=this.refs.sentinel;e.shiftKey?n===r&&o.focus():n===this.refs.sentinel&&r.focus()}},getDialogElement:function(){var e=this.props,t=e.closable,n=e.prefixCls,r={};void 0!==e.width&&(r.width=e.width),void 0!==e.height&&(r.height=e.height);var o=void 0;e.footer&&(o=c["default"].createElement("div",{className:n+"-footer",ref:"footer"},e.footer));var a=void 0;e.title&&(a=c["default"].createElement("div",{className:n+"-header",ref:"header"},c["default"].createElement("div",{className:n+"-title",id:this.titleId},e.title)));var i=void 0;t&&(i=c["default"].createElement("button",{onClick:this.close,"aria-label":"Close",className:n+"-close"},c["default"].createElement("span",{className:n+"-close-x"})));var s=l({},e.style,r),u=this.getTransitionName(),p=c["default"].createElement(g["default"],{role:"document",ref:"dialog",style:s,className:n+" "+(e.className||""),visible:e.visible},c["default"].createElement("div",{className:n+"-content"},i,a,c["default"].createElement("div",{className:n+"-body",style:e.bodyStyle,ref:"body"},e.children),o),c["default"].createElement("div",{tabIndex:"0",ref:"sentinel",style:{width:0,height:0,overflow:"hidden"}},"sentinel"));return c["default"].createElement(v["default"],{key:"dialog",showProp:"visible",onLeave:this.onAnimateLeave,transitionName:u,component:"",transitionAppear:!0},p)},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getWrapStyle:function(){return l({},this.getZIndexStyle(),this.props.wrapStyle)},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=c["default"].createElement(g["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=c["default"].createElement(v["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName,n=e.animation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getElement:function(e){return this.refs[e]},setScrollbar:function(){this.bodyIsOverflowing&&this.scrollbarWidth&&(document.body.style.paddingRight=this.scrollbarWidth+"px")},addScrollingEffect:function(){P++,1===P&&(this.checkScrollbar(),this.setScrollbar(),document.body.style.overflow="hidden")},removeScrollingEffect:function(){P--,0===P&&(document.body.style.overflow="",this.resetScrollbar())},close:function(e){this.props.onClose(e)},checkScrollbar:function(){var e=window.innerWidth;if(!e){var t=document.documentElement.getBoundingClientRect();e=t.right-Math.abs(t.left)}this.bodyIsOverflowing=document.body.clientWidth<e,this.bodyIsOverflowing&&(this.scrollbarWidth=this.measureScrollbar())},resetScrollbar:function(){document.body.style.paddingRight=""},measureScrollbar:function(){if(void 0!==this.scrollbarWidth)return this.scrollbarWidth;var e=document.createElement("div");for(var t in O)O.hasOwnProperty(t)&&(e.style[t]=O[t]);document.body.appendChild(e);var n=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),this.scrollbarWidth=n,n},adjustDialog:function(){if(this.refs.wrap&&this.scrollbarWidth){var e=this.refs.wrap.scrollHeight>document.documentElement.clientHeight;this.refs.wrap.style.paddingLeft=(!this.bodyIsOverflowing&&e?this.scrollbarWidth:"")+"px",this.refs.wrap.style.paddingRight=(this.bodyIsOverflowing&&!e?this.scrollbarWidth:"")+"px"}},resetAdjustments:function(){this.refs.wrap&&(this.refs.wrap.style.paddingLeft=this.refs.wrap.style.paddingLeft="")},render:function(){var e=this.props,t=e.prefixCls,n=this.getWrapStyle();return e.visible&&(n.display=null),c["default"].createElement("div",null,this.getMaskElement(),c["default"].createElement("div",{tabIndex:"-1",onKeyDown:this.onKeyDown,className:t+"-wrap "+(e.wrapClassName||""),ref:"wrap",onClick:this.onMaskClick,role:"dialog","aria-labelledby":e.title?this.titleId:null,style:n},this.getDialogElement()))}});t["default"]=C,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){}function l(e,t){var n={};return t.forEach(function(t){void 0!==e[t]&&(n[t]=e[t])}),n}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),p=n(1),f=r(p),d=n(4),h=r(d),y=n(308),v=r(y),m=function(e){function t(e){o(this,t);var n=a(this,Object.getPrototypeOf(t).call(this,e));return n.state={visible:e.visible},["onClose","cleanDialogContainer"].forEach(function(e){n[e]=n[e].bind(n)}),n}return i(t,e),c(t,[{key:"componentDidMount",value:function(){this.componentDidUpdate()}},{key:"componentWillReceiveProps",value:function(e){"visible"in e&&this.setState({visible:e.visible})}},{key:"shouldComponentUpdate",value:function(e,t){return!(!this.state.visible&&!t.visible)}},{key:"componentDidUpdate",value:function(){this.dialogRendered&&(this.dialogInstance=h["default"].unstable_renderSubtreeIntoContainer(this,this.getDialogElement(),this.getDialogContainer()))}},{key:"componentWillUnmount",value:function(){this.dialogContainer&&(this.state.visible?h["default"].unstable_renderSubtreeIntoContainer(this,this.getDialogElement({onAfterClose:this.cleanDialogContainer,onClose:s,visible:!1}),this.dialogContainer):this.cleanDialogContainer())}},{key:"onClose",value:function(e){this.props.onClose(e)}},{key:"getDialogContainer",value:function(){return this.dialogContainer||(this.dialogContainer=document.createElement("div"),document.body.appendChild(this.dialogContainer)),this.dialogContainer}},{key:"getDialogElement",value:function(e){var t=this.props,n=l(t,["className","closable","maskClosable","title","footer","mask","keyboard","animation","transitionName","maskAnimation","maskTransitionName","mousePosition","prefixCls","style","width","wrapStyle","height","zIndex","bodyStyle","wrapClassName"]);return n=u({},n,{onClose:this.onClose,visible:this.state.visible},e),f["default"].createElement(v["default"],u({},n,{key:"dialog"}),t.children)}},{key:"getElement",value:function(e){return this.dialogInstance.getElement(e)}},{key:"cleanDialogContainer",value:function(){this.dialogContainer&&(h["default"].unmountComponentAtNode(this.dialogContainer),document.body.removeChild(this.dialogContainer),this.dialogContainer=null)}},{key:"render",value:function(){return this.dialogRendered=this.dialogRendered||this.state.visible,null}}]),t}(f["default"].Component);m.defaultProps={className:"",mask:!0,keyboard:!0,closable:!0,maskClosable:!0,prefixCls:"rc-dialog",onClose:s},m.propTypes={className:p.PropTypes.string,keyboard:p.PropTypes.bool,wrapStyle:p.PropTypes.object,style:p.PropTypes.object,mask:p.PropTypes.bool,closable:p.PropTypes.bool,maskClosable:p.PropTypes.bool,prefixCls:p.PropTypes.string,visible:p.PropTypes.bool,onClose:p.PropTypes.func},t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=i["default"].createClass({displayName:"LazyRenderBox",propTypes:{className:a.PropTypes.string,visible:a.PropTypes.bool,hiddenClassName:a.PropTypes.string},shouldComponentUpdate:function(e){return e.hiddenClassName||e.visible},render:function(){var e=this.props.className;return this.props.hiddenClassName&&!this.props.visible&&(e+=" "+this.props.hiddenClassName),i["default"].createElement("div",o({},this.props,{className:e}))}});t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(309)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(4),c=r(u),p=n(14),f=r(p),d=n(314),h=r(d),y=l["default"].createClass({displayName:"Dropdown",propTypes:{minOverlayWidthMatchTrigger:s.PropTypes.bool,onVisibleChange:s.PropTypes.func,prefixCls:s.PropTypes.string,children:s.PropTypes.any,transitionName:s.PropTypes.string,overlayClassName:s.PropTypes.string,animation:s.PropTypes.any,align:s.PropTypes.object,overlayStyle:s.PropTypes.object,placement:s.PropTypes.string,trigger:s.PropTypes.array,showAction:s.PropTypes.array,hideAction:s.PropTypes.array,getPopupContainer:s.PropTypes.func},getDefaultProps:function(){return{minOverlayWidthMatchTrigger:!0,prefixCls:"rc-dropdown",trigger:["hover"],showAction:[],hideAction:[],overlayClassName:"",overlayStyle:{},defaultVisible:!1,onVisibleChange:function(){},placement:"bottomLeft"}},getInitialState:function(){var e=this.props;return"visible"in e?{visible:e.visible}:{visible:e.defaultVisible}},componentWillReceiveProps:function(e){"visible"in e&&this.setState({visible:e.visible})},onClick:function(e){var t=this.props,n=t.overlay.props;"visible"in t||this.setState({visible:!1}),n.onClick&&n.onClick(e)},onVisibleChange:function(e){var t=this.props;"visible"in t||this.setState({visible:e}),t.onVisibleChange(e)},getMenuElement:function(){var e=this.props;return l["default"].cloneElement(e.overlay,{prefixCls:e.prefixCls+"-menu",onClick:this.onClick})},getPopupDomNode:function(){return this.refs.trigger.getPopupDomNode()},afterVisibleChange:function(e){if(e&&this.props.minOverlayWidthMatchTrigger){var t=this.getPopupDomNode(),n=c["default"].findDOMNode(this);n.offsetWidth>t.offsetWidth&&(t.style.width=n.offsetWidth+"px")}},render:function(){var e,t=this.props,n=t.prefixCls,r=t.children,s=t.transitionName,u=t.animation,c=t.align,p=t.placement,d=t.getPopupContainer,y=t.showAction,v=t.hideAction,m=t.overlayClassName,g=t.overlayStyle,b=t.trigger,P=a(t,["prefixCls","children","transitionName","animation","align","placement","getPopupContainer","showAction","hideAction","overlayClassName","overlayStyle","trigger"]);return l["default"].createElement(f["default"],i({},P,(e={prefixCls:n,ref:"trigger",popupClassName:m,popupStyle:g,builtinPlacements:h["default"],action:b,showAction:y},o(e,"showAction",y),o(e,"hideAction",v),o(e,"popupPlacement",p),o(e,"popupAlign",c),o(e,"popupTransitionName",s),o(e,"popupAnimation",u),o(e,"popupVisible",this.state.visible),o(e,"afterPopupVisibleChange",this.afterVisibleChange),o(e,"popup",this.getMenuElement()),o(e,"onPopupVisibleChange",this.onVisibleChange),o(e,"getPopupContainer",d),e)),r)}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(312),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o=t.placements={topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:r}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n=window.getComputedStyle,r=n?n(e):e.currentStyle;if(r)return r[t.replace(/-(\w)/gi,function(e,t){return t.toUpperCase()})]}function a(e){for(var t=e,n=void 0;"body"!==(n=t.nodeName.toLowerCase());){var r=o(t,"overflowY");if("auto"===r||"scroll"===r)return t;t=t.parentNode}return"body"===n?t.ownerDocument:t}function i(e){return(0,u["default"])(s({},e),[v])}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(100),u=r(l),c=n(316),p=n(101),f=n(4),d=r(f),h=n(40),y=r(h),v={getForm:function(){return s({},c.mixin.getForm.call(this),{validateFieldsAndScroll:this.validateFieldsAndScroll})},validateFieldsAndScroll:function(e,t,n){var r=this,o=(0,p.getParams)(e,t,n),i=o.names,l=o.callback,u=o.options,c=function(e,t){if(e){var n=void 0,o=void 0;for(var i in e)if(e.hasOwnProperty(i)){var c=r.getFieldInstance(i);if(c){var p=d["default"].findDOMNode(c),f=p.getBoundingClientRect().top;(void 0===o||o>f)&&(o=f,n=p)}}if(n){var h=u.container||a(n);(0,y["default"])(n,h,s({onlyScrollIfNeeded:!0},u.scroll))}}"function"==typeof l&&l(e,t)};return this.validateFields(i,u,c)}};t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,i["default"])(e,[s])}Object.defineProperty(t,"__esModule",{value:!0}),t.mixin=void 0;var a=n(100),i=r(a),s=t.mixin={getForm:function(){return{getFieldsValue:this.getFieldsValue,getFieldValue:this.getFieldValue,getFieldInstance:this.getFieldInstance,setFieldsValue:this.setFieldsValue,setFields:this.setFields,setFieldsInitialValue:this.setFieldsInitialValue,getFieldProps:this.getFieldProps,getFieldError:this.getFieldError,isFieldValidating:this.isFieldValidating,isFieldsValidating:this.isFieldsValidating,isSubmitting:this.isSubmitting,submit:this.submit,validateFields:this.validateFields,resetFields:this.resetFields}}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}function i(e){e.preventDefault()}var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(1),u=r(l),c=n(2),p=r(c),f=u["default"].createClass({displayName:"InputNumber",propTypes:{onChange:u["default"].PropTypes.func,onKeyDown:u["default"].PropTypes.func,onFocus:u["default"].PropTypes.func,onBlur:u["default"].PropTypes.func,max:u["default"].PropTypes.number,min:u["default"].PropTypes.number,step:u["default"].PropTypes.oneOfType([u["default"].PropTypes.number,u["default"].PropTypes.string]) },getDefaultProps:function(){return{prefixCls:"rc-input-number",max:1/0,min:-(1/0),step:1,style:{},defaultValue:"",onChange:a,onKeyDown:a,onFocus:a,onBlur:a}},getInitialState:function(){var e=void 0,t=this.props;return e="value"in t?t.value:t.defaultValue,e=this.toPrecisionAsStep(e),{inputValue:e,value:e,focused:t.autoFocus}},componentDidMount:function(){this.componentDidUpdate()},componentWillReceiveProps:function(e){if("value"in e){var t=this.toPrecisionAsStep(e.value);this.setState({inputValue:t,value:t})}},componentDidUpdate:function(){this.state.focused&&document.activeElement!==this.refs.input&&this.refs.input.focus()},onChange:function(e){this.setInputValue(e.target.value.trim())},onKeyDown:function(e){var t;38===e.keyCode?this.up(e):40===e.keyCode&&this.down(e);for(var n=arguments.length,r=Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];(t=this.props).onKeyDown.apply(t,[e].concat(r))},onFocus:function(){var e;this.setState({focused:!0}),(e=this.props).onFocus.apply(e,arguments)},onBlur:function(e){var t;this.setState({focused:!1});var n=this.getCurrentValidValue(e.target.value.trim());this.setValue(n);for(var r=arguments.length,o=Array(r>1?r-1:0),a=1;a<r;a++)o[a-1]=arguments[a];(t=this.props).onBlur.apply(t,[e].concat(o))},onStepMouseDown:function(e){e.preventDefault();var t=this.getCurrentValidValue(this.state.inputValue);this.setState({value:t})},getCurrentValidValue:function(e){var t=e,n=this.props;return""===t?t="":isNaN(t)?t=this.state.value:(t=Number(t),t<n.min&&(t=n.min),t>n.max&&(t=n.max)),this.toPrecisionAsStep(t)},setValue:function(e){"value"in this.props||this.setState({value:e,inputValue:e}),this.props.onChange(isNaN(e)||""===e?"":e)},setInputValue:function(e){this.setState({inputValue:e})},getPrecision:function(){var e=this.props,t=e.step.toString();if(t.indexOf("e-")>=0)return parseInt(t.slice(t.indexOf("e-")+1),10);var n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n},getPrecisionFactor:function(){var e=this.getPrecision();return Math.pow(10,e)},toPrecisionAsStep:function(e){if(isNaN(e)||""===e)return e;var t=this.getPrecision();return Number(Number(e).toFixed(Math.abs(t)))},upStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),a=void 0;return a="number"==typeof e?(o*e+o*n)/o:r===-(1/0)?n:r,this.toPrecisionAsStep(a)},downStep:function(e){var t=this.props,n=t.step,r=t.min,o=this.getPrecisionFactor(),a=void 0;return a="number"==typeof e?(o*e-o*n)/o:r===-(1/0)?-n:r,this.toPrecisionAsStep(a)},step:function(e,t){t&&t.preventDefault();var n=this.props;if(!n.disabled){var r=this.state.value;if(!isNaN(r)){var o=this[e+"Step"](r);o>n.max||o<n.min||(this.setValue(o),this.setState({focused:!0}))}}},down:function(e){this.step("down",e)},up:function(e){this.step("up",e)},focus:function(){this.refs.input.focus()},render:function(){var e,t=s({},this.props);delete t.defaultValue;var n=t.prefixCls,r=(0,p["default"])((e={},o(e,n,!0),o(e,t.className,!!t.className),o(e,n+"-disabled",t.disabled),o(e,n+"-focused",this.state.focused),e)),l="",c="",f=this.state.value;if(isNaN(f))l=n+"-handler-up-disabled",c=n+"-handler-down-disabled";else{var d=Number(f);d>=t.max&&(l=n+"-handler-up-disabled"),d<=t.min&&(c=n+"-handler-down-disabled")}var h=void 0;return h=this.state.focused?this.state.inputValue:this.state.value,u["default"].createElement("div",{className:r,style:t.style},u["default"].createElement("div",{className:n+"-handler-wrap"},u["default"].createElement("a",{unselectable:"unselectable",ref:"up",onClick:l?a:this.up,onMouseDown:this.onStepMouseDown,className:n+"-handler "+n+"-handler-up "+l},u["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-up-inner",onClick:i})),u["default"].createElement("a",{unselectable:"unselectable",ref:"down",onMouseDown:this.onStepMouseDown,onClick:c?a:this.down,className:n+"-handler "+n+"-handler-down "+c},u["default"].createElement("span",{unselectable:"unselectable",className:n+"-handler-down-inner",onClick:i}))),u["default"].createElement("div",{className:n+"-input-wrap"},u["default"].createElement("input",s({},t,{style:null,className:n+"-input",autoComplete:"off",onFocus:this.onFocus,onBlur:this.onBlur,onKeyDown:this.onKeyDown,autoFocus:t.autoFocus,readOnly:t.readOnly,disabled:t.disabled,max:t.max,min:t.min,name:t.name,onChange:this.onChange,ref:"input",value:h}))))}});e.exports=f},function(e,t,n){"use strict";e.exports=n(317)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(10),s=r(i),l=a["default"].createClass({displayName:"DOMWrap",propTypes:{tag:o.PropTypes.string},getDefaultProps:function(){return{tag:"div"}},render:function(){var e=(0,s["default"])({},this.props);e.visible||(e.className=e.className||"",e.className+=" "+e.hiddenClassName);var t=e.tag;return a["default"].createElement(t,e)}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=i["default"].createClass({displayName:"Divider",getDefaultProps:function(){return{disabled:!0}},render:function(){var e=this.props,t=e.className||"",n=e.rootPrefixCls;return t+=" "+(n+"-item-divider"),i["default"].createElement("li",o({},e,{className:t}))}});t["default"]=s,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(102),s=r(i),l=n(10),u=r(l),c=n(22),p=a["default"].createClass({displayName:"Menu",propTypes:{openSubMenuOnMouseEnter:o.PropTypes.bool,closeSubMenuOnMouseLeave:o.PropTypes.bool,selectedKeys:o.PropTypes.arrayOf(o.PropTypes.string),defaultSelectedKeys:o.PropTypes.arrayOf(o.PropTypes.string),defaultOpenKeys:o.PropTypes.arrayOf(o.PropTypes.string),openKeys:o.PropTypes.arrayOf(o.PropTypes.string),mode:o.PropTypes.string,onClick:o.PropTypes.func,onSelect:o.PropTypes.func,onDeselect:o.PropTypes.func,onDestroy:o.PropTypes.func,openTransitionName:o.PropTypes.string,openAnimation:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.object]),level:o.PropTypes.number,eventKey:o.PropTypes.string,selectable:o.PropTypes.bool,children:o.PropTypes.any},mixins:[s["default"]],getDefaultProps:function(){return{openSubMenuOnMouseEnter:!0,closeSubMenuOnMouseLeave:!0,selectable:!0,onClick:c.noop,onSelect:c.noop,onOpen:c.noop,onClose:c.noop,onDeselect:c.noop,defaultSelectedKeys:[],defaultOpenKeys:[]}},getInitialState:function(){var e=this.props,t=e.defaultSelectedKeys,n=e.defaultOpenKeys;return"selectedKeys"in e&&(t=e.selectedKeys||[]),"openKeys"in e&&(n=e.openKeys||[]),{selectedKeys:t,openKeys:n}},componentWillReceiveProps:function(e){var t={};"selectedKeys"in e&&(t.selectedKeys=e.selectedKeys),"openKeys"in e&&(t.openKeys=e.openKeys),this.setState(t)},onDestroy:function(e){var t=this.state,n=this.props,r=t.selectedKeys,o=t.openKeys,a=r.indexOf(e);"selectedKeys"in n||a===-1||r.splice(a,1),a=o.indexOf(e),"openKeys"in n||a===-1||o.splice(a,1)},onItemHover:function(e){var t=this,n=e.item;"inline"!==this.props.mode&&!this.props.closeSubMenuOnMouseLeave&&n.isSubMenu&&!function(){var r=t.state.activeKey,o=t.getFlatInstanceArray().filter(function(e){return e&&e.props.eventKey===r})[0];o&&o.props.open&&t.onOpenChange({key:n.props.eventKey,item:e.item,open:!0})}(),this.onCommonItemHover(e)},onSelect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys,r=e.key;n=t.multiple?n.concat([r]):[r],"selectedKeys"in t||this.setState({selectedKeys:n}),t.onSelect((0,u["default"])({},e,{selectedKeys:n}))}},onClick:function(e){var t=this.props;t.onClick(e)},onOpenChange:function(e){var t=this.props,n=this.state.openKeys,r=!0;if(e.open)r=n.indexOf(e.key)===-1,r&&(n=n.concat(e.key));else{var o=n.indexOf(e.key);r=o!==-1,r&&(n=n.concat(),n.splice(o,1))}if(r){this.state.openKeys=n,"openKeys"in this.props||this.setState({openKeys:n});var a=(0,u["default"])({openKeys:n},e);e.open?t.onOpen(a):t.onClose(a)}},onDeselect:function(e){var t=this.props;if(t.selectable){var n=this.state.selectedKeys.concat(),r=e.key,o=n.indexOf(r);o!==-1&&n.splice(o,1),"selectedKeys"in t||this.setState({selectedKeys:n}),t.onDeselect((0,u["default"])({},e,{selectedKeys:n}))}},getOpenTransitionName:function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n||(t=e.prefixCls+"-open-"+n),t},isInlineMode:function(){return"inline"===this.props.mode},lastOpenSubMenu:function(){var e=this,t=[];return this.state.openKeys.length&&(t=this.getFlatInstanceArray().filter(function(t){return t&&e.state.openKeys.indexOf(t.props.eventKey)!==-1})),t[0]},renderMenuItem:function(e,t,n){if(!e)return null;var r=(0,c.getKeyFromChildrenIndex)(e,this.props.eventKey,t),o=this.state,a={openKeys:o.openKeys,open:o.openKeys.indexOf(r)!==-1,selectedKeys:o.selectedKeys,selected:o.selectedKeys.indexOf(r)!==-1,openSubMenuOnMouseEnter:this.props.openSubMenuOnMouseEnter};return this.renderCommonMenuItem(e,t,n,a)},render:function(){var e=(0,u["default"])({},this.props);return e.className+=" "+e.prefixCls+"-root",this.renderRoot(e)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(11),l=n(2),u=r(l),c=n(22),p=i["default"].createClass({displayName:"MenuItem",propTypes:{rootPrefixCls:a.PropTypes.string,eventKey:a.PropTypes.string,active:a.PropTypes.bool,selected:a.PropTypes.bool,disabled:a.PropTypes.bool,title:a.PropTypes.string,onSelect:a.PropTypes.func,onClick:a.PropTypes.func,onDeselect:a.PropTypes.func,parentMenu:a.PropTypes.object,onItemHover:a.PropTypes.func,onDestroy:a.PropTypes.func,onMouseEnter:a.PropTypes.func,onMouseLeave:a.PropTypes.func},getDefaultProps:function(){return{onSelect:c.noop,onMouseEnter:c.noop,onMouseLeave:c.noop}},componentWillUnmount:function(){var e=this.props;e.onDestroy&&e.onDestroy(e.eventKey),e.parentMenu.menuItemInstance===this&&this.clearMenuItemMouseLeaveTimer()},onKeyDown:function(e){var t=e.keyCode;if(t===s.KeyCode.ENTER)return this.onClick(e),!0},onMouseLeave:function(e){var t=this,n=this.props,r=n.eventKey,o=n.parentMenu;o.menuItemInstance=this,o.menuItemMouseLeaveFn=function(){t.isMounted()&&n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"})},o.menuItemMouseLeaveTimer=setTimeout(o.menuItemMouseLeaveFn,30),n.onMouseLeave({key:r,domEvent:e})},onMouseEnter:function(e){var t=this.props,n=t.parentMenu;this.clearMenuItemMouseLeaveTimer(n.menuItemInstance!==this),n.subMenuInstance&&n.subMenuInstance.clearSubMenuTimers(!0);var r=t.eventKey;t.onItemHover({key:r,item:this,hover:!0,trigger:"mouseenter"}),t.onMouseEnter({key:r,domEvent:e})},onClick:function(e){var t=this.props,n=t.eventKey,r={key:n,keyPath:[n],item:this,domEvent:e};t.onClick(r),t.multiple?t.selected?t.onDeselect(r):t.onSelect(r):t.selected||t.onSelect(r)},getPrefixCls:function(){return this.props.rootPrefixCls+"-item"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getSelectedClassName:function(){return this.getPrefixCls()+"-selected"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},clearMenuItemMouseLeaveTimer:function(e){var t=this.props,n=t.parentMenu;n.menuItemMouseLeaveTimer&&(clearTimeout(n.menuItemMouseLeaveTimer),n.menuItemMouseLeaveTimer=null,e&&n.menuItemMouseLeaveFn&&n.menuItemMouseLeaveFn(),n.menuItemMouseLeaveFn=null)},render:function(){var e=this.props,t={};t[this.getActiveClassName()]=!e.disabled&&e.active,t[this.getSelectedClassName()]=e.selected,t[this.getDisabledClassName()]=e.disabled,t[this.getPrefixCls()]=!0,t[e.className]=!!e.className;var n=o({},e.attribute,{title:e.title,className:(0,u["default"])(t),role:"menuitem","aria-selected":e.selected,"aria-disabled":e.disabled}),r={};e.disabled||(r={onClick:this.onClick,onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter});var a=o({},e.style);return"inline"===e.mode&&(a.paddingLeft=e.inlineIndent*e.level),i["default"].createElement("li",o({style:a},n,r),e.children)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=a["default"].createClass({displayName:"MenuItemGroup",propTypes:{renderMenuItem:o.PropTypes.func,index:o.PropTypes.number},getDefaultProps:function(){return{disabled:!0}},renderInnerMenuItem:function(e,t){var n=this.props.renderMenuItem;return n(e,this.props.index,t)},render:function(){var e=this.props,t=e.className||"",n=e.rootPrefixCls;t+=" "+n+"-item-group";var r=n+"-item-group-title",o=n+"-item-group-list";return a["default"].createElement("li",{className:t},a["default"].createElement("div",{className:r},e.title),a["default"].createElement("ul",{className:o},a["default"].Children.map(e.children,this.renderInnerMenuItem)))}});i.isMenuItemGroup=!0,t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(326),s=r(i),l=n(1),u=r(l),c=n(11),p=n(2),f=r(p),d=n(22),h=u["default"].createClass({displayName:"SubMenu",propTypes:{parentMenu:l.PropTypes.object,title:l.PropTypes.node,onClick:l.PropTypes.func,onOpenChange:l.PropTypes.func,rootPrefixCls:l.PropTypes.string,eventKey:l.PropTypes.string,multiple:l.PropTypes.bool,active:l.PropTypes.bool,open:l.PropTypes.bool,onSelect:l.PropTypes.func,closeSubMenuOnMouseLeave:l.PropTypes.bool,openSubMenuOnMouseEnter:l.PropTypes.bool,onDeselect:l.PropTypes.func,onDestroy:l.PropTypes.func,onItemHover:l.PropTypes.func,onMouseEnter:l.PropTypes.func,onMouseLeave:l.PropTypes.func,onTitleMouseEnter:l.PropTypes.func,onTitleMouseLeave:l.PropTypes.func,onTitleClick:l.PropTypes.func},mixins:[n(325)],getDefaultProps:function(){return{onMouseEnter:d.noop,onMouseLeave:d.noop,onTitleMouseEnter:d.noop,onTitleMouseLeave:d.noop,onTitleClick:d.noop,title:""}},getInitialState:function(){return this.isSubMenu=1,{defaultActiveFirst:!1}},componentWillUnmount:function(){var e=this.props;e.onDestroy&&e.onDestroy(e.eventKey),e.parentMenu.subMenuInstance===this&&this.clearSubMenuTimers()},onDestroy:function(e){this.props.onDestroy(e)},onKeyDown:function(e){var t=e.keyCode,n=this.menuInstance;if(t===c.KeyCode.ENTER)return this.onTitleClick(e),this.setState({defaultActiveFirst:!0}),!0;if(t===c.KeyCode.RIGHT)return this.props.open?n.onKeyDown(e):(this.triggerOpenChange(!0),this.setState({defaultActiveFirst:!0})),!0;if(t===c.KeyCode.LEFT){var r=void 0;if(!this.props.open)return;return r=n.onKeyDown(e),r||(this.triggerOpenChange(!1),r=!0),r}return!this.props.open||t!==c.KeyCode.UP&&t!==c.KeyCode.DOWN?void 0:n.onKeyDown(e)},onOpenChange:function(e){this.props.onOpenChange(this.addKeyPath(e))},onMouseEnter:function(e){var t=this.props;this.clearSubMenuLeaveTimer(t.parentMenu.subMenuInstance!==this),t.onMouseEnter({key:t.eventKey,domEvent:e})},onTitleMouseEnter:function(e){var t=this.props,n=t.parentMenu;this.clearSubMenuTitleLeaveTimer(n.subMenuInstance!==this),n.menuItemInstance&&n.menuItemInstance.clearMenuItemMouseLeaveTimer(!0),t.onItemHover({key:t.eventKey,item:this,hover:!0,trigger:"mouseenter"}),t.openSubMenuOnMouseEnter&&this.triggerOpenChange(!0),this.setState({defaultActiveFirst:!1}),t.onTitleMouseEnter({key:t.eventKey,domEvent:e})},onTitleMouseLeave:function(e){var t=this,n=this.props,r=n.parentMenu;r.subMenuInstance=this,r.subMenuTitleLeaveFn=function(){var r=n.eventKey;t.isMounted()&&("inline"===n.mode&&n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"}),n.onTitleMouseLeave({key:n.eventKey,domEvent:e}))},r.subMenuTitleLeaveTimer=setTimeout(r.subMenuTitleLeaveFn,100)},onMouseLeave:function(e){var t=this,n=this.props,r=n.parentMenu;r.subMenuInstance=this,r.subMenuLeaveFn=function(){var r=n.eventKey;t.isMounted()&&("inline"!==n.mode&&(n.active&&n.onItemHover({key:r,item:t,hover:!1,trigger:"mouseleave"}),n.open&&n.closeSubMenuOnMouseLeave&&t.triggerOpenChange(!1)),n.onMouseLeave({key:r,domEvent:e}))},r.subMenuLeaveTimer=setTimeout(r.subMenuLeaveFn,100)},onTitleClick:function(e){var t=this.props;t.onTitleClick({key:t.eventKey,domEvent:e}),t.openSubMenuOnMouseEnter||(this.triggerOpenChange(!t.open,"click"),this.setState({defaultActiveFirst:!1}))},onSubMenuClick:function(e){this.props.onClick(this.addKeyPath(e))},onSelect:function(e){this.props.onSelect(e)},onDeselect:function(e){this.props.onDeselect(e)},getPrefixCls:function(){return this.props.rootPrefixCls+"-submenu"},getActiveClassName:function(){return this.getPrefixCls()+"-active"},getDisabledClassName:function(){return this.getPrefixCls()+"-disabled"},getOpenClassName:function(){return this.props.rootPrefixCls+"-submenu-open"},saveMenuInstance:function(e){this.menuInstance=e},addKeyPath:function(e){return a({},e,{keyPath:(e.keyPath||[]).concat(this.props.eventKey)})},triggerOpenChange:function(e,t){var n=this.props.eventKey;this.onOpenChange({key:n,item:this,trigger:t,open:e})},clearSubMenuTimers:function(e){this.clearSubMenuLeaveTimer(e),this.clearSubMenuTitleLeaveTimer(e)},clearSubMenuTitleLeaveTimer:function(e){var t=this.props.parentMenu;t.subMenuTitleLeaveTimer&&(clearTimeout(t.subMenuTitleLeaveTimer),t.subMenuTitleLeaveTimer=null,e&&t.subMenuTitleLeaveFn&&t.subMenuTitleLeaveFn(),t.subMenuTitleLeaveFn=null)},clearSubMenuLeaveTimer:function(e){var t=this.props.parentMenu;t.subMenuLeaveTimer&&(clearTimeout(t.subMenuLeaveTimer),t.subMenuLeaveTimer=null,e&&t.subMenuLeaveFn&&t.subMenuLeaveFn(),t.subMenuLeaveFn=null)},renderChildren:function(e){var t=this.props,n={mode:"horizontal"===t.mode?"vertical":t.mode,visible:t.open,level:t.level+1,inlineIndent:t.inlineIndent,focusable:!1,onClick:this.onSubMenuClick,onSelect:this.onSelect,onDeselect:this.onDeselect,onDestroy:this.onDestroy,selectedKeys:t.selectedKeys,eventKey:t.eventKey+"-menu-",openKeys:t.openKeys,openTransitionName:t.openTransitionName,openAnimation:t.openAnimation,onOpenChange:this.onOpenChange,closeSubMenuOnMouseLeave:t.closeSubMenuOnMouseLeave,defaultActiveFirst:this.state.defaultActiveFirst,multiple:t.multiple,prefixCls:t.rootPrefixCls,id:this._menuId,ref:this.saveMenuInstance};return u["default"].createElement(s["default"],n,e)},render:function(){var e;this.haveOpen=this.haveOpen||this.props.open;var t=this.props,n=this.getPrefixCls(),r=(e={},o(e,t.className,!!t.className),o(e,n+"-"+t.mode,1),e);r[this.getOpenClassName()]=this.props.open,r[this.getActiveClassName()]=t.active,r[this.getDisabledClassName()]=t.disabled,this._menuId=this._menuId||(0,c.guid)(),r[n]=!0,r[n+"-"+t.mode]=1;var i={},s={},l={};t.disabled||(i={onClick:this.onTitleClick},s={onMouseLeave:this.onMouseLeave,onMouseEnter:this.onMouseEnter},l={onMouseEnter:this.onTitleMouseEnter,onMouseLeave:this.onTitleMouseLeave});var p={};return"inline"===t.mode&&(p.paddingLeft=t.inlineIndent*t.level),u["default"].createElement("li",a({className:(0,f["default"])(r)},s),u["default"].createElement("div",a({style:p,className:n+"-title"},l,i,{"aria-open":t.open,"aria-owns":this._menuId,"aria-haspopup":"true"}),t.title),this.renderChildren(t.children))}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(11),a=r(o),i=n(4),s=r(i);t["default"]={componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(){"inline"!==this.props.mode&&(this.props.open?this.bindRootCloseHandlers():this.unbindRootCloseHandlers())},handleDocumentKeyUp:function(e){e.keyCode===o.KeyCode.ESC&&this.props.onItemHover({key:this.props.eventKey,item:this,hover:!1})},handleDocumentClick:function(e){if(!a["default"].Dom.contains(s["default"].findDOMNode(this),e.target)){var t=this.props;t.onItemHover({hover:!1,item:this,key:this.props.eventKey}),this.triggerOpenChange(!1)}},bindRootCloseHandlers:function(){this._onDocumentClickListener||(this._onDocumentClickListener=a["default"].Dom.addEventListener(document,"click",this.handleDocumentClick),this._onDocumentKeyupListener=a["default"].Dom.addEventListener(document,"keyup",this.handleDocumentKeyUp))},unbindRootCloseHandlers:function(){this._onDocumentClickListener&&(this._onDocumentClickListener.remove(),this._onDocumentClickListener=null),this._onDocumentKeyupListener&&(this._onDocumentKeyupListener.remove(),this._onDocumentKeyupListener=null)},componentWillUnmount:function(){this.unbindRootCloseHandlers()}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},i=n(1),s=r(i),l=n(102),u=r(l),c=n(10),p=r(c),f=n(22),d=n(8),h=r(d),y=s["default"].createClass({displayName:"SubPopupMenu",propTypes:{onSelect:i.PropTypes.func,onClick:i.PropTypes.func,onDeselect:i.PropTypes.func,onOpenChange:i.PropTypes.func,onDestroy:i.PropTypes.func,openTransitionName:i.PropTypes.string,openAnimation:i.PropTypes.oneOfType([i.PropTypes.string,i.PropTypes.object]),openKeys:i.PropTypes.arrayOf(i.PropTypes.string),closeSubMenuOnMouseLeave:i.PropTypes.bool,visible:i.PropTypes.bool,children:i.PropTypes.any},mixins:[u["default"]],onDeselect:function(e){this.props.onDeselect(e)},onSelect:function(e){this.props.onSelect(e)},onClick:function(e){this.props.onClick(e)},onOpenChange:function(e){this.props.onOpenChange(e)},onDestroy:function(e){this.props.onDestroy(e)},onItemHover:function(e){this.onCommonItemHover(e)},getOpenTransitionName:function(){return this.props.openTransitionName},renderMenuItem:function(e,t,n){var r=this.props,o=(0,f.getKeyFromChildrenIndex)(e,r.eventKey,t),a={openKeys:r.openKeys,selectedKeys:r.selectedKeys,open:r.openKeys.indexOf(o)!==-1,selected:r.selectedKeys.indexOf(o)!==-1,openSubMenuOnMouseEnter:!0};return this.renderCommonMenuItem(e,t,n,a)},render:function(){var e=this.renderFirst;if(this.renderFirst=1,this.haveOpened=this.haveOpened||this.props.visible,!this.haveOpened)return null;var t=!0;!e&&this.props.visible&&(t=!1);var n=(0,p["default"])({},this.props);n.className+=" "+n.prefixCls+"-sub";var r={};return n.openTransitionName?r.transitionName=n.openTransitionName:"object"===a(n.openAnimation)&&(r.animation=(0,p["default"])({},n.openAnimation),t||delete r.animation.appear),s["default"].createElement(h["default"],o({},r,{showProp:"visible",component:"",transitionAppear:t}),this.renderRoot(n))}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"Notice",propTypes:{duration:a.PropTypes.number,onClose:a.PropTypes.func,children:a.PropTypes.any},getDefaultProps:function(){return{onEnd:function(){},onClose:function(){},duration:1.5,style:{right:"50%"}}},componentDidMount:function(){var e=this;this.props.duration&&(this.closeTimer=setTimeout(function(){e.close()},1e3*this.props.duration))},componentWillUnmount:function(){this.clearCloseTimer()},clearCloseTimer:function(){this.closeTimer&&(clearTimeout(this.closeTimer),this.closeTimer=null)},close:function(){this.clearCloseTimer(),this.props.onClose()},render:function(){var e,t=this.props,n=t.prefixCls+"-notice",r=(e={},o(e,""+n,1),o(e,n+"-closable",t.closable),o(e,t.className,!!t.className),e);return i["default"].createElement("div",{className:(0,l["default"])(r),style:t.style},i["default"].createElement("div",{className:n+"-content"},t.children),t.closable?i["default"].createElement("a",{tabIndex:"0",onClick:this.close,className:n+"-close"},i["default"].createElement("span",{className:n+"-close-x"})):null)}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){return"rcNotification_"+b+"_"+g++}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(4),c=r(u),p=n(8),f=r(p),d=n(11),h=n(2),y=r(h),v=n(327),m=r(v),g=0,b=Date.now(),P=l["default"].createClass({displayName:"Notification",propTypes:{prefixCls:s.PropTypes.string,transitionName:s.PropTypes.string,animation:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.object]),style:s.PropTypes.object},getDefaultProps:function(){return{prefixCls:"rc-notification",animation:"fade",style:{top:65,left:"50%"}}},getInitialState:function(){return{notices:[]}},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},add:function(e){var t=e.key=e.key||a();this.setState(function(n){var r=n.notices;if(!r.filter(function(e){return e.key===t}).length)return{notices:r.concat(e)}})},remove:function(e){this.setState(function(t){return{notices:t.notices.filter(function(t){return t.key!==e})}})},render:function(){var e,t=this,n=this.props,r=this.state.notices.map(function(e){var r=(0,d.createChainedFunction)(t.remove.bind(t,e.key),e.onClose);return l["default"].createElement(m["default"],i({prefixCls:n.prefixCls},e,{onClose:r}),e.content)}),a=(e={},o(e,n.prefixCls,1),o(e,n.className,!!n.className),e);return l["default"].createElement("div",{className:(0,y["default"])(a),style:n.style},l["default"].createElement(f["default"],{transitionName:this.getTransitionName()},r))}});P.newInstance=function(e){var t=e||{},n=document.createElement("div");document.body.appendChild(n);var r=c["default"].render(l["default"].createElement(P,t),n);return{notice:function(e){r.add(e)},removeNotice:function(e){r.remove(e)},component:r,destroy:function(){c["default"].unmountComponentAtNode(n),document.body.removeChild(n)}}},t["default"]=P,e.exports=t["default"]},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},s=n(1),l=n(104),u=function(e){function t(e){var n=this;r(this,t),i(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={current:e.current,_current:e.current},["_handleChange","_changeSize","_go","_buildOptionText"].forEach(function(e){return n[e]=n[e].bind(n)})}return o(t,e),a(t,[{key:"_buildOptionText",value:function(e){return e+" "+this.props.locale.items_per_page}},{key:"_changeSize",value:function(e){this.props.changeSize(Number(e))}},{key:"_handleChange",value:function(e){var t=e.target.value;this.setState({_current:t})}},{key:"_go",value:function(e){var t=e.target.value;if(""!==t){var n=Number(this.state._current);if(isNaN(n)&&(n=this.state.current),e.keyCode===l.ENTER){var r=this.props.quickGo(n);this.setState({_current:r,current:r})}}}},{key:"render",value:function(){var e=this,t=this.props,n=this.state,r=t.locale,o=t.rootPrefixCls+"-options",a=t.changeSize,i=t.quickGo,l=t.buildOptionText||this._buildOptionText,u=t.selectComponentClass,c=null,p=null;return a||i?(a&&u&&!function(){var n=u.Option,r=t.pageSize||t.pageSizeOptions[0],a=t.pageSizeOptions.map(function(e,t){return s.createElement(n,{key:t,value:e},l(e))});c=s.createElement(u,{prefixCls:t.selectPrefixCls,showSearch:!1,className:o+"-size-changer",optionLabelProp:"children",dropdownMatchSelectWidth:!1,value:r+"",onChange:e._changeSize},a)}(),i&&(p=s.createElement("div",{className:o+"-quick-jumper"},r.jump_to,s.createElement("input",{type:"text",value:n._current,onChange:this._handleChange.bind(this),onKeyUp:this._go.bind(this)}),r.page)),s.createElement("div",{className:""+o},c,p)):null}}]),t}(s.Component);u.propTypes={changeSize:s.PropTypes.func,quickGo:s.PropTypes.func,selectComponentClass:s.PropTypes.func,current:s.PropTypes.number,pageSizeOptions:s.PropTypes.arrayOf(s.PropTypes.string),pageSize:s.PropTypes.number,buildOptionText:s.PropTypes.func,locale:s.PropTypes.object},u.defaultProps={pageSizeOptions:["10","20","30","40"]},e.exports=u},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var a=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),i=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},s=n(1),l=function(e){function t(){r(this,t),i(Object.getPrototypeOf(t.prototype),"constructor",this).apply(this,arguments)}return o(t,e),a(t,[{key:"render",value:function(){var e=this.props,t=e.locale,n=e.rootPrefixCls+"-item",r=n+" "+n+"-"+e.page;e.active&&(r=r+" "+n+"-active");var o=void 0;return o=1===e.page?t.first_page:e.last?t.last_page+": "+e.page:e.page,s.createElement("li",{title:o,className:r,onClick:e.onClick},s.createElement("a",null,e.page))}}]),t}(s.Component);l.propTypes={page:s.PropTypes.number,active:s.PropTypes.bool,last:s.PropTypes.bool,locale:s.PropTypes.object},e.exports=l},function(e,t,n){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0, configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function a(){}var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},l=n(1),u=n(330),c=n(329),p=n(104),f=n(105),d=function(e){function t(e){var n=this;r(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e);var o=e.onChange!==a,i="current"in e;i&&!o&&console.warn("Warning: You provided a `current` prop to a Pagination component without an `onChange` handler. This will render a read-only component.");var l=e.defaultCurrent;"current"in e&&(l=e.current);var u=e.defaultPageSize;"pageSize"in e&&(u=e.pageSize),this.state={current:l,_current:l,pageSize:u},["render","_handleChange","_handleKeyUp","_handleKeyDown","_changePageSize","_isValid","_prev","_next","_hasPrev","_hasNext","_jumpPrev","_jumpNext"].forEach(function(e){return n[e]=n[e].bind(n)})}return o(t,e),i(t,[{key:"componentWillReceiveProps",value:function(e){if("current"in e&&this.setState({current:e.current,_current:e.current}),"pageSize"in e){var t={},n=this.state.current,r=this._calcPage(e.pageSize);n=n>r?r:n,"current"in e||(t.current=n,t._current=n),t.pageSize=e.pageSize,this.setState(t)}}},{key:"_calcPage",value:function(e){var t=e;return"undefined"==typeof t&&(t=this.state.pageSize),Math.floor((this.props.total-1)/t)+1}},{key:"_isValid",value:function(e){return"number"==typeof e&&e>=1&&e!==this.state.current}},{key:"_handleKeyDown",value:function(e){e.keyCode!==p.ARROW_UP&&e.keyCode!==p.ARROW_DOWN||e.preventDefault()}},{key:"_handleKeyUp",value:function(e){var t=e.target.value,n=void 0;n=""===t?t:isNaN(Number(t))?this.state._current:Number(t),this.setState({_current:n}),e.keyCode===p.ENTER?this._handleChange(n):e.keyCode===p.ARROW_UP?this._handleChange(n-1):e.keyCode===p.ARROW_DOWN&&this._handleChange(n+1)}},{key:"_changePageSize",value:function(e){var t=this.state.current,n=this._calcPage(e);t=t>n?n:t,"number"==typeof e&&("pageSize"in this.props||this.setState({pageSize:e}),"current"in this.props||this.setState({current:t,_current:t})),this.props.onShowSizeChange(t,e)}},{key:"_handleChange",value:function(e){var t=e;return this._isValid(t)?(t>this._calcPage()&&(t=this._calcPage()),"current"in this.props||this.setState({current:t,_current:t}),this.props.onChange(t),t):this.state.current}},{key:"_prev",value:function(){this._hasPrev()&&this._handleChange(this.state.current-1)}},{key:"_next",value:function(){this._hasNext()&&this._handleChange(this.state.current+1)}},{key:"_jumpPrev",value:function(){this._handleChange(Math.max(1,this.state.current-5))}},{key:"_jumpNext",value:function(){this._handleChange(Math.min(this._calcPage(),this.state.current+5))}},{key:"_hasPrev",value:function(){return this.state.current>1}},{key:"_hasNext",value:function(){return this.state.current<this._calcPage()}},{key:"render",value:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=this._calcPage(),o=[],a=null,i=null,s=null,p=null;if(e.simple)return l.createElement("ul",{className:n+" "+n+"-simple "+e.className},l.createElement("li",{title:t.prev_page,onClick:this._prev,className:(this._hasPrev()?"":n+"-disabled ")+(n+"-prev")},l.createElement("a",null)),l.createElement("div",{title:this.state.current+"/"+r,className:n+"-simple-pager"},l.createElement("input",{type:"text",value:this.state._current,onKeyDown:this._handleKeyDown,onKeyUp:this._handleKeyUp,onChange:this._handleKeyUp}),l.createElement("span",{className:n+"-slash"},"\uff0f"),r),l.createElement("li",{title:t.next_page,onClick:this._next,className:(this._hasNext()?"":n+"-disabled ")+(n+"-next")},l.createElement("a",null)));if(r<=9)for(var f=1;f<=r;f++){var d=this.state.current===f;o.push(l.createElement(u,{locale:t,rootPrefixCls:n,onClick:this._handleChange.bind(this,f),key:f,page:f,active:d}))}else{a=l.createElement("li",{title:t.prev_5,key:"prev",onClick:this._jumpPrev,className:n+"-jump-prev"},l.createElement("a",null)),i=l.createElement("li",{title:t.next_5,key:"next",onClick:this._jumpNext,className:n+"-jump-next"},l.createElement("a",null)),p=l.createElement(u,{locale:e.locale,last:!0,rootPrefixCls:n,onClick:this._handleChange.bind(this,r),key:r,page:r,active:!1}),s=l.createElement(u,{locale:e.locale,rootPrefixCls:n,onClick:this._handleChange.bind(this,1),key:1,page:1,active:!1});var h=this.state.current,y=Math.max(1,h-2),v=Math.min(h+2,r);h-1<=2&&(v=5),r-h<=2&&(y=r-4);for(var f=y;f<=v;f++){var d=h===f;o.push(l.createElement(u,{locale:e.locale,rootPrefixCls:n,onClick:this._handleChange.bind(this,f),key:f,page:f,active:d}))}h-1>=4&&o.unshift(a),r-h>=4&&o.push(i),1!==y&&o.unshift(s),v!==r&&o.push(p)}var m=null;return e.showTotal&&(m=l.createElement("span",{className:n+"-total-text"},e.showTotal(e.total))),l.createElement("ul",{className:n+" "+e.className,unselectable:"unselectable"},m,l.createElement("li",{title:t.prev_page,onClick:this._prev,className:(this._hasPrev()?"":n+"-disabled ")+(n+"-prev")},l.createElement("a",null)),o,l.createElement("li",{title:t.next_page,onClick:this._next,className:(this._hasNext()?"":n+"-disabled ")+(n+"-next")},l.createElement("a",null)),l.createElement(c,{locale:e.locale,rootPrefixCls:n,selectComponentClass:e.selectComponentClass,selectPrefixCls:e.selectPrefixCls,changeSize:this.props.showSizeChanger?this._changePageSize.bind(this):null,current:this.state.current,pageSize:this.state.pageSize,pageSizeOptions:this.props.pageSizeOptions,quickGo:this.props.showQuickJumper?this._handleChange.bind(this):null}))}}]),t}(l.Component);d.propTypes={current:l.PropTypes.number,defaultCurrent:l.PropTypes.number,total:l.PropTypes.number,pageSize:l.PropTypes.number,defaultPageSize:l.PropTypes.number,onChange:l.PropTypes.func,showSizeChanger:l.PropTypes.bool,onShowSizeChange:l.PropTypes.func,selectComponentClass:l.PropTypes.func,showQuickJumper:l.PropTypes.bool,pageSizeOptions:l.PropTypes.arrayOf(l.PropTypes.string),showTotal:l.PropTypes.func,locale:l.PropTypes.object},d.defaultProps={defaultCurrent:1,total:0,defaultPageSize:10,onChange:a,className:"",selectPrefixCls:"rc-select",prefixCls:"rc-pagination",selectComponentClass:null,showQuickJumper:!1,showSizeChanger:!1,onShowSizeChange:a,locale:f},e.exports=d},function(e,t,n){"use strict";e.exports=n(331)},function(e,t,n){"use strict";var r=n(10),o=n(1),a={strokeWidth:1,strokeColor:"#3FC7FA",trailWidth:1,trailColor:"#D9D9D9"},i=o.createClass({displayName:"Line",render:function(){var e=r({},this.props),t={strokeDasharray:"100px, 100px",strokeDashoffset:100-e.percent+"px",transition:"stroke-dashoffset 0.6s ease 0s, stroke 0.6s linear"};["strokeWidth","strokeColor","trailWidth","trailColor"].forEach(function(t){return"trailWidth"===t&&!e.trailWidth&&e.strokeWidth?void(e.trailWidth=e.strokeWidth):"strokeWidth"===t&&e.strokeWidth&&(!parseFloat(e.strokeWidth)||parseFloat(e.strokeWidth)>100||parseFloat(e.strokeWidth)<0)?void(e[t]=a[t]):void(e[t]||(e[t]=a[t]))});var n=e.strokeWidth,i=n/2,s=100-n/2,l="M "+i+","+i+" L "+s+","+i,u="0 0 100 "+n;return o.createElement("svg",{className:"rc-progress-line",viewBox:u,preserveAspectRatio:"none"},o.createElement("path",{className:"rc-progress-line-trail",d:l,strokeLinecap:"round",stroke:e.trailColor,strokeWidth:e.trailWidth,fillOpacity:"0"}),o.createElement("path",{className:"rc-progress-line-path",d:l,strokeLinecap:"round",stroke:e.strokeColor,strokeWidth:e.strokeWidth,fillOpacity:"0",style:t}))}}),s=o.createClass({displayName:"Circle",render:function(){var e=r({},this.props),t=e.strokeWidth,n=50-t/2,i="M 50,50 m 0,-"+n+"\n a "+n+","+n+" 0 1 1 0,"+2*n+"\n a "+n+","+n+" 0 1 1 0,-"+2*n,s=2*Math.PI*n,l={strokeDasharray:s+"px "+s+"px",strokeDashoffset:(100-e.percent)/100*s+"px",transition:"stroke-dashoffset 0.6s ease 0s, stroke 0.6s ease"};return["strokeWidth","strokeColor","trailWidth","trailColor"].forEach(function(t){return"trailWidth"===t&&!e.trailWidth&&e.strokeWidth?void(e.trailWidth=e.strokeWidth):void(e[t]||(e[t]=a[t]))}),o.createElement("svg",{className:"rc-progress-circle",viewBox:"0 0 100 100"},o.createElement("path",{className:"rc-progress-circle-trail",d:i,stroke:e.trailColor,strokeWidth:e.trailWidth,fillOpacity:"0"}),o.createElement("path",{className:"rc-progress-circle-path",d:i,strokeLinecap:"round",stroke:e.strokeColor,strokeWidth:e.strokeWidth,fillOpacity:"0",style:l}))}});e.exports={Line:i,Circle:s}},function(e,t,n){"use strict";e.exports=n(333)},function(e,t,n){(function(r){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function a(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function l(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):a(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var u=n(1),c=o(u),p=n(4),f=n(338),d=n(336),h=o(d),y={easeInElastic:function(e,t,n){var r=e,o=t>=1?t:1,a=(n||1)/(t<1?t:1),i=a/Math.PI*2*(Math.asin(1/o)||0);return-(o*Math.pow(2,10*(r-=1))*Math.sin((r-i)*a))},easeOutElastic:function(e,t,n){var r=t>=1?t:1,o=(n||1)/(t<1?t:1),a=o/Math.PI*2*(Math.asin(1/r)||0);return r*Math.pow(2,-10*e)*Math.sin((e-a)*o)+1},easeInOutElastic:function(e,t,n){var r=e,o=t>=1?t:1,a=(n||1)/(t<1?t:1),i=a/Math.PI*2*(Math.asin(1/o)||0);return r*=2,r<1?-.5*(o*Math.pow(2,10*(r-=1))*Math.sin((r-i)*a)):o*Math.pow(2,-10*(r-=1))*Math.sin((r-i)*a)*.5+1},easeInBounce:function(e){var t=e,n=1-t;return n<1/2.75?1-7.5625*t*t:t<2/2.75?1-(7.5625*(t-=1.5/2.75)*t+.75):t<2.5/2.75?1-(7.5625*(t-=2.25/2.75)*t+.9375):1-(7.5625*(t-=2.625/2.75)*t+.984375)},easeOutBounce:function(e){var t=e;return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},easeInOutBounce:function(e){var t=e,n=t<.5;return t=n?1-2*t:2*t-1,t=t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375,n?.5*(1-t):.5*t+.5}},v=void 0;"undefined"!=typeof document&&"undefined"!=typeof window?(v=n(418),Object.keys(y).forEach(function(e){v.Easings&&(v.Easings[e]=y[e])})):v=function(){var e=arguments[arguments.length-1];r(function(){return e()})};var m={easeInBack:[.6,-.28,.735,.045],easeOutBack:[.175,.885,.32,1.275],easeInOutBack:[.68,-.55,.265,1.55]},g="ant-queue-anim-placeholder-",b=function(e){function t(){i(this,t);var n=s(this,e.apply(this,arguments));n.keysToEnter=[],n.keysToLeave=[],n.keysAnimating=[],n.placeholderTimeoutIds={};var r=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(n.props));return r.forEach(function(e){e&&e.key&&n.keysToEnter.push(e.key)}),n.originalChildren=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(n.props)),n.state={children:r,childrenShow:{}},["performEnter","performLeave","enterBegin","leaveComplete"].forEach(function(e){return n[e]=n[e].bind(n)}),n}return l(t,e),t.prototype.componentDidMount=function(){this.componentDidUpdate()},t.prototype.componentWillReceiveProps=function(e){var t=this,n=(0,f.toArrayChildren)(e.children),r=this.originalChildren,o=(0,f.mergeChildren)(r,n);this.keysToEnter=[],this.keysToLeave=[],this.keysAnimating=[],this.setState({children:o}),n.forEach(function(e){if(e){var n=e.key,o=(0,f.findChildInChildrenByKey)(r,n);!o&&n&&t.keysToEnter.push(n)}}),r.forEach(function(e){if(e){var r=e.key,o=(0,f.findChildInChildrenByKey)(n,r);!o&&r&&t.keysToLeave.push(r)}})},t.prototype.componentDidUpdate=function(){this.originalChildren=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(this.props));var e=Array.prototype.slice.call(this.keysToEnter),t=Array.prototype.slice.call(this.keysToLeave);0===this.keysAnimating.length&&(this.keysAnimating=e.concat(t)),e.forEach(this.performEnter),t.forEach(this.performLeave)},t.prototype.componentWillUnmount=function(){var e=this;[].concat(this.keysToEnter,this.keysToLeave,this.keysAnimating).forEach(function(t){return e.refs[t]&&v((0,p.findDOMNode)(e.refs[t]),"stop")}),Object.keys(this.placeholderTimeoutIds).forEach(function(t){clearTimeout(e.placeholderTimeoutIds[t])}),this.keysToEnter=[],this.keysToLeave=[],this.keysAnimating=[]},t.prototype.getVelocityConfig=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return this.props.animConfig?f.transformArguments.apply(void 0,[this.props.animConfig].concat(n))[e]:h["default"][f.transformArguments.apply(void 0,[this.props.type].concat(n))[e]]},t.prototype.getVelocityEnterConfig=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return this.getVelocityConfig.apply(this,[0].concat(t))},t.prototype.getVelocityLeaveConfig=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];var r=this.getVelocityConfig.apply(this,[1].concat(t)),o={};return Object.keys(r).forEach(function(e){Array.isArray(r[e])?o[e]=Array.prototype.slice.call(r[e]).reverse():o[e]=r[e]}),o},t.prototype.getVelocityEasing=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return f.transformArguments.apply(void 0,[this.props.ease].concat(t)).map(function(e){if("string"==typeof e)return m[e]||e})},t.prototype.performEnter=function(e,t){var n=(0,f.transformArguments)(this.props.interval,e,t)[0],r=(0,f.transformArguments)(this.props.delay,e,t)[0];this.placeholderTimeoutIds[e]=setTimeout(this.performEnterBegin.bind(this,e,t),n*t+r),this.keysToEnter.indexOf(e)>=0&&this.keysToEnter.splice(this.keysToEnter.indexOf(e),1)},t.prototype.performEnterBegin=function(e,t){var n=this.state.childrenShow;n[e]=!0,this.setState({childrenShow:n},this.realPerformEnter.bind(this,e,t))},t.prototype.realPerformEnter=function(e,t){var n=(0,p.findDOMNode)(this.refs[e]);if(n){var r=(0,f.transformArguments)(this.props.duration,e,t)[0];n.style.visibility="hidden",v(n,"stop"),v(n,this.getVelocityEnterConfig(e,t),{duration:r,easing:this.getVelocityEasing(e,t)[0],visibility:"visible",begin:this.enterBegin.bind(this,e),complete:this.enterComplete.bind(this,e)})}},t.prototype.performLeave=function(e,t){clearTimeout(this.placeholderTimeoutIds[e]),delete this.placeholderTimeoutIds[e];var n=(0,p.findDOMNode)(this.refs[e]);if(n){var r=(0,f.transformArguments)(this.props.interval,e,t)[1],o=(0,f.transformArguments)(this.props.delay,e,t)[1],a=(0,f.transformArguments)(this.props.duration,e,t)[1],i=this.props.leaveReverse?this.keysToLeave.length-t-1:t;v(n,"stop"),v(n,this.getVelocityLeaveConfig(e,t),{delay:r*i+o,duration:a,easing:this.getVelocityEasing(e,t)[1],begin:this.leaveBegin.bind(this),complete:this.leaveComplete.bind(this,e)})}},t.prototype.enterBegin=function(e,t){var n=this;t.forEach(function(e){var t=n.props.animatingClassName;e.className=e.className.replace(t[1],""),e.className.indexOf(t[0])===-1&&(e.className+=" "+t[0])})},t.prototype.enterComplete=function(e,t){var n=this;this.keysAnimating.indexOf(e)>=0&&this.keysAnimating.splice(this.keysAnimating.indexOf(e),1),t.forEach(function(e){e.className=e.className.replace(n.props.animatingClassName[0],"").trim()})},t.prototype.leaveBegin=function(e){var t=this;e.forEach(function(e){var n=t.props.animatingClassName;e.className=e.className.replace(n[0],""),e.className.indexOf(n[1])===-1&&(e.className+=" "+n[1])})},t.prototype.leaveComplete=function(e,t){var n=this;if(!(this.keysAnimating.indexOf(e)<0)){this.keysAnimating.splice(this.keysAnimating.indexOf(e),1);var r=this.state.childrenShow;r[e]=!1,this.keysToLeave.indexOf(e)>=0&&this.keysToLeave.splice(this.keysToLeave.indexOf(e),1);var o=this.keysToLeave.some(function(e){return r[e]});if(!o){var a=(0,f.toArrayChildren)((0,f.getChildrenFromProps)(this.props));this.setState({children:a,childrenShow:r})}t.forEach(function(e){e.className=e.className.replace(n.props.animatingClassName[1],"").trim()})}},t.prototype.render=function(){var e=this,t=(0,f.toArrayChildren)(this.state.children).map(function(t){return t&&t.key?e.state.childrenShow[t.key]?(0,u.cloneElement)(t,{ref:t.key,key:t.key}):(0,u.createElement)("div",{ref:g+t.key,key:g+t.key}):t});return(0,u.createElement)(this.props.component,this.props,t)},t}(c["default"].Component),P=c["default"].PropTypes.oneOfType([c["default"].PropTypes.number,c["default"].PropTypes.array]),O=c["default"].PropTypes.oneOfType([c["default"].PropTypes.string,c["default"].PropTypes.array]),C=c["default"].PropTypes.oneOfType([c["default"].PropTypes.object,c["default"].PropTypes.array]),T=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,c["default"].PropTypes.string]),w=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,O]),x=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,C]),E=c["default"].PropTypes.oneOfType([c["default"].PropTypes.func,P]);b.propTypes={component:T,interval:P,duration:E,delay:E,type:w,animConfig:x,ease:w,leaveReverse:c["default"].PropTypes.bool,animatingClassName:c["default"].PropTypes.array},b.defaultProps={component:"div",interval:100,duration:450,delay:0,type:"right",animConfig:null,ease:"easeOutQuart",leaveReverse:!1,animatingClassName:["queue-anim-entering","queue-anim-leaving"]},t["default"]=b,e.exports=t["default"]}).call(t,n(47).setImmediate)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={left:{opacity:[1,0],translateX:[0,-30]},top:{opacity:[1,0],translateY:[0,-30]},right:{opacity:[1,0],translateX:[0,30]},bottom:{opacity:[1,0],translateY:[0,30]},alpha:{opacity:[1,0]},scale:{opacity:[1,0],scale:[1,0]},scaleBig:{opacity:[1,0],scale:[1,2]},scaleX:{opacity:[1,0],scaleX:[1,0]},scaleY:{opacity:[1,0],scaleY:[1,0]}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(335),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=[];return c["default"].Children.forEach(e,function(e){t.push(e)}),t}function a(e,t){var n=null;return e&&e.forEach(function(e){!n&&e&&e.key===t&&(n=e)}),n}function i(e,t){var n=[],r={},o=[];return e.forEach(function(e){e&&(a(t,e.key)?o.length&&(r[e.key]=o,o=[]):e.key&&o.push(e))}),t.forEach(function(e){e&&(r.hasOwnProperty(e.key)&&(n=n.concat(r[e.key])),n.push(e))}),o.forEach(function(t){var r=e.indexOf(t);r>=0&&n.splice(r,0,t)}),n}function s(e,t,n){var r=void 0;return r="function"==typeof e?e({key:t,index:n}):e,Array.isArray(r)&&2===r.length?r:[r,r]}function l(e){return e&&e.children}Object.defineProperty(t,"__esModule",{value:!0}),t.toArrayChildren=o,t.findChildInChildrenByKey=a,t.mergeChildren=i,t.transformArguments=s,t.getChildrenFromProps=l;var u=n(1),c=r(u)},function(e,t,n){"use strict";var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o=n(1),a=n(99),i=o.createClass({displayName:"Radio",getDefaultProps:function(){return{prefixCls:"rc-radio",type:"radio"}},render:function(){return o.createElement(a,r({},this.props,{ref:"checkbox"}))}});e.exports=i},function(e,t,n){"use strict";e.exports=n(339)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(4),i=r(a),s=n(1),l=r(s),u=n(344),c=n(342),p=r(c),f=l["default"].createClass({displayName:"Rate",propTypes:{disabled:s.PropTypes.bool,value:s.PropTypes.number,defaultValue:s.PropTypes.number,count:s.PropTypes.number,allowHalf:s.PropTypes.bool,style:s.PropTypes.object,prefixCls:s.PropTypes.string,onChange:s.PropTypes.func},getDefaultProps:function(){return{defaultValue:0,count:5,allowHalf:!1,style:{},prefixCls:"rc-rate",onChange:o}},getInitialState:function(){var e=this.props.value;return void 0===e&&(e=this.props.defaultValue),{value:e}},componentWillReceiveProps:function(e){if("value"in e){var t=e.value;void 0===t&&(t=e.defaultValue),this.setState({value:t})}},onHover:function(e,t){var n=this.getStarValue(t,e.pageX);this.setState({hoverValue:n})},onMouseLeave:function(){this.setState({hoverValue:void 0})},onClick:function(e,t){var n=this.getStarValue(t,e.pageX);"value"in this.props||this.setState({value:n}),this.onMouseLeave(),this.props.onChange(n)},getStarDOM:function(e){return i["default"].findDOMNode(this.refs["star_"+e])},getStarValue:function(e,t){var n=e+1;if(this.props.allowHalf){var r=(0,u.getOffsetLeft)(this.getStarDOM(0)),o=(0,u.getOffsetLeft)(this.getStarDOM(1))-r;t-r-o*e<o/2&&(n-=.5)}return n},render:function(){for(var e=this.props,t=e.count,n=e.allowHalf,r=e.style,o=e.prefixCls,a=e.disabled,i=this.state,s=i.value,u=i.hoverValue,c=[],f=a?o+"-disabled":"",d=0;d<t;d++)c.push(l["default"].createElement(p["default"],{ref:"star_"+d,index:d,disabled:a,prefixCls:o+"-star",allowHalf:n,value:void 0===u?s:u,onClick:this.onClick,onHover:this.onHover,key:d}));return l["default"].createElement("ul",{className:o+" "+f,style:r,onMouseLeave:a?null:this.onMouseLeave},c)}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=a["default"].createClass({displayName:"Star",propTypes:{value:o.PropTypes.number,index:o.PropTypes.number,prefixCls:o.PropTypes.string,allowHalf:o.PropTypes.bool,disabled:o.PropTypes.bool,onHover:o.PropTypes.func,onClick:o.PropTypes.func},onHover:function(e){this.props.onHover(e,this.props.index)},onClick:function(e){this.props.onClick(e,this.props.index)},getClassName:function(){var e=this.props,t=e.index,n=e.value,r=e.prefixCls,o=e.allowHalf,a=t+1;return o&&n+.5===a?r+" "+r+"-half "+r+"-active":a<=n?r+" "+r+"-full":r+" "+r+"-zero"},render:function(){var e=this.onHover,t=this.onClick,n=this.props,r=n.disabled,o=n.prefixCls;return a["default"].createElement("li",{className:this.getClassName(),onClick:r?null:t,onMouseMove:r?null:e},a["default"].createElement("div",{className:o+"-content"}))}});t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(341),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t){"use strict";function n(e,t){var n=t?e.pageYOffset:e.pageXOffset,r=t?"scrollTop":"scrollLeft";if("number"!=typeof n){var o=e.document;n=o.documentElement[r],"number"!=typeof n&&(n=o.body[r])}return n}function r(e){var t=void 0,n=void 0,r=void 0,o=e.ownerDocument,a=o.body,i=o&&o.documentElement;return t=e.getBoundingClientRect(),n=t.left,r=t.top,n-=i.clientLeft||a.clientLeft||0,r-=i.clientTop||a.clientTop||0,{left:n,top:r}}function o(e){var t=r(e),o=e.ownerDocument,a=o.defaultView||o.parentWindow;return t.left+=n(a),t.left}Object.defineProperty(t,"__esModule",{value:!0}),t.getOffsetLeft=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),s=r(i),l=n(4),u=n(31),c=n(21),p=r(c),f=n(40),d=r(f),h=s["default"].createClass({displayName:"DropdownMenu",propTypes:{defaultActiveFirstOption:i.PropTypes.bool,value:i.PropTypes.any,dropdownMenuStyle:i.PropTypes.object,multiple:i.PropTypes.bool,onPopupFocus:i.PropTypes.func,onMenuDeSelect:i.PropTypes.func,onMenuSelect:i.PropTypes.func,prefixCls:i.PropTypes.string,menuItems:i.PropTypes.any,inputValue:i.PropTypes.string,visible:i.PropTypes.bool},componentWillMount:function(){this.lastInputValue=this.props.inputValue},componentDidMount:function(){this.scrollActiveItemToView(),this.lastVisible=this.props.visible},shouldComponentUpdate:function(e){return e.visible||(this.lastVisible=!1),e.visible},componentDidUpdate:function(e){var t=this.props;!e.visible&&t.visible&&this.scrollActiveItemToView(),this.lastVisible=t.visible,this.lastInputValue=t.inputValue},scrollActiveItemToView:function(){var e=(0,l.findDOMNode)(this.firstActiveItem);e&&(0,d["default"])(e,(0,l.findDOMNode)(this.refs.menu),{onlyScrollIfNeeded:!0})},renderMenu:function(){var e=this,t=this.props,n=t.menuItems,r=t.defaultActiveFirstOption,l=t.value,f=t.prefixCls,d=t.multiple,h=t.onMenuSelect,y=t.inputValue;if(n&&n.length){var v=function(){var o={};d?(o.onDeselect=t.onMenuDeselect,o.onSelect=h):o.onClick=h;var v=(0,u.getSelectKeys)(n,l),m={},g=n;return v.length&&!function(){t.visible&&!e.lastVisible&&(m.activeKey=v[0]);var r=!1,o=function(t){return r||v.indexOf(t.key)===-1?t:(r=!0,(0,i.cloneElement)(t,{ref:function(t){e.firstActiveItem=t}}))};g=n.map(function(e){if(e.type===c.ItemGroup){var t=e.props.children.map(o);return(0,i.cloneElement)(e,{},t)}return o(e)})}(),y!==e.lastInputValue&&(m.activeKey=""),{v:s["default"].createElement(p["default"],a({ref:"menu",style:e.props.dropdownMenuStyle,defaultActiveFirst:r},m,{multiple:d,focusable:!1},o,{selectedKeys:v,prefixCls:f+"-menu"}),g)}}();if("object"===("undefined"==typeof v?"undefined":o(v)))return v.v}return null},render:function(){return s["default"].createElement("div",{style:{overflow:"auto"},onFocus:this.props.onPopupFocus,onMouseDown:u.preventDefaultEvent},this.renderMenu())}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(31),l=n(21),u=n(350),c=r(u),p=n(44),f=r(p),d=n(106),h=r(d);t["default"]={filterOption:function y(e,t){if(!e)return!0;var y=this.props.filterOption;return!y||!t.props.disabled&&y.call(this,e,t)},renderFilterOptions:function(e){return this.renderFilterOptionsFromChildren(this.props.children,!0,e)},renderFilterOptionsFromChildren:function(e,t,n){var r=this,a=[],u=this.props,p=void 0===n?this.state.inputValue:n,d=[],y=u.tags;if(i["default"].Children.forEach(e,function(e){if(e.type!==f["default"]){(0,c["default"])(e.type===h["default"],"the children of `Select` should be `Select.Option` or `Select.OptGroup`, "+("instead of `"+(e.type.name||e.type.displayName||e.type)+"`."));var t=(0,s.getValuePropValue)(e);r.filterOption(p,e)&&a.push(i["default"].createElement(l.Item,o({style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,value:t,key:t},e.props))),y&&!e.props.disabled&&d.push(t)}else{var n=r.renderFilterOptionsFromChildren(e.props.children,!1);if(n.length){var u=e.props.label,v=e.key;v||"string"!=typeof u?!u&&v&&(u=v):v=u,a.push(i["default"].createElement(l.ItemGroup,{key:v,title:u},n))}}}),y){var v=this.state.value||[];if(v=v.filter(function(e){return d.indexOf(e.key)===-1&&(!p||String(e.key).indexOf(String(p))>-1)}),a=a.concat(v.map(function(e){var t=e.key;return i["default"].createElement(l.Item,{style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,value:t,key:t},t)})),p){var m=a.every(function(e){return(0,s.getValuePropValue)(e)!==p});m&&a.unshift(i["default"].createElement(l.Item,{style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,value:p,key:p},p))}}return!a.length&&t&&u.notFoundContent&&(a=[i["default"].createElement(l.Item,{style:s.UNSELECTABLE_STYLE,attribute:s.UNSELECTABLE_ATTRIBUTE,disabled:!0,value:"NOT_FOUND",key:"NOT_FOUND"},u.notFoundContent)]),a}},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}function i(e,t){return String((0,C.getPropValue)(t,this.props.optionFilterProp)).indexOf(e)>-1}function s(e,t){this[e]=t}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=n(1),c=r(u),p=n(4),f=r(p),d=n(11),h=n(2),y=r(h),v=n(44),m=r(v),g=n(8),b=r(g),P=n(77),O=r(P),C=n(31),T=n(348),w=r(T),x=n(346),E=r(x),S=c["default"].createClass({displayName:"Select",propTypes:{defaultActiveFirstOption:u.PropTypes.bool,multiple:u.PropTypes.bool,filterOption:u.PropTypes.any,showSearch:u.PropTypes.bool,disabled:u.PropTypes.bool,allowClear:u.PropTypes.bool,showArrow:u.PropTypes.bool,tags:u.PropTypes.bool,prefixCls:u.PropTypes.string,className:u.PropTypes.string,transitionName:u.PropTypes.string,optionLabelProp:u.PropTypes.string,optionFilterProp:u.PropTypes.string,animation:u.PropTypes.string,choiceTransitionName:u.PropTypes.string,onChange:u.PropTypes.func,onBlur:u.PropTypes.func,onSelect:u.PropTypes.func,onSearch:u.PropTypes.func,placeholder:u.PropTypes.any,onDeselect:u.PropTypes.func,labelInValue:u.PropTypes.bool,value:u.PropTypes.any,defaultValue:u.PropTypes.any,dropdownStyle:u.PropTypes.object,maxTagTextLength:u.PropTypes.number},mixins:[E["default"]],getDefaultProps:function(){return{prefixCls:"rc-select",filterOption:i,defaultOpen:!1,labelInValue:!1,defaultActiveFirstOption:!0,showSearch:!0,allowClear:!1,placeholder:"",defaultValue:[],onChange:a,onBlur:a,onSelect:a,onSearch:a,onDeselect:a,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},dropdownMenuStyle:{},optionFilterProp:"value",optionLabelProp:"value",notFoundContent:"Not Found"}},getInitialState:function(){var e=this.props,t=[];t="value"in e?(0,C.toArray)(e.value):(0,C.toArray)(e.defaultValue),t=this.addLabelToValue(e,t);var n="";e.combobox&&(n=t.length?String(t[0].key):""),this.saveInputRef=s.bind(this,"inputInstance"),this.saveInputMirrorRef=s.bind(this,"inputMirrorInstance");var r=e.open;return void 0===r&&(r=e.defaultOpen),{value:t,inputValue:n,open:r}},componentWillReceiveProps:function(e){if("value"in e){var t=(0,C.toArray)(e.value);t=this.addLabelToValue(e,t),this.setState({value:t}),e.combobox&&this.setState({inputValue:t.length?String(t[0].key):""})}},componentDidUpdate:function(){var e=this.state,t=this.props;if(e.open&&(0,C.isMultipleOrTags)(t)){var n=this.getInputDOMNode(),r=this.getInputMirrorDOMNode();n.value?(n.style.width="",n.style.width=r.clientWidth+"px"):n.style.width=""}},componentWillUnmount:function(){this.clearBlurTime(),this.dropdownContainer&&(f["default"].unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},onInputChange:function(e){var t=e.target.value,n=this.props;this.setInputValue(t),this.setState({open:!0}),(0,C.isCombobox)(n)&&this.fireChange([{key:t}])},onDropdownVisibleChange:function(e){this.setOpenState(e)},onKeyDown:function(e){var t=this.props;if(!t.disabled){var n=e.keyCode;this.state.open&&!this.getInputDOMNode()?this.onInputKeyDown(e):n!==d.KeyCode.ENTER&&n!==d.KeyCode.DOWN||(this.setOpenState(!0),e.preventDefault())}},onInputKeyDown:function(e){var t=this.props;if(!t.disabled){var n=this.state,r=e.keyCode; if(!(0,C.isMultipleOrTags)(t)||e.target.value||r!==d.KeyCode.BACKSPACE){if(r===d.KeyCode.DOWN){if(!n.open)return this.openIfHasChildren(),e.preventDefault(),void e.stopPropagation()}else if(r===d.KeyCode.ESC)return void(n.open&&(this.setOpenState(!1),e.preventDefault(),e.stopPropagation()));if(n.open){var o=this.refs.trigger.getInnerMenu();o&&o.onKeyDown(e)&&(e.preventDefault(),e.stopPropagation())}}else{var a=n.value.concat();if(a.length){var i=a.pop();t.onDeselect(t.labelInValue?i:i.key),this.fireChange(a)}}}},onMenuSelect:function(e){var t=e.item,n=this.state.value,r=this.props,o=(0,C.getValuePropValue)(t),a=this.getLabelFromOption(t),i=o;if(r.labelInValue&&(i={key:i,label:a}),r.onSelect(i,t),(0,C.isMultipleOrTags)(r)){if((0,C.findIndexInValueByKey)(n,o)!==-1)return;n=n.concat([{key:o,label:a}])}else{if(n.length&&n[0].key===o)return void this.setOpenState(!1,!0);n=[{key:o,label:a}],this.setOpenState(!1,!0)}this.fireChange(n);var s=void 0;s=(0,C.isCombobox)(r)?(0,C.getPropValue)(t,r.optionLabelProp):"",this.setInputValue(s,!1)},onMenuDeselect:function(e){var t=e.item,n=e.domEvent;"click"===n.type&&this.removeSelected((0,C.getValuePropValue)(t)),this.setInputValue("",!1)},onArrowClick:function(e){e.stopPropagation(),this.props.disabled||this.setOpenState(!this.state.open,!0)},onPlaceholderClick:function(){this.getInputDOMNode()&&this.getInputDOMNode().focus()},onOuterFocus:function(){this.clearBlurTime(),this._focused=!0,this.updateFocusClassName()},onPopupFocus:function(){this.maybeFocus(!0,!0)},onOuterBlur:function(){var e=this;this.blurTimer=setTimeout(function(){e._focused=!1,e.updateFocusClassName();var t=e.props,n=e.state.value;if((0,C.isSingleMode)(t)&&t.showSearch&&e.state.inputValue&&t.defaultActiveFirstOption){var r=e._options||[];if(r.length){var o=(0,C.findFirstMenuItem)(r);o&&(n=[{key:o.key,label:e.getLabelFromOption(o)}],e.fireChange(n))}}t.onBlur(e.getVLForOnChange(n))},10)},onClearSelection:function(e){var t=this.props,n=this.state;if(!t.disabled){var r=n.inputValue,o=n.value;e.stopPropagation(),(r||o.length)&&(o.length&&this.fireChange([]),this.setOpenState(!1,!0),r&&this.setInputValue(""))}},onChoiceAnimationLeave:function(){this.refs.trigger.refs.trigger.forcePopupAlign()},getLabelBySingleValue:function(e,t){var n=this;if(void 0===t)return null;var r=null;return c["default"].Children.forEach(e,function(e){if(e.type===m["default"]){var o=n.getLabelBySingleValue(e.props.children,t);null!==o&&(r=o)}else(0,C.getValuePropValue)(e)===t&&(r=n.getLabelFromOption(e))}),r},getLabelFromOption:function(e){return(0,C.getPropValue)(e,this.props.optionLabelProp)},getLabelFromProps:function(e,t){return this.getLabelByValue(e.children,t)},getVLForOnChange:function(e){var t=e;return void 0!==t?(this.props.labelInValue||(t=t.map(function(e){return e.key})),(0,C.isMultipleOrTags)(this.props)?t:t[0]):t},getLabelByValue:function(e,t){var n=this.getLabelBySingleValue(e,t);return null===n?t:n},getDropdownContainer:function(){return this.dropdownContainer||(this.dropdownContainer=document.createElement("div"),document.body.appendChild(this.dropdownContainer)),this.dropdownContainer},getPlaceholderElement:function(){var e=this.props,t=this.state,n=!1;t.inputValue&&(n=!0),t.value.length&&(n=!0),(0,C.isCombobox)(e)&&1===t.value.length&&!t.value[0].key&&(n=!1);var r=e.placeholder;return r?c["default"].createElement("div",l({onMouseDown:C.preventDefaultEvent,style:l({display:n?"none":"block"},C.UNSELECTABLE_STYLE)},C.UNSELECTABLE_ATTRIBUTE,{onClick:this.onPlaceholderClick,className:e.prefixCls+"-selection__placeholder"}),r):null},getInputElement:function(){var e=this.props;return c["default"].createElement("div",{className:e.prefixCls+"-search__field__wrap"},c["default"].createElement("input",{ref:this.saveInputRef,onChange:this.onInputChange,onKeyDown:this.onInputKeyDown,value:this.state.inputValue,disabled:e.disabled,className:e.prefixCls+"-search__field"}),c["default"].createElement("span",{ref:this.saveInputMirrorRef,className:e.prefixCls+"-search__field__mirror"},this.state.inputValue))},getInputDOMNode:function(){return this.inputInstance},getInputMirrorDOMNode:function(){return this.inputMirrorInstance},getPopupDOMNode:function(){return this.refs.trigger.getPopupDOMNode()},getPopupMenuComponent:function(){return this.refs.trigger.getInnerMenu()},setOpenState:function(e,t){var n=this,r=this.props,o=this.state;if(o.open===e)return void this.maybeFocus(e,t);var a={open:e};!e&&(0,C.isSingleMode)(r)&&r.showSearch&&this.setInputValue(""),e||this.maybeFocus(e,t),this.setState(a,function(){e&&n.maybeFocus(e,t)})},setInputValue:function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];this.setState({inputValue:e}),t&&this.props.onSearch(e)},clearBlurTime:function(){this.blurTimer&&(clearTimeout(this.blurTimer),this.blurTimer=null)},updateFocusClassName:function(){var e=this.refs,t=this.props;this._focused?(0,O["default"])(e.root).add(t.prefixCls+"-focused"):(0,O["default"])(e.root).remove(t.prefixCls+"-focused")},maybeFocus:function(e,t){if(t||e){var n=this.getInputDOMNode(),r=document,o=r.activeElement;if(n&&(e||(0,C.isMultipleOrTagsOrCombobox)(this.props)))o!==n&&n.focus();else{var a=this.refs.selection;o!==a&&a.focus()}}},addLabelToValue:function(e,t){var n=this,r=t;return e.labelInValue?r.forEach(function(t){t.label=t.label||n.getLabelFromProps(e,t.key)}):r=r.map(function(t){return{key:t,label:n.getLabelFromProps(e,t)}}),r},removeSelected:function(e){var t=this.props;if(!t.disabled){var n=void 0,r=this.state.value.filter(function(t){return t.key===e&&(n=t.label),t.key!==e}),o=(0,C.isMultipleOrTags)(t);if(o){var a=e;t.labelInValue&&(a={key:e,label:n}),t.onDeselect(a)}this.fireChange(r)}},openIfHasChildren:function(){var e=this.props;(c["default"].Children.count(e.children)||(0,C.isSingleMode)(e))&&this.setOpenState(!0)},fireChange:function(e){var t=this.props;"value"in t||this.setState({value:e}),t.onChange(this.getVLForOnChange(e))},renderTopControlNode:function(){var e=this,t=this.state,n=t.value,r=t.open,o=t.inputValue,a=this.props,i=a.choiceTransitionName,s=a.prefixCls,u=a.maxTagTextLength,p=a.showSearch,f=s+"-selection__rendered",d=null;if((0,C.isSingleMode)(a)){var h=null;if(n.length){var y=!1,v=1;p&&r?(y=!o,y&&(v=.4)):y=!0,h=c["default"].createElement("div",{key:"value",className:s+"-selection-selected-value",style:{display:y?"block":"none",opacity:v}},n[0].label)}d=p?[h,c["default"].createElement("div",{className:s+"-search "+s+"-search--inline",key:"input",style:{display:r?"block":"none"}},this.getInputElement())]:[h]}else{var m=[];(0,C.isMultipleOrTags)(a)&&(m=n.map(function(t){var n=t.label,r=n;u&&"string"==typeof n&&n.length>u&&(n=n.slice(0,u)+"...");var o=(0,C.toArray)(a.children).some(function(e){var n=(0,C.getValuePropValue)(e);return n===t.key&&e.props&&e.props.disabled}),i=o?s+"-selection__choice "+s+"-selection__choice__disabled":s+"-selection__choice";return c["default"].createElement("li",l({style:C.UNSELECTABLE_STYLE},C.UNSELECTABLE_ATTRIBUTE,{onMouseDown:C.preventDefaultEvent,className:i,key:t.key,title:r}),c["default"].createElement("div",{className:s+"-selection__choice__content"},n),o?null:c["default"].createElement("span",{className:s+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.key)}))})),m.push(c["default"].createElement("li",{className:s+"-search "+s+"-search--inline",key:"__input"},this.getInputElement())),d=(0,C.isMultipleOrTags)(a)&&i?c["default"].createElement(b["default"],{onLeave:this.onChoiceAnimationLeave,component:"ul",transitionName:i},m):c["default"].createElement("ul",null,m)}return c["default"].createElement("div",{className:f},this.getPlaceholderElement(),d)},render:function(){var e,t=this.props,n=(0,C.isMultipleOrTags)(t),r=this.state,a=t.className,i=t.disabled,s=t.allowClear,u=t.prefixCls,p=this.renderTopControlNode(),f={},d=this.state.open,h=[];d&&(h=this.renderFilterOptions()),this._options=h,!d||!(0,C.isMultipleOrTagsOrCombobox)(t)&&t.showSearch||h.length||(d=!1),(0,C.isMultipleOrTagsOrCombobox)(t)||(f={onKeyDown:this.onKeyDown,tabIndex:0});var v=(e={},o(e,a,!!a),o(e,u,1),o(e,u+"-open",d),o(e,u+"-focused",d||!!this._focused),o(e,u+"-combobox",(0,C.isCombobox)(t)),o(e,u+"-disabled",i),o(e,u+"-enabled",!i),o(e,u+"-allow-clear",!!t.allowClear),e),m=l({},C.UNSELECTABLE_STYLE,{display:"none"});(r.inputValue||r.value.length)&&(m.display="block");var g=c["default"].createElement("span",l({key:"clear",onMouseDown:C.preventDefaultEvent,style:m},C.UNSELECTABLE_ATTRIBUTE,{className:u+"-selection__clear",onClick:this.onClearSelection}));return c["default"].createElement(w["default"],{onPopupFocus:this.onPopupFocus,dropdownAlign:t.dropdownAlign,dropdownClassName:t.dropdownClassName,dropdownMatchSelectWidth:t.dropdownMatchSelectWidth,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle,transitionName:t.transitionName,animation:t.animation,prefixCls:t.prefixCls,dropdownStyle:t.dropdownStyle,combobox:t.combobox,showSearch:t.showSearch,options:h,multiple:n,disabled:i,visible:d,inputValue:r.inputValue,value:r.value,onDropdownVisibleChange:this.onDropdownVisibleChange,getPopupContainer:t.getPopupContainer,onMenuSelect:this.onMenuSelect,onMenuDeselect:this.onMenuDeselect,ref:"trigger"},c["default"].createElement("div",{style:t.style,ref:"root",onBlur:this.onOuterBlur,onFocus:this.onOuterFocus,className:(0,y["default"])(v)},c["default"].createElement("div",l({ref:"selection",key:"selection",className:u+"-selection\n "+u+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":d},f),p,s&&!n?g:null,n||!t.showArrow?null:c["default"].createElement("span",l({key:"arrow",className:u+"-arrow",style:C.UNSELECTABLE_STYLE},C.UNSELECTABLE_ATTRIBUTE,{onMouseDown:C.preventDefaultEvent,onClick:this.onArrowClick}),c["default"].createElement("b",null)))))}});t["default"]=S,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(14),l=r(s),u=n(1),c=r(u),p=n(2),f=r(p),d=n(345),h=r(d),y=n(4),v=r(y),m=n(31),g={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},b=c["default"].createClass({displayName:"SelectTrigger",propTypes:{onPopupFocus:u.PropTypes.func,dropdownMatchSelectWidth:u.PropTypes.bool,dropdownAlign:u.PropTypes.object,visible:u.PropTypes.bool,disabled:u.PropTypes.bool,showSearch:u.PropTypes.bool,dropdownClassName:u.PropTypes.string,multiple:u.PropTypes.bool,inputValue:u.PropTypes.string,filterOption:u.PropTypes.any,options:u.PropTypes.any,prefixCls:u.PropTypes.string,popupClassName:u.PropTypes.string,children:u.PropTypes.any},componentDidUpdate:function(){var e=this.props,t=e.visible,n=e.dropdownMatchSelectWidth;if(t){var r=this.getPopupDOMNode();if(r){var o=n?"width":"minWidth";r.style[o]=v["default"].findDOMNode(this).offsetWidth+"px"}}},getInnerMenu:function(){return this.popupMenu&&this.popupMenu.refs.menu},getPopupDOMNode:function(){return this.refs.trigger.getPopupDomNode()},getDropdownElement:function(e){var t=this.props;return c["default"].createElement(h["default"],i({ref:this.saveMenu},e,{prefixCls:this.getDropdownPrefixCls(),onMenuSelect:t.onMenuSelect,onMenuDeselect:t.onMenuDeselect,value:t.value,defaultActiveFirstOption:t.defaultActiveFirstOption,dropdownMenuStyle:t.dropdownMenuStyle}))},getDropdownTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=this.getDropdownPrefixCls()+"-"+e.animation),t},getDropdownPrefixCls:function(){return this.props.prefixCls+"-dropdown"},saveMenu:function(e){this.popupMenu=e},render:function(){var e,t=this.props,n=t.onPopupFocus,r=a(t,["onPopupFocus"]),s=r.multiple,u=r.visible,p=r.inputValue,d=r.dropdownAlign,h=r.disabled,y=r.showSearch,v=r.dropdownClassName,b=this.getDropdownPrefixCls(),P=(e={},o(e,v,!!v),o(e,b+"--"+(s?"multiple":"single"),1),e),O=this.getDropdownElement({menuItems:r.options,onPopupFocus:n,multiple:s,inputValue:p,visible:u}),C=void 0;return C=h?[]:(0,m.isSingleMode)(r)&&!y?["click"]:["blur"],c["default"].createElement(l["default"],i({},r,{showAction:h?[]:["click"],hideAction:C,ref:"trigger",popupPlacement:"bottomLeft",builtinPlacements:g,prefixCls:b,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:r.onDropdownVisibleChange,popup:O,popupAlign:d,popupVisible:u,getPopupContainer:r.getPopupContainer,popupClassName:(0,f["default"])(P),popupStyle:r.dropdownStyle}),r.children)}});t["default"]=b,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.OptGroup=t.Option=void 0;var o=n(347),a=r(o),i=n(106),s=r(i),l=n(44),u=r(l);a["default"].Option=s["default"],a["default"].OptGroup=u["default"],t.Option=s["default"],t.OptGroup=u["default"],t["default"]=a["default"]},17,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),s=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},l=n(1),u=r(l),c=n(111),p=r(c),f=function(e){function t(e){o(this,t),s(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.state={isTooltipVisible:!1}}return a(t,e),i(t,[{key:"showTooltip",value:function(){this.setState({isTooltipVisible:!0})}},{key:"hideTooltip",value:function(){this.setState({isTooltipVisible:!1})}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.tipTransitionName,r=e.tipFormatter,o=e.vertical,a=e.offset,i=e.value,s=e.dragging,l=e.noTip,c=o?{bottom:a+"%"}:{left:a+"%"},f=u["default"].createElement("div",{className:t,style:c,onMouseUp:this.showTooltip.bind(this),onMouseEnter:this.showTooltip.bind(this),onMouseLeave:this.hideTooltip.bind(this)});if(l)return f;var d=s||this.state.isTooltipVisible;return u["default"].createElement(p["default"],{prefixCls:t.replace("slider-handle","tooltip"),placement:"top",visible:d,overlay:u["default"].createElement("span",null,r(i)),delay:0,transitionName:n},f)}}]),t}(u["default"].Component);t["default"]=f,f.propTypes={className:u["default"].PropTypes.string,vertical:u["default"].PropTypes.bool,offset:u["default"].PropTypes.number,tipTransitionName:u["default"].PropTypes.string,tipFormatter:u["default"].PropTypes.func,value:u["default"].PropTypes.number,dragging:u["default"].PropTypes.bool,noTip:u["default"].PropTypes.bool},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),s=r(i),l=n(2),u=r(l),c=function(e){var t=e.className,n=e.vertical,r=e.marks,i=e.included,l=e.upperBound,c=e.lowerBound,p=e.max,f=e.min,d=Object.keys(r),h=d.length,y=100/(h-1),v=.9*y,m=p-f,g=d.map(parseFloat).sort(function(e,t){return e-t}).map(function(e){var p,d=!i&&e===l||i&&e<=l&&e>=c,h=(0,u["default"])((p={},o(p,t+"-text",!0),o(p,t+"-text-active",d),p)),y={marginBottom:"-200%",bottom:(e-f)/m*100+"%"},g={width:v+"%",marginLeft:-v/2+"%",left:(e-f)/m*100+"%"},b=n?y:g,P=r[e],O="object"==typeof P&&!s["default"].isValidElement(P),C=O?P.label:P,T=O?a({},b,P.style):b;return s["default"].createElement("span",{className:h,style:T,key:e},C)});return s["default"].createElement("div",{className:t},g)};t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){}function l(e){return e.touches.length>1||"touchend"===e.type.toLowerCase()&&e.touches.length>0}function u(e,t){return e?t.touches[0].clientY:t.touches[0].pageX}function c(e,t){return e?t.clientY:t.pageX}function p(e){e.stopPropagation(),e.preventDefault()}Object.defineProperty(t,"__esModule",{value:!0});var f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),h=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},y=n(1),v=r(y),m=n(11),g=n(2),b=r(g),P=n(355),O=r(P),C=n(351),T=r(C),w=n(354),x=r(w),E=n(352),S=r(E),k=function(e){function t(e){a(this,t),h(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e);var n=e.range,r=e.min,o=e.max,i=n?[r,r]:r,s="defaultValue"in e?e.defaultValue:i,l=void 0!==e.value?e.value:s,u=void 0,c=void 0;e.range?(c=this.trimAlignValue(l[0]),u=this.trimAlignValue(l[1])):u=this.trimAlignValue(l);var p=void 0;p=e.range&&u===c&&c===o?"lowerBound":"upperBound",this.state={handle:null,recent:p,upperBound:u,lowerBound:c||r}}return i(t,e),d(t,[{key:"componentWillReceiveProps",value:function(e){if("value"in e||"min"in e||"max"in e){var t=this.state,n=t.lowerBound,r=t.upperBound;if(e.range){var o=e.value||[n,r],a=this.trimAlignValue(o[1],e),i=this.trimAlignValue(o[0],e);if(i===n&&a===r)return;this.setState({upperBound:a,lowerBound:i}),(this.isValueOutOfBounds(r,e)||this.isValueOutOfBounds(n,e))&&this.props.onChange([i,a])}else{var o=void 0!==e.value?e.value:r,s=this.trimAlignValue(o,e);if(s===r&&n===e.min)return;this.setState({upperBound:s,lowerBound:e.min}),this.isValueOutOfBounds(r,e)&&this.props.onChange(s)}}}},{key:"onChange",value:function(e){var t=this.props,n=!("value"in t);n?this.setState(e):e.handle&&this.setState({handle:e.handle});var r=f({},this.state,e),o=t.range?[r.lowerBound,r.upperBound]:r.upperBound;t.onChange(o)}},{key:"onMouseMove",value:function(e){var t=c(this.props.vertical,e);this.onMove(e,t)}},{key:"onTouchMove",value:function(e){if(l(e))return void this.end("touch");var t=u(this.props.vertical,e);this.onMove(e,t)}},{key:"onMove",value:function(e,t){p(e);var n=this.props,r=this.state,a=t-this.startPosition;a=this.props.vertical?-a:a;var i=a/this.getSliderLength()*(n.max-n.min),s=this.trimAlignValue(this.startValue+i),l=r[r.handle];if(s!==l)return n.allowCross&&s<r.lowerBound&&"upperBound"===r.handle?void this.onChange({handle:"lowerBound",lowerBound:s,upperBound:this.state.lowerBound}):n.allowCross&&s>r.upperBound&&"lowerBound"===r.handle?void this.onChange({handle:"upperBound",upperBound:s,lowerBound:this.state.upperBound}):void this.onChange(o({},r.handle,s))}},{key:"onTouchStart",value:function(e){if(!l(e)){var t=u(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("touch"),p(e)}}},{key:"onMouseDown",value:function(e){if(0===e.button){var t=c(this.props.vertical,e);this.onStart(t),this.addDocumentEvents("mouse"),p(e)}}},{key:"onStart",value:function(e){var t=this.props;t.onBeforeChange(this.getValue());var n=this.calcValueByPos(e);this.startValue=n,this.startPosition=e;var r=this.state,a=r.upperBound,i=r.lowerBound,s="upperBound";if(this.props.range){var l=Math.abs(a-n)>Math.abs(i-n);l&&(s="lowerBound");var u=a===i;u&&(s=r.recent),u&&n!==a&&(s=n<a?"lowerBound":"upperBound")}this.setState({handle:s,recent:s});var c=r[s];n!==c&&this.onChange(o({},s,n))}},{key:"getValue",value:function(){var e=this.state,t=e.lowerBound,n=e.upperBound;return this.props.range?[t,n]:n}},{key:"getSliderLength",value:function(){var e=this.refs.slider;return e?this.props.vertical?e.clientHeight:e.clientWidth:0}},{key:"getSliderStart",value:function(){var e=this.refs.slider,t=e.getBoundingClientRect();return this.props.vertical?t.top:t.left}},{key:"getPrecision",value:function(e){var t=e.toString(),n=0;return t.indexOf(".")>=0&&(n=t.length-t.indexOf(".")-1),n}},{key:"isValueOutOfBounds",value:function(e,t){return e<t.min||e>t.max}},{key:"trimAlignValue",value:function(e,t){var n=this.state||{},r=n.handle,o=n.lowerBound,a=n.upperBound,i=f({},this.props,t||{}),s=i.marks,l=i.step,u=i.min,c=i.max,p=i.allowCross,d=e;d<=u&&(d=u),d>=c&&(d=c),!p&&"upperBound"===r&&d<=o&&(d=o),!p&&"lowerBound"===r&&d>=a&&(d=a);var h=Object.keys(s).map(parseFloat);if(null!==l){var y=Math.round(d/l)*l;h.push(y)}var v=h.map(function(e){return Math.abs(d-e)}),m=h[v.indexOf(Math.min.apply(Math,v))];return null!==l?parseFloat(m.toFixed(this.getPrecision(l))):m}},{key:"calcOffset",value:function(e){var t=this.props,n=t.min,r=t.max,o=(e-n)/(r-n);return 100*o}},{key:"calcValue",value:function(e){var t=this.props,n=t.vertical,r=t.min,o=t.max,a=Math.abs(e/this.getSliderLength()),i=n?(1-a)*(o-r)+r:a*(o-r)+r;return i}},{key:"calcValueByPos",value:function(e){var t=e-this.getSliderStart(),n=this.trimAlignValue(this.calcValue(t));return n}},{key:"addDocumentEvents",value:function(e){"touch"===e?(this.onTouchMoveListener=m.Dom.addEventListener(document,"touchmove",this.onTouchMove.bind(this)),this.onTouchUpListener=m.Dom.addEventListener(document,"touchend",this.end.bind(this,"touch"))):"mouse"===e&&(this.onMouseMoveListener=m.Dom.addEventListener(document,"mousemove",this.onMouseMove.bind(this)),this.onMouseUpListener=m.Dom.addEventListener(document,"mouseup",this.end.bind(this,"mouse")))}},{key:"removeEvents",value:function(e){"touch"===e?(this.onTouchMoveListener.remove(),this.onTouchUpListener.remove()):"mouse"===e&&(this.onMouseMoveListener.remove(),this.onMouseUpListener.remove())}},{key:"end",value:function(e){this.removeEvents(e),this.props.onAfterChange(this.getValue()),this.setState({handle:null})}},{key:"render",value:function(){var e,t=this.state,n=t.handle,r=t.upperBound,a=t.lowerBound,i=this.props,l=i.className,u=i.prefixCls,c=i.disabled,p=i.vertical,f=i.dots,d=i.included,h=i.range,m=i.step,g=i.marks,P=i.max,C=i.min,T=i.tipTransitionName,w=i.tipFormatter,E=i.children,k=this.props.handle,j=this.calcOffset(r),_=this.calcOffset(a),N=u+"-handle",M=null===m||null===w,D=(0,y.cloneElement)(k,{className:N,noTip:M,tipTransitionName:T,tipFormatter:w,vertical:p,offset:j,value:r,dragging:"upperBound"===n}),A=null;h&&(A=(0,y.cloneElement)(k,{className:N,noTip:M,tipTransitionName:T,tipFormatter:w,vertical:p,offset:_,value:a,dragging:"lowerBound"===n}));var L=(0,b["default"])((e={},o(e,u,!0),o(e,u+"-disabled",c),o(e,l,!!l),o(e,u+"-vertical",this.props.vertical),e)),V=d||h;return v["default"].createElement("div",{ref:"slider",className:L,onTouchStart:c?s:this.onTouchStart.bind(this),onMouseDown:c?s:this.onMouseDown.bind(this)},D,A,v["default"].createElement(O["default"],{className:u+"-track",vertical:p,included:V,offset:_,length:j-_}),v["default"].createElement(x["default"],{prefixCls:u,vertical:p,marks:g,dots:f,step:m,included:V,lowerBound:a,upperBound:r,max:P,min:C}),v["default"].createElement(S["default"],{className:u+"-mark",vertical:p,marks:g,included:V,lowerBound:a,upperBound:r,max:P,min:C}),E)}}]),t}(v["default"].Component);k.propTypes={min:v["default"].PropTypes.number,max:v["default"].PropTypes.number,step:v["default"].PropTypes.number,defaultValue:v["default"].PropTypes.oneOfType([v["default"].PropTypes.number,v["default"].PropTypes.arrayOf(v["default"].PropTypes.number)]),value:v["default"].PropTypes.oneOfType([v["default"].PropTypes.number,v["default"].PropTypes.arrayOf(v["default"].PropTypes.number)]),marks:v["default"].PropTypes.object,included:v["default"].PropTypes.bool,className:v["default"].PropTypes.string,prefixCls:v["default"].PropTypes.string,disabled:v["default"].PropTypes.bool,children:v["default"].PropTypes.any,onBeforeChange:v["default"].PropTypes.func,onChange:v["default"].PropTypes.func,onAfterChange:v["default"].PropTypes.func,handle:v["default"].PropTypes.element,tipTransitionName:v["default"].PropTypes.string,tipFormatter:v["default"].PropTypes.func,dots:v["default"].PropTypes.bool,range:v["default"].PropTypes.bool,vertical:v["default"].PropTypes.bool,allowCross:v["default"].PropTypes.bool},k.defaultProps={prefixCls:"rc-slider",className:"",tipTransitionName:"",min:0,max:100,step:1,marks:{},handle:v["default"].createElement(T["default"],null),onBeforeChange:s,onChange:s,onAfterChange:s,tipFormatter:function(e){return e},included:!0,disabled:!1,dots:!1,range:!1,vertical:!1,allowCross:!0},t["default"]=k,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t,n,r,o,a){(0,p["default"])(!n||r>0,"`Slider[step]` should be a positive number in order to make Slider[dots] work.");var i=Object.keys(t).map(parseFloat);if(n)for(var s=o;s<=a;s+=r)i.indexOf(s)>=0||i.push(s);return i}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(2),u=r(l),c=n(357),p=r(c),f=function(e){var t=e.prefixCls,n=e.vertical,r=e.marks,i=e.dots,l=e.step,c=e.included,p=e.lowerBound,f=e.upperBound,d=e.max,h=e.min,y=d-h,v=a(n,r,i,l,h,d).map(function(e){var r,a=Math.abs(e-h)/y*100+"%",i=n?{bottom:a}:{left:a},l=!c&&e===f||c&&e<=f&&e>=p,d=(0,u["default"])((r={},o(r,t+"-dot",!0),o(r,t+"-dot-active",l),r));return s["default"].createElement("span",{className:d,style:i,key:e})});return s["default"].createElement("div",{className:t+"-step"},v)};t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=function(e){var t=e.className,n=e.included,r=e.vertical,o=e.offset,i=e.length,s={visibility:n?"visible":"hidden"};return r?(s.bottom=o+"%",s.height=i+"%"):(s.left=o+"%",s.width=i+"%"),a["default"].createElement("div",{className:t,style:s})};t["default"]=i,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(353)},17,function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function i(e){var t,n,r=e.className,i=e.prefixCls,l=e.style,c=e.tailWidth,f=e.status,d=void 0===f?"wait":f,h=e.iconPrefix,y=e.icon,v=e.wrapperStyle,m=e.adjustMarginRight,g=e.stepLast,b=e.stepNumber,P=e.description,O=e.title,C=a(e,["className","prefixCls","style","tailWidth","status","iconPrefix","icon","wrapperStyle","adjustMarginRight","stepLast","stepNumber","description","title"]),T=(0,p["default"])((t={},o(t,i+"-icon",!0),o(t,h+"icon",!0),o(t,h+"icon-"+y,y),o(t,h+"icon-check",!y&&"finish"===d),o(t,h+"icon-cross",!y&&"error"===d),t)),w=y||"finish"===d||"error"===d?u["default"].createElement("span",{className:T}):u["default"].createElement("span",{className:i+"-icon"},b),x=(0,p["default"])((n={},o(n,i+"-item",!0),o(n,i+"-item-last",g),o(n,i+"-status-"+d,!0),o(n,i+"-custom",y),o(n,r,!!r),n));return u["default"].createElement("div",s({},C,{className:x,style:s({width:c,marginRight:m},l)}),g?"":u["default"].createElement("div",{className:i+"-tail"},u["default"].createElement("i",null)),u["default"].createElement("div",{className:i+"-step"},u["default"].createElement("div",{className:i+"-head",style:{background:v.background||v.backgroundColor}},u["default"].createElement("div",{className:i+"-head-inner"},w)),u["default"].createElement("div",{className:i+"-main"},u["default"].createElement("div",{className:i+"-title",style:{background:v.background||v.backgroundColor}},O),P?u["default"].createElement("div",{className:i+"-description"},P):"")))}var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=n(1),u=r(l),c=n(2),p=r(c);i.propTypes={className:l.PropTypes.string,prefixCls:l.PropTypes.string,style:l.PropTypes.object,wrapperStyle:l.PropTypes.object,tailWidth:l.PropTypes.oneOfType([l.PropTypes.number,l.PropTypes.string]),status:l.PropTypes.string,iconPrefix:l.PropTypes.string,icon:l.PropTypes.string,adjustMarginRight:l.PropTypes.oneOfType([l.PropTypes.number,l.PropTypes.string]),stepLast:l.PropTypes.bool,stepNumber:l.PropTypes.string,description:l.PropTypes.any,title:l.PropTypes.any},e.exports=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(var n=Object.getOwnPropertyNames(t),r=0;r<n.length;r++){var o=n[r],a=Object.getOwnPropertyDescriptor(t,o);a&&a.configurable&&void 0===e[o]&&Object.defineProperty(e,o,a)}return e}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):o(e,t))}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(4),h=r(d),y=n(2),v=r(y),m=function(e){function t(n){s(this,t);var r=l(this,e.call(this,n));return r.culcLastStepOffsetWidth=function(){var e=h["default"].findDOMNode(r);e.children.length>0&&(r.culcTimeout=setTimeout(function(){var t=e.lastChild.getBoundingClientRect().width; r.state.lastStepOffsetWidth!==t&&r.setState({lastStepOffsetWidth:t})}))},r.state={lastStepOffsetWidth:0},r}return u(t,e),t.prototype.componentDidMount=function(){this.culcLastStepOffsetWidth()},t.prototype.componentDidUpdate=function(){this.culcLastStepOffsetWidth()},t.prototype.componentWillUnmount=function(){this.culcTimeout&&clearTimeout(this.culcTimeout)},t.prototype.render=function(){var e,t=this,n=this.props,r=n.prefixCls,o=n.style,s=void 0===o?{}:o,l=n.className,u=n.children,p=n.direction,d=n.labelPlacement,h=n.iconPrefix,y=n.status,m=n.size,g=i(n,["prefixCls","style","className","children","direction","labelPlacement","iconPrefix","status","size"]),b=u.length-1,P=this.state.lastStepOffsetWidth>0,O=(0,v["default"])((e={},a(e,r,!0),a(e,r+"-"+m,m),a(e,r+"-"+p,!0),a(e,r+"-label-"+d,"horizontal"===p),a(e,r+"-hidden",!P),a(e,l,l),e));return f["default"].createElement("div",c({className:O,style:s},g),f["default"].Children.map(u,function(e,o){var a="vertical"!==p&&o!==b&&P?100/b+"%":null,i="vertical"===p||o===b?null:-(t.state.lastStepOffsetWidth/b+1),l={stepNumber:(o+1).toString(),stepLast:o===b,tailWidth:a,adjustMarginRight:i,prefixCls:r,iconPrefix:h,wrapperStyle:s};return"error"===n.status&&o===n.current-1&&(l.className=n.prefixCls+"-next-error"),e.props.status||(o===n.current?l.status=y:o<n.current?l.status="finish":l.status="wait"),f["default"].cloneElement(e,l)},this))},t}(f["default"].Component);t["default"]=m,m.propTypes={prefixCls:p.PropTypes.string,iconPrefix:p.PropTypes.string,direction:p.PropTypes.string,labelPlacement:p.PropTypes.string,children:p.PropTypes.any,status:p.PropTypes.string,size:p.PropTypes.string},m.defaultProps={prefixCls:"rc-steps",iconPrefix:"rc",direction:"horizontal",labelPlacement:"horizontal",current:0,status:"process",size:""},e.exports=t["default"]},function(e,t,n){"use strict";var r=n(359);r.Step=n(358),e.exports=r},function(e,t,n){"use strict";function r(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=n(2),u=s.createClass({displayName:"Switch",propTypes:{className:s.PropTypes.string,prefixCls:s.PropTypes.string,disabled:s.PropTypes.bool,checkedChildren:s.PropTypes.any,unCheckedChildren:s.PropTypes.any,onChange:s.PropTypes.func,onMouseUp:s.PropTypes.func},getDefaultProps:function(){return{prefixCls:"rc-switch",checkedChildren:null,unCheckedChildren:null,className:"",defaultChecked:!1,onChange:a}},getInitialState:function(){var e=this.props,t=!1;return t="checked"in e?!!e.checked:!!e.defaultChecked,{checked:t}},componentWillReceiveProps:function(e){"checked"in e&&this.setState({checked:!!e.checked})},setChecked:function(e){"checked"in this.props||this.setState({checked:e}),this.props.onChange(e)},toggle:function(){var e=!this.state.checked;this.setChecked(e)},handleKeyDown:function(e){37===e.keyCode&&this.setChecked(!1),39===e.keyCode&&this.setChecked(!0)},handleMouseUp:function(e){this.refs.node&&this.refs.node.blur(),this.props.onMouseUp&&this.props.onMouseUp(e)},render:function(){var e,t=this.props,n=t.className,u=t.prefixCls,c=t.disabled,p=t.checkedChildren,f=t.unCheckedChildren,d=r(t,["className","prefixCls","disabled","checkedChildren","unCheckedChildren"]),h=this.state.checked,y=l((e={},o(e,n,!!n),o(e,u,!0),o(e,u+"-checked",h),o(e,u+"-disabled",c),e));return s.createElement("span",i({},d,{className:y,tabIndex:"0",ref:"node",onKeyDown:this.handleKeyDown,onClick:c?a:this.toggle,onMouseUp:this.handleMouseUp}),s.createElement("span",{className:u+"-inner"},h?p:f))}});e.exports=u},function(e,t,n){"use strict";e.exports=n(361)},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),s=r(i),l=n(364),u=r(l),c=n(366),p=s["default"].createClass({displayName:"Table",propTypes:{data:s["default"].PropTypes.array,expandIconAsCell:s["default"].PropTypes.bool,defaultExpandAllRows:s["default"].PropTypes.bool,expandedRowKeys:s["default"].PropTypes.array,defaultExpandedRowKeys:s["default"].PropTypes.array,useFixedHeader:s["default"].PropTypes.bool,columns:s["default"].PropTypes.array,prefixCls:s["default"].PropTypes.string,bodyStyle:s["default"].PropTypes.object,style:s["default"].PropTypes.object,rowKey:s["default"].PropTypes.func,rowClassName:s["default"].PropTypes.func,expandedRowClassName:s["default"].PropTypes.func,childrenColumnName:s["default"].PropTypes.string,onExpand:s["default"].PropTypes.func,onExpandedRowsChange:s["default"].PropTypes.func,indentSize:s["default"].PropTypes.number,onRowClick:s["default"].PropTypes.func,columnsPageRange:s["default"].PropTypes.array,columnsPageSize:s["default"].PropTypes.number,expandIconColumnIndex:s["default"].PropTypes.number,showHeader:s["default"].PropTypes.bool,footer:s["default"].PropTypes.func,scroll:s["default"].PropTypes.object,rowRef:s["default"].PropTypes.func},getDefaultProps:function(){return{data:[],useFixedHeader:!1,expandIconAsCell:!1,columns:[],defaultExpandAllRows:!1,defaultExpandedRowKeys:[],rowKey:function(e){return e.key},rowClassName:function(){return""},expandedRowClassName:function(){return""},onExpand:function(){},onExpandedRowsChange:function(){},prefixCls:"rc-table",bodyStyle:{},style:{},childrenColumnName:"children",indentSize:15,columnsPageSize:5,expandIconColumnIndex:0,showHeader:!0,scroll:{},rowRef:function(){return null}}},getInitialState:function(){var e=this.props,t=[],n=[].concat(o(e.data));if(e.defaultExpandAllRows)for(var r=0;r<n.length;r++){var a=n[r];a[e.childrenColumnName]&&a[e.childrenColumnName].length>0&&(t.push(e.rowKey(a)),n=n.concat(a[e.childrenColumnName]))}else t=e.expandedRowKeys||e.defaultExpandedRowKeys;return{expandedRowKeys:t,data:e.data,currentColumnsPage:0,currentHoverIndex:null,scrollPosition:"left",fixedColumnsRowsHeight:[]}},componentDidMount:function(){var e=this;this.refs.headTable&&(this.refs.headTable.scrollLeft=0),this.refs.bodyTable&&(this.refs.bodyTable.scrollLeft=0);var t=this.props.prefixCls,n=this.refs.bodyTable.querySelectorAll("."+t+"-row"),r=[].slice.call(n).map(function(e){return e.getBoundingClientRect().height||"auto"});this.timer=setTimeout(function(){e.setState({fixedColumnsRowsHeight:r})})},componentWillReceiveProps:function(e){"data"in e&&this.setState({data:e.data}),"expandedRowKeys"in e&&this.setState({expandedRowKeys:e.expandedRowKeys})},componentWillUnmount:function(){clearTimeout(this.timer)},onExpandedRowsChange:function(e){this.props.expandedRowKeys||this.setState({expandedRowKeys:e}),this.props.onExpandedRowsChange(e)},onExpanded:function(e,t){var n=this.findExpandedRow(t);if("undefined"==typeof n||e){if(!n&&e){var r=this.getExpandedRows().concat();r.push(this.props.rowKey(t)),this.onExpandedRowsChange(r)}}else this.onRowDestroy(t);this.props.onExpand(e,t)},onRowDestroy:function(e){var t=this.getExpandedRows().concat(),n=this.props.rowKey(e),r=-1;t.forEach(function(e,t){e===n&&(r=t)}),r!==-1&&t.splice(r,1),this.onExpandedRowsChange(t)},getExpandedRows:function(){return this.props.expandedRowKeys||this.state.expandedRowKeys},getHeader:function(e,t){var n=this.props,r=n.showHeader,o=n.expandIconAsCell,a=n.prefixCls,i=[];return o&&"right"!==t&&i.push({key:"rc-table-expandIconAsCell",className:a+"-expand-icon-th",title:""}),i=i.concat(e||this.getCurrentColumns()).map(function(e){if(0!==e.colSpan)return s["default"].createElement("th",{key:e.key,colSpan:e.colSpan,className:e.className||""},e.title)}),r?s["default"].createElement("thead",{className:a+"-thead"},s["default"].createElement("tr",null,i)):null},getExpandedRow:function(e,t,n,r,o){var a=this.props.prefixCls;return s["default"].createElement("tr",{key:e+"-extra-row",style:{display:n?"":"none"},className:a+"-expanded-row "+r},this.props.expandIconAsCell&&"right"!==o?s["default"].createElement("td",{key:"rc-table-expand-icon-placeholder"}):null,s["default"].createElement("td",{colSpan:this.props.columns.length},"right"!==o?t:"&nbsp;"))},getRowsByData:function(e,t,n,r,o){for(var i=this.props,l=i.childrenColumnName,c=i.expandedRowRender,p=this.state.fixedColumnsRowsHeight,f=[],d=i.rowKey,h=i.rowClassName,y=i.rowRef,v=i.expandedRowClassName,m=i.data.some(function(e){return e[l]}),g=i.onRowClick,b=this.isAnyColumnsFixed(),P="right"!==o&&i.expandIconAsCell,O="right"!==o?i.expandIconColumnIndex:-1,C=0;C<e.length;C++){var T=e[C],w=d?d(T,C):void 0,x=T[l],E=this.isRowExpanded(T),S=void 0;c&&E&&(S=c(T,C));var k=h(T,C);this.state.currentHoverIndex===C&&(k+=" "+i.prefixCls+"-row-hover");var j={};b&&(j.onHover=this.handleRowHover);var _=o&&p[C]?{height:p[C]}:{};f.push(s["default"].createElement(u["default"],a({indent:n,indentSize:i.indentSize,needIndentSpaced:m,className:k,record:T,expandIconAsCell:P,onDestroy:this.onRowDestroy,index:C,visible:t,onExpand:this.onExpanded,expandable:x||c,expanded:E,prefixCls:i.prefixCls+"-row",childrenColumnName:l,columns:r||this.getCurrentColumns(),expandIconColumnIndex:O,onRowClick:g,style:_},j,{key:w,ref:y(T,C)})));var N=t&&E;S&&E&&f.push(this.getExpandedRow(w,S,N,v(T,C),o)),x&&(f=f.concat(this.getRowsByData(x,N,n+1)))}return f},getRows:function(e,t){return this.getRowsByData(this.state.data,!0,0,e,t)},getColGroup:function(e,t){var n=[];return this.props.expandIconAsCell&&"right"!==t&&n.push(s["default"].createElement("col",{className:this.props.prefixCls+"-expand-icon-col",key:"rc-table-expand-icon-col"})),n=n.concat((e||this.props.columns).map(function(e){return s["default"].createElement("col",{key:e.key,style:{width:e.width,minWidth:e.width}})})),s["default"].createElement("colgroup",null,n)},getCurrentColumns:function(){var e=this,t=this.props,n=t.columns,r=t.columnsPageRange,o=t.columnsPageSize,i=t.prefixCls,s=this.state.currentColumnsPage;return!r||r[0]>r[1]?n:n.map(function(t,n){var l=a({},t);if(n>=r[0]&&n<=r[1]){var u=r[0]+s*o,c=r[0]+(s+1)*o-1;c>r[1]&&(c=r[1]),(n<u||n>c)&&(l.className=l.className||"",l.className+=" "+i+"-column-hidden"),l=e.wrapPageColumn(l,n===u,n===c)}return l})},getLeftFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"left"===e.fixed||e.fixed===!0});return this.getTable({columns:t,fixed:"left"})},getRightFixedTable:function(){var e=this.props.columns,t=e.filter(function(e){return"right"===e.fixed});return this.getTable({columns:t,fixed:"right"})},getTable:function(){var e=this,t=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],n=t.columns,r=t.fixed,o=this.props,i=o.prefixCls,l=o.scroll,u=void 0===l?{}:l,p=this.props.useFixedHeader,f=a({},this.props.bodyStyle),d={},h="";if((u.x||n)&&(h=i+"-fixed",f.overflowX=f.overflowX||"auto"),u.y){f.height=f.height||u.y,f.overflowY=f.overflowY||"auto",p=!0;var y=(0,c.measureScrollbar)();y>0&&((r?f:d).marginBottom="-"+y+"px",(r?f:d).paddingBottom="0px")}var v=function(){var t=arguments.length<=0||void 0===arguments[0]||arguments[0],o=arguments.length<=1||void 0===arguments[1]||arguments[1],a={};return!n&&u.x&&(u.x===!0?a.tableLayout="fixed":a.width=u.x),s["default"].createElement("table",{className:h,style:a},e.getColGroup(n,r),t?e.getHeader(n,r):null,o?s["default"].createElement("tbody",{className:i+"-tbody"},e.getRows(n,r)):null)},m=void 0;p&&(m=s["default"].createElement("div",{className:i+"-header",ref:n?null:"headTable",style:d,onMouseEnter:this.detectScrollTarget,onScroll:this.handleBodyScroll},v(!0,!1)));var g=s["default"].createElement("div",{className:i+"-body",style:f,ref:"bodyTable",onMouseEnter:this.detectScrollTarget,onScroll:this.handleBodyScroll},v(!p));if(n&&n.length){var b=void 0;"left"===n[0].fixed||n[0].fixed===!0?b="fixedColumnsBodyLeft":"right"===n[0].fixed&&(b="fixedColumnsBodyRight"),delete f.overflowX,delete f.overflowY,g=s["default"].createElement("div",{className:i+"-body-outer",style:a({},f)},s["default"].createElement("div",{className:i+"-body-inner",ref:b,onMouseEnter:this.detectScrollTarget,onScroll:this.handleBodyScroll},v(!p)))}return s["default"].createElement("span",null,m,g)},getFooter:function(){var e=this.props,t=e.footer,n=e.prefixCls;return t?s["default"].createElement("div",{className:n+"-footer"},t(this.state.data)):null},getMaxColumnsPage:function(){var e=this.props,t=e.columnsPageRange,n=e.columnsPageSize;return Math.floor((t[1]-t[0]+1)/n)},goToColumnsPage:function(e){var t=this.getMaxColumnsPage(),n=e;n<0&&(n=0),n>t&&(n=t),this.setState({currentColumnsPage:n})},prevColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage-1)},nextColumnsPage:function(){this.goToColumnsPage(this.state.currentColumnsPage+1)},wrapPageColumn:function(e,t,n){var r=this.props.prefixCls,o=this.state.currentColumnsPage,a=this.getMaxColumnsPage(),i=r+"-prev-columns-page";0===o&&(i+=" "+r+"-prev-columns-page-disabled");var l=s["default"].createElement("span",{className:i,onClick:this.prevColumnsPage}),u=r+"-next-columns-page";o===a&&(u+=" "+r+"-next-columns-page-disabled");var c=s["default"].createElement("span",{className:u,onClick:this.nextColumnsPage});return t&&(e.title=s["default"].createElement("span",null,l,e.title),e.className=(e.className||"")+(" "+r+"-column-has-prev")),n&&(e.title=s["default"].createElement("span",null,e.title,c),e.className=(e.className||"")+(" "+r+"-column-has-next")),e},findExpandedRow:function(e){var t=this,n=this.getExpandedRows().filter(function(n){return n===t.props.rowKey(e)});return n[0]},isRowExpanded:function(e){return"undefined"!=typeof this.findExpandedRow(e)},detectScrollTarget:function(e){this.scrollTarget=e.currentTarget},isAnyColumnsFixed:function(){return this.getCurrentColumns().some(function(e){return!!e.fixed})},isAnyColumnsLeftFixed:function(){return this.getCurrentColumns().some(function(e){return"left"===e.fixed||e.fixed===!0})},isAnyColumnsRightFixed:function(){return this.getCurrentColumns().some(function(e){return"right"===e.fixed})},handleBodyScroll:function(e){if(e.target===this.scrollTarget){var t=this.props.scroll,n=void 0===t?{}:t;n.x&&(e.target===this.refs.bodyTable&&this.refs.headTable?this.refs.headTable.scrollLeft=e.target.scrollLeft:e.target===this.refs.headTable&&this.refs.bodyTable&&(this.refs.bodyTable.scrollLeft=e.target.scrollLeft),0===e.target.scrollLeft?this.setState({scrollPosition:"left"}):e.target.scrollLeft+1>=e.target.children[0].getBoundingClientRect().width-e.target.getBoundingClientRect().width?this.setState({scrollPosition:"right"}):"middle"!==this.state.scrollPosition&&this.setState({scrollPosition:"middle"})),n.y&&(e.target!==this.refs.fixedColumnsBodyLeft&&(this.refs.fixedColumnsBodyLeft.scrollTop=e.target.scrollTop),e.target!==this.refs.fixedColumnsBodyRight&&(this.refs.fixedColumnsBodyRight.scrollTop=e.target.scrollTop),e.target!==this.refs.bodyTable&&(this.refs.bodyTable.scrollTop=e.target.scrollTop))}},handleRowHover:function(e,t){e?this.setState({currentHoverIndex:t}):this.setState({currentHoverIndex:null})},render:function(){var e=this.props,t=e.prefixCls,n=e.prefixCls;e.className&&(n+=" "+e.className),e.columnsPageRange&&(n+=" "+t+"-columns-paging"),(e.useFixedHeader||e.scroll&&e.scroll.y)&&(n+=" "+t+"-fixed-header"),n+=" "+t+"-scroll-position-"+this.state.scrollPosition;var r=this.isAnyColumnsFixed()||e.scroll.x||e.scroll.y;return s["default"].createElement("div",{className:n,style:e.style},this.isAnyColumnsLeftFixed()&&s["default"].createElement("div",{className:t+"-fixed-left"},this.getLeftFixedTable()),s["default"].createElement("div",{className:r?t+"-scroll":""},this.getTable(),this.getFooter()),this.isAnyColumnsRightFixed()&&s["default"].createElement("div",{className:t+"-fixed-right"},this.getRightFixedTable()))}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(280),l=r(s),u=i["default"].createClass({displayName:"TableRow",propTypes:{onDestroy:i["default"].PropTypes.func,onRowClick:i["default"].PropTypes.func,record:i["default"].PropTypes.object,prefixCls:i["default"].PropTypes.string,expandIconColumnIndex:i["default"].PropTypes.number,onHover:i["default"].PropTypes.func},getDefaultProps:function(){return{onRowClick:function(){},onDestroy:function(){},expandIconColumnIndex:0,onHover:function(){}}},componentWillUnmount:function(){this.props.onDestroy(this.props.record)},isInvalidRenderCellText:function(e){return e&&!i["default"].isValidElement(e)&&"[object Object]"===Object.prototype.toString.call(e)},render:function c(){for(var e=this.props,t=e.prefixCls,n=e.columns,r=e.record,a=e.style,s=e.visible,u=e.index,p=[],f=e.expanded,d=e.expandable,h=e.expandIconAsCell,y=e.indent,v=e.indentSize,m=e.needIndentSpaced,g=e.onRowClick,b=e.expandIconColumnIndex,P=0;P<n.length;P++){var O=n[P],C=O.className||"",c=O.render,T=l["default"].get(r,O.dataIndex),w=void 0,x=void 0,E=void 0,S=void 0,k=!1;d?w=i["default"].createElement("span",{className:t+"-expand-icon "+t+"-"+(f?"expanded":"collapsed"),onClick:e.onExpand.bind(null,!f,r)}):m&&(w=i["default"].createElement("span",{className:t+"-expand-icon "+t+"-spaced"}));var j=!h&&P===b;h&&0===P&&p.push(i["default"].createElement("td",{className:t+"-expand-icon-cell",key:"rc-table-expand-icon-cell"},w)),c&&(T=c(T,r,u),this.isInvalidRenderCellText(T)&&(x=T.props||{},S=x.rowSpan,E=x.colSpan,T=T.children)),this.isInvalidRenderCellText(T)&&(T=null),0!==S&&0!==E||(k=!0);var _=i["default"].createElement("span",{style:{paddingLeft:v*y+"px"},className:t+"-indent indent-level-"+y});k||p.push(i["default"].createElement("td",{key:O.key,colSpan:E,rowSpan:S,className:C},j?_:null,j?w:null,T))}return i["default"].createElement("tr",{onClick:g.bind(null,r,u),onMouseEnter:e.onHover.bind(null,!0,u),onMouseLeave:e.onHover.bind(null,!1,u),className:t+" "+e.className+" "+t+"-level-"+y,style:s?a:o({},a,{display:"none"})},p)}});t["default"]=u,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(363)},function(e,t){"use strict";function n(){if(r)return r;var e=document.createElement("div");for(var t in o)o.hasOwnProperty(t)&&(e.style[t]=o[t]);document.body.appendChild(e);var n=e.offsetWidth-e.clientWidth;return document.body.removeChild(e),r=n}Object.defineProperty(t,"__esModule",{value:!0}),t.measureScrollbar=n;var r=void 0,o={position:"absolute",top:"-9999px",width:"50px",height:"50px",overflow:"scroll"}},function(e,t,n){"use strict";function r(e){var t=e.refs,n=t.nav,r=(0,o.offset)(n),a=t.inkBar,i=t.activeTab,s=e.props.tabPosition;if(i){var l=i,u=(0,o.offset)(l),c=(0,o.getTransformPropertyName)();if("top"===s||"bottom"===s){var p=u.left-r.left;c?(a.style[c]="translate3d("+p+"px,0,0)",a.style.width=l.offsetWidth+"px",a.style.height=""):(a.style.left=p+"px",a.style.top="",a.style.bottom="",a.style.right=n.offsetWidth-p-l.offsetWidth+"px")}else{var f=u.top-r.top;c?(a.style[c]="translate3d(0,"+f+"px,0)",a.style.height=l.offsetHeight+"px",a.style.width=""):(a.style.left="",a.style.right="",a.style.top=f+"px",a.style.bottom=n.offsetHeight-f-l.offsetHeight+"px")}}a.style.display=i?"block":"none"}Object.defineProperty(t,"__esModule",{value:!0});var o=n(108);t["default"]={componentDidUpdate:function(){r(this)},componentDidMount:function(){r(this)}},e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t["default"]={LEFT:37,UP:38,RIGHT:39,DOWN:40},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s=n(1),l=r(s),u=n(2),c=r(u),p=n(367),f=r(p),d=n(108),h={"float":"right"},y=l["default"].createClass({displayName:"Nav",propTypes:{tabPosition:s.PropTypes.string,tabBarExtraContent:s.PropTypes.any,onTabClick:s.PropTypes.func,onKeyDown:s.PropTypes.func},mixins:[f["default"]],getInitialState:function(){return{next:!1,offset:0,prev:!1}},componentDidMount:function(){this.componentDidUpdate()},componentDidUpdate:function(e){var t=this.props;if(e&&e.tabPosition!==t.tabPosition)return void this.setOffset(0);var n=this.refs.nav,r=this.getOffsetWH(n),o=this.refs.navWrap,a=this.getOffsetWH(o),i=this.state,s=i.offset,l=a-r,u=this.state,c=u.next,p=u.prev;l>=0?(c=!1,this.setOffset(0),s=0):l<s?c=!0:(c=!1,this.setOffset(l),s=l),p=s<0,this.setNext(c),this.setPrev(p);var f={next:c,prev:p};this.isNextPrevShown(i)!==this.isNextPrevShown(f)?this.setNextPrev({},this.scrollToActiveTab):e&&t.activeKey===e.activeKey||this.scrollToActiveTab()},onTabClick:function(e){this.props.onTabClick(e)},setNextPrev:function(e,t){this.setState(e,t)},getTabs:function(){var e=this,t=this.props,n=t.panels,r=t.activeKey,o=[],a=t.prefixCls;return l["default"].Children.forEach(n,function(t){var n=t.key,s=r===n?a+"-tab-active":"";s+=" "+a+"-tab";var u={};t.props.disabled?s+=" "+a+"-tab-disabled":u={onClick:e.onTabClick.bind(e,n)};var c={};r===n&&(c.ref="activeTab"),o.push(l["default"].createElement("div",i({role:"tab","aria-disabled":t.props.disabled?"true":"false","aria-selected":r===n?"true":"false"},u,{className:s,key:n},c),l["default"].createElement("div",{className:a+"-tab-inner"},t.props.tab)))}),o},getOffsetWH:function(e){var t=this.props.tabPosition,n="offsetWidth";return"left"!==t&&"right"!==t||(n="offsetHeight"),e[n]},getOffsetLT:function(e){var t=this.props.tabPosition,n="left";return"left"!==t&&"right"!==t||(n="top"),e.getBoundingClientRect()[n]},setOffset:function(e){var t=Math.min(0,e);if(this.state.offset!==t){this.setState({offset:t});var n={},r=this.props.tabPosition,o=(0,d.getTransformPropertyName)();n="left"===r||"right"===r?o?{name:o,value:"translate3d(0,"+t+"px,0)"}:{name:"top",value:t+"px"}:o?{name:o,value:"translate3d("+t+"px,0,0)"}:{name:"left",value:t+"px"},this.refs.nav.style[n.name]=n.value}},setPrev:function(e){this.state.prev!==e&&this.setState({prev:e})},setNext:function(e){this.state.next!==e&&this.setState({next:e})},isNextPrevShown:function(e){return e.next||e.prev},scrollToActiveTab:function(){var e=this.refs,t=e.activeTab,n=e.navWrap;if(t){var r=this.getOffsetWH(t),o=this.getOffsetWH(n),a=this.state.offset,i=this.getOffsetLT(n),s=this.getOffsetLT(t);i>s?(a+=i-s,this.setState({offset:a})):i+o<s+r&&(a-=s+r-(i+o),this.setState({offset:a}))}},prev:function(){var e=this.refs.navWrap,t=this.getOffsetWH(e),n=this.state,r=n.offset;this.setOffset(r+t)},next:function(){var e=this.refs.navWrap,t=this.getOffsetWH(e),n=this.state,r=n.offset;this.setOffset(r-t)},render:function(){var e=this.props,t=this.state,n=e.prefixCls,r=this.getTabs(),i=e.tabMovingDirection,s=n+"-ink-bar";i&&(s+=" "+n+"-ink-bar-transition-"+i);var u=void 0,p=void 0,f=t.prev||t.next;if(f){var d,y;p=l["default"].createElement("span",{onClick:t.prev?this.prev:a,unselectable:"unselectable",className:(0,c["default"])((d={},o(d,n+"-tab-prev",1),o(d,n+"-tab-btn-disabled",!t.prev),d))},l["default"].createElement("span",{className:n+"-tab-prev-icon"})),u=l["default"].createElement("span",{onClick:t.next?this.next:a,unselectable:"unselectable",className:(0,c["default"])((y={},o(y,n+"-tab-next",1),o(y,n+"-tab-btn-disabled",!t.next),y))},l["default"].createElement("span",{className:n+"-tab-next-icon"}))}var v=this.props.tabBarExtraContent;return l["default"].createElement("div",{role:"tablist",className:n+"-bar",tabIndex:"0",onKeyDown:this.props.onKeyDown},v?l["default"].createElement("div",{style:h},v):null,l["default"].createElement("div",{className:n+"-nav-container "+(f?n+"-nav-container-scrolling":""),style:e.style,ref:"container"},p,u,l["default"].createElement("div",{className:n+"-nav-wrap",ref:"navWrap"},l["default"].createElement("div",{className:n+"-nav-scroll"},l["default"].createElement("div",{className:n+"-nav",ref:"nav"},l["default"].createElement("div",{className:s,ref:"inkBar"}),r)))))}});t["default"]=y,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(){}function i(e){var t=void 0;return l["default"].Children.forEach(e.children,function(e){t||e.props.disabled||(t=e.key)}),t}Object.defineProperty(t,"__esModule",{value:!0});var s=n(1),l=r(s),u=n(368),c=r(u),p=n(107),f=r(p),d=n(369),h=r(d),y=n(8),v=r(y),m=n(2),g=r(m),b=l["default"].createClass({displayName:"Tabs",propTypes:{destroyInactiveTabPane:s.PropTypes.bool,onTabClick:s.PropTypes.func,onChange:s.PropTypes.func,children:s.PropTypes.any,tabBarExtraContent:s.PropTypes.any,animation:s.PropTypes.string,prefixCls:s.PropTypes.string,className:s.PropTypes.string,tabPosition:s.PropTypes.string},getDefaultProps:function(){return{prefixCls:"rc-tabs",destroyInactiveTabPane:!1,tabBarExtraContent:null,onChange:a,tabPosition:"top",style:{},contentStyle:{},navStyle:{},onTabClick:a}},getInitialState:function(){var e=this.props,t=void 0;return t="activeKey"in e?e.activeKey:"defaultActiveKey"in e?e.defaultActiveKey:i(e),{activeKey:t}},componentWillReceiveProps:function(e){var t=this.state.activeKey;if("activeKey"in e&&(t=e.activeKey,!t))return void this.setState({activeKey:t});var n=void 0;l["default"].Children.forEach(e.children,function(e){e.key===t&&(n=!0)}),n?this.setActiveKey(t,e):this.setActiveKey(i(e),e)},onTabClick:function(e){this.setActiveKey(e),this.props.onTabClick(e),this.state.activeKey!==e&&this.props.onChange(e)},onNavKeyDown:function(e){var t=e.keyCode;if(t===c["default"].RIGHT||t===c["default"].DOWN){e.preventDefault();var n=this.getNextActiveKey(!0);this.onTabClick(n)}else if(t===c["default"].LEFT||t===c["default"].UP){e.preventDefault();var r=this.getNextActiveKey(!1);this.onTabClick(r)}},getNextActiveKey:function(e){var t=this.state.activeKey,n=[];l["default"].Children.forEach(this.props.children,function(t){t.props.disabled||(e?n.push(t):n.unshift(t))});var r=n.length,o=r&&n[0].key;return n.forEach(function(e,a){e.key===t&&(o=a===r-1?n[0].key:n[a+1].key)}),o},getTabPanes:function(){var e=this.state,t=this.props,n=e.activeKey,r=t.children,o=[];return l["default"].Children.forEach(r,function(e){var r=e.key,a=n===r;o.push(l["default"].cloneElement(e,{active:a,rootPrefixCls:t.prefixCls}))}),o},getIndexPair:function(e,t,n){var r=[];l["default"].Children.forEach(e.children,function(e){r.push(e.key)});var o=r.indexOf(t),a=r.indexOf(n);return{currentIndex:o,nextIndex:a}},setActiveKey:function(e,t){var n=t||this.props,r=this.state.activeKey;if(!(r===e||"activeKey"in n&&n===this.props))if(r){var o=this.getIndexPair(n,r,e),a=o.currentIndex,i=o.nextIndex;if(a===-1){var s=this.getIndexPair(this.props,r,e);a=s.currentIndex,i=s.nextIndex}var l=a>i?"backward":"forward";this.setState({activeKey:e,tabMovingDirection:l})}else this.setState({activeKey:e})},render:function(){var e,t=this.props,n=t.destroyInactiveTabPane,r=t.prefixCls,a=t.tabPosition,i=t.className,s=t.animation,u=(0,g["default"])((e={},o(e,r,1),o(e,r+"-"+a,1),o(e,i,!!i),e)),c=this.state.tabMovingDirection,p=this.getTabPanes(),f=void 0;f=t.transitionName&&t.transitionName[c||"backward"],!f&&s&&(f=r+"-"+s+"-"+(c||"backward")),n&&(p=p.filter(function(e){return e.props.active})),f&&(p=n?l["default"].createElement(v["default"],{exclusive:!0,component:"div",transitionName:f},p):l["default"].createElement(v["default"],{showProp:"active",exclusive:!0,component:"div",transitionName:f},p));var d=[l["default"].createElement(h["default"],{prefixCls:r,key:"nav",onKeyDown:this.onNavKeyDown,tabBarExtraContent:this.props.tabBarExtraContent,tabPosition:a,style:t.navStyle,onTabClick:this.onTabClick,tabMovingDirection:c,panels:this.props.children,activeKey:this.state.activeKey}),l["default"].createElement("div",{className:r+"-content",style:t.contentStyle,key:"content"},p)];return"bottom"===a&&d.reverse(),l["default"].createElement("div",{className:u,style:t.style},d)}});b.TabPane=f["default"],t["default"]=b,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.TabPane=t["default"]=void 0;var o=n(370),a=r(o),i=n(107),s=r(i);t["default"]=a["default"],t.TabPane=s["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(109),a=r(o);t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(41),a=r(o),i=n(83),s=r(i);t["default"]={clear:"Clear",format:a["default"],calendar:s["default"]},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(81),a=r(o),i=n(84),s=r(i);t["default"]={clear:"\u6e05\u9664",format:a["default"],calendar:s["default"]},e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(378),s=r(i),l=n(9),u=r(l),c=function(e,t){var n=""+e;e<10&&(n="0"+e);var r=!1;return t&&t.indexOf(e)>=0&&(r=!0),{value:n,disabled:r}},p=a["default"].createClass({displayName:"Combobox",propTypes:{formatter:o.PropTypes.object,prefixCls:o.PropTypes.string,value:o.PropTypes.object,onChange:o.PropTypes.func,showHour:o.PropTypes.bool,gregorianCalendarLocale:o.PropTypes.object,showSecond:o.PropTypes.bool,hourOptions:o.PropTypes.array,minuteOptions:o.PropTypes.array,secondOptions:o.PropTypes.array,disabledHours:o.PropTypes.func,disabledMinutes:o.PropTypes.func,disabledSeconds:o.PropTypes.func,onCurrentSelectPanelChange:o.PropTypes.func},onItemChange:function(e,t){var n=this.props.onChange,r=this.props.value;r=r?r.clone():this.getNow().clone(),"hour"===e?r.setHourOfDay(t):"minute"===e?r.setMinutes(t):r.setSeconds(t),n(r)},onEnterSelectPanel:function(e){this.props.onCurrentSelectPanelChange(e)},getHourSelect:function(e){var t=this.props,n=t.prefixCls,r=t.hourOptions,o=t.disabledHours,i=t.showHour;if(!i)return null;var l=o();return a["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,l)}),selectedIndex:r.indexOf(e),type:"hour",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"hour")})},getMinuteSelect:function(e){var t=this.props,n=t.prefixCls,r=t.minuteOptions,o=t.disabledMinutes,i=this.props.value||this.getNow(),l=o(i.getHourOfDay());return a["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,l)}),selectedIndex:r.indexOf(e),type:"minute",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"minute")})},getSecondSelect:function(e){var t=this.props,n=t.prefixCls,r=t.secondOptions,o=t.disabledSeconds,i=t.showSecond;if(!i)return null;var l=this.props.value||this.getNow(),u=o(l.getHourOfDay(),l.getMinutes());return a["default"].createElement(s["default"],{prefixCls:n,options:r.map(function(e){return c(e,u)}),selectedIndex:r.indexOf(e),type:"second",onSelect:this.onItemChange,onMouseEnter:this.onEnterSelectPanel.bind(this,"second")})},getNow:function(){if(this.showNow)return this.showNow;var e=new u["default"](this.props.gregorianCalendarLocale); return e.setTime(Date.now()),this.showNow=e,e},render:function(){var e=this.props.prefixCls,t=this.props.value||this.getNow();return a["default"].createElement("div",{className:e+"-combobox"},this.getHourSelect(t.getHourOfDay()),this.getMinuteSelect(t.getMinutes()),this.getSecondSelect(t.getSeconds()))}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(381),s=r(i),l=a["default"].createClass({displayName:"Header",propTypes:{formatter:o.PropTypes.object,prefixCls:o.PropTypes.string,gregorianCalendarLocale:o.PropTypes.object,locale:o.PropTypes.object,disabledDate:o.PropTypes.func,placeholder:o.PropTypes.string,value:o.PropTypes.object,hourOptions:o.PropTypes.array,minuteOptions:o.PropTypes.array,secondOptions:o.PropTypes.array,disabledHours:o.PropTypes.func,disabledMinutes:o.PropTypes.func,disabledSeconds:o.PropTypes.func,onChange:o.PropTypes.func,onClear:o.PropTypes.func,onEsc:o.PropTypes.func,allowEmpty:o.PropTypes.bool,currentSelectPanel:o.PropTypes.string},getInitialState:function(){var e=this.props.value;return{str:e&&this.props.formatter.format(e)||"",invalid:!1}},componentDidMount:function(){this.timer=setTimeout(this.selectRange,0)},componentWillReceiveProps:function(e){var t=e.value;this.setState({str:t&&e.formatter.format(t)||"",invalid:!1})},componentDidUpdate:function(){this.timer=setTimeout(this.selectRange,0)},componentWillUnmount:function(){clearTimeout(this.timer)},onInputChange:function(e){var t=e.target.value;this.setState({str:t});var n=null,r=this.props,o=r.formatter,a=r.gregorianCalendarLocale,i=r.hourOptions,s=r.minuteOptions,l=r.secondOptions,u=r.disabledHours,c=r.disabledMinutes,p=r.disabledSeconds,f=r.onChange,d=r.allowEmpty;if(t){var h=this.props.value;try{n=o.parse(t,{locale:a,obeyCount:!0})}catch(y){return void this.setState({invalid:!0})}if(!n)return void this.setState({invalid:!0});if(i.indexOf(n.getHourOfDay())<0||s.indexOf(n.getMinutes())<0||l.indexOf(n.getSeconds())<0)return void this.setState({invalid:!0});var v=u(),m=c(n.getHourOfDay()),g=p(n.getHourOfDay(),n.getMinutes());if(v&&v.indexOf(n.getHourOfDay())>=0||m&&m.indexOf(n.getMinutes())>=0||g&&g.indexOf(n.getSeconds())>=0)return void this.setState({invalid:!0});if(h&&n){if(h.getHourOfDay()!==n.getHourOfDay()||h.getMinutes()!==n.getMinutes()||h.getSeconds()!==n.getSeconds()){var b=h.clone();b.setHourOfDay(n.getHourOfDay()),b.setMinutes(n.getMinutes()),b.setSeconds(n.getSeconds()),f(b)}}else h!==n&&f(n)}else{if(!d)return void this.setState({invalid:!0});f(null)}this.setState({invalid:!1})},onKeyDown:function(e){27===e.keyCode&&this.props.onEsc()},onClear:function(){this.setState({str:""}),this.props.onClear()},getClearButton:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.allowEmpty;return r?a["default"].createElement("a",{className:n+"-clear-btn",role:"button",title:t.clear,onMouseDown:this.onClear}):null},getInput:function(){var e=this.props,t=e.prefixCls,n=e.placeholder,r=this.state,o=r.invalid,i=r.str,s=o?t+"-input-invalid":"";return a["default"].createElement("input",{className:t+"-input "+s,ref:"input",onKeyDown:this.onKeyDown,value:i,placeholder:n,onChange:this.onInputChange})},selectRange:function(){if(this.refs.input.select(),this.props.currentSelectPanel&&this.refs.input.value){var e=0,t=0;"hour"===this.props.currentSelectPanel?(e=0,t=this.refs.input.value.indexOf(":")):"minute"===this.props.currentSelectPanel?(e=this.refs.input.value.indexOf(":")+1,t=this.refs.input.value.lastIndexOf(":")):"second"===this.props.currentSelectPanel&&(e=this.refs.input.value.lastIndexOf(":")+1,t=this.refs.input.value.length),t-e===2&&(0,s["default"])(this.refs.input,e,t)}},render:function(){var e=this.props.prefixCls;return a["default"].createElement("div",{className:e+"-input-wrap"},this.getInput(),this.getClearButton())}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(e,t,n){for(var r=[],o=0;o<e;o++)(!t||t.indexOf(o)<0||!n)&&r.push(o);return r}Object.defineProperty(t,"__esModule",{value:!0});var i=n(1),s=r(i),l=n(110),u=r(l),c=n(376),p=r(c),f=n(375),d=r(f),h=s["default"].createClass({displayName:"Panel",propTypes:{prefixCls:i.PropTypes.string,value:i.PropTypes.object,locale:i.PropTypes.object,placeholder:i.PropTypes.string,gregorianCalendarLocale:i.PropTypes.object,formatter:i.PropTypes.object,disabledHours:i.PropTypes.func,disabledMinutes:i.PropTypes.func,disabledSeconds:i.PropTypes.func,hideDisabledOptions:i.PropTypes.bool,onChange:i.PropTypes.func,onEsc:i.PropTypes.func,allowEmpty:i.PropTypes.bool,showHour:i.PropTypes.bool,showSecond:i.PropTypes.bool,onClear:i.PropTypes.func},mixins:[u["default"]],getDefaultProps:function(){return{onChange:o,onClear:o}},getInitialState:function(){return{value:this.props.value,selectionRange:[]}},componentWillReceiveProps:function(e){var t=e.value;t&&this.setState({value:t})},onChange:function(e){this.setState({value:e}),this.props.onChange(e)},onClear:function(){this.props.onClear()},onCurrentSelectPanelChange:function(e){this.setState({currentSelectPanel:e})},render:function(){var e=this.props,t=e.locale,n=e.prefixCls,r=e.placeholder,o=e.disabledHours,i=e.disabledMinutes,l=e.disabledSeconds,u=e.hideDisabledOptions,c=e.allowEmpty,f=e.showHour,h=e.showSecond,y=e.formatter,v=e.gregorianCalendarLocale,m=this.state.value,g=o(),b=i(m?m.getHourOfDay():null),P=l(m?m.getHourOfDay():null,m?m.getMinutes():null),O=a(24,g,u),C=a(60,b,u),T=a(60,P,u);return s["default"].createElement("div",{className:n+"-inner"},s["default"].createElement(p["default"],{prefixCls:n,gregorianCalendarLocale:v,locale:t,value:m,currentSelectPanel:this.state.currentSelectPanel,onEsc:this.props.onEsc,formatter:y,placeholder:r,hourOptions:O,minuteOptions:C,secondOptions:T,disabledHours:o,disabledMinutes:i,disabledSeconds:l,onChange:this.onChange,onClear:this.onClear,allowEmpty:c}),s["default"].createElement(d["default"],{prefixCls:n,value:m,gregorianCalendarLocale:v,formatter:y,onChange:this.onChange,showHour:f,showSecond:h,hourOptions:O,minuteOptions:C,secondOptions:T,disabledHours:o,disabledMinutes:i,disabledSeconds:l,onCurrentSelectPanelChange:this.onCurrentSelectPanelChange}))}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(4),l=r(s),u=n(2),c=r(u),p=function d(e,t,n){var r=window.requestAnimationFrame||function(){return setTimeout(arguments[0],10)};if(n<=0)return void(e.scrollTop=t);var o=t-e.scrollTop,a=o/n*10;r(function(){e.scrollTop=e.scrollTop+a,e.scrollTop!==t&&d(e,t,n-10)})},f=i["default"].createClass({displayName:"Select",propTypes:{prefixCls:a.PropTypes.string,options:a.PropTypes.array,gregorianCalendarLocale:a.PropTypes.object,selectedIndex:a.PropTypes.number,type:a.PropTypes.string,onSelect:a.PropTypes.func,onMouseEnter:a.PropTypes.func},componentDidMount:function(){this.scrollToSelected(0)},componentDidUpdate:function(e){e.selectedIndex!==this.props.selectedIndex&&this.scrollToSelected(120)},onSelect:function h(e){var t=this.props,h=t.onSelect,n=t.type;h(n,e)},getOptions:function(){var e=this,t=this.props,n=t.options,r=t.selectedIndex,a=t.prefixCls;return n.map(function(t,n){var s,l=(0,c["default"])((s={},o(s,a+"-select-option-selected",r===n),o(s,a+"-select-option-disabled",t.disabled),s)),u=null;return t.disabled||(u=e.onSelect.bind(e,+t.value)),i["default"].createElement("li",{className:l,key:n,onClick:u,disabled:t.disabled},t.value)})},scrollToSelected:function(e){var t=l["default"].findDOMNode(this),n=l["default"].findDOMNode(this.refs.list),r=this.props.selectedIndex;r<0&&(r=0);var o=n.children[r],a=o.offsetTop;p(t,a,e)},render:function(){if(0===this.props.options.length)return null;var e=this.props.prefixCls;return i["default"].createElement("div",{className:e+"-select",onMouseEnter:this.props.onMouseEnter},i["default"].createElement("ul",{ref:"list"},this.getOptions()))}});t["default"]=f,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return"string"==typeof e?new i["default"](e,t.format):e}Object.defineProperty(t,"__esModule",{value:!0}),t.getFormatter=o;var a=n(29),i=r(a)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o={bottomLeft:{points:["tl","tl"],overflow:n,offset:[0,-3],targetOffset:r},bottomRight:{points:["tr","tr"],overflow:n,offset:[0,-3],targetOffset:r},topRight:{points:["br","br"],overflow:n,offset:[0,3],targetOffset:r},topLeft:{points:["bl","bl"],overflow:n,offset:[0,3],targetOffset:r}};t["default"]=o,e.exports=t["default"]},function(e,t){"use strict";function n(e,t,n){if(e.createTextRange){var r=e.createTextRange();r.collapse(!0),r.moveStart("character",t),r.moveEnd("character",n),r.select(),e.focus()}else e.setSelectionRange?(e.focus(),e.setSelectionRange(t,n)):"undefined"!=typeof e.selectionStart&&(e.selectionStart=t,e.selectionEnd=n,e.focus())}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var n={};for(var r in e)t.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(e,r)&&(n[r]=e[r]);return n}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),s=r(i),l=n(383),u=n(14),c=r(u),p=s["default"].createClass({displayName:"Tooltip",propTypes:{trigger:i.PropTypes.any,children:i.PropTypes.any,defaultVisible:i.PropTypes.bool,visible:i.PropTypes.bool,placement:i.PropTypes.string,transitionName:i.PropTypes.string,animation:i.PropTypes.any,onVisibleChange:i.PropTypes.func,afterVisibleChange:i.PropTypes.func,overlay:i.PropTypes.node.isRequired,overlayStyle:i.PropTypes.object,overlayClassName:i.PropTypes.string,prefixCls:i.PropTypes.string,mouseEnterDelay:i.PropTypes.number,mouseLeaveDelay:i.PropTypes.number,getTooltipContainer:i.PropTypes.func,destroyTooltipOnHide:i.PropTypes.bool,align:i.PropTypes.object,arrowContent:i.PropTypes.any},getDefaultProps:function(){return{prefixCls:"rc-tooltip",mouseEnterDelay:0,destroyTooltipOnHide:!1,mouseLeaveDelay:.1,align:{},placement:"right",trigger:["hover"],arrowContent:null}},getPopupElement:function(){var e=this.props,t=e.arrowContent,n=e.overlay,r=e.prefixCls;return[s["default"].createElement("div",{className:r+"-arrow",key:"arrow"},t),s["default"].createElement("div",{className:r+"-inner",key:"content"},n)]},getPopupDomNode:function(){return this.refs.trigger.popupDomNode},render:function(){var e=this.props,t=e.overlayClassName,n=e.trigger,r=e.mouseEnterDelay,i=e.mouseLeaveDelay,u=e.overlayStyle,p=e.prefixCls,f=e.children,d=e.onVisibleChange,h=e.transitionName,y=e.animation,v=e.placement,m=e.align,g=e.destroyTooltipOnHide,b=e.defaultVisible,P=e.getTooltipContainer,O=o(e,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","children","onVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),C=a({},O);return"visible"in this.props&&(C.popupVisible=this.props.visible),s["default"].createElement(c["default"],a({popupClassName:t,ref:"trigger",prefixCls:p,popup:this.getPopupElement(),action:n,builtinPlacements:l.placements,popupPlacement:v,popupAlign:m,getPopupContainer:P,onPopupVisibleChange:d,popupTransitionName:h,popupAnimation:y,defaultPopupVisible:b,destroyPopupOnHide:g,mouseLeaveDelay:i,popupStyle:u,mouseEnterDelay:r},C),f)}});t["default"]=p,e.exports=t["default"]},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={adjustX:1,adjustY:1},r=[0,0],o=t.placements={left:{points:["cr","cl"],overflow:n,offset:[-4,0],targetOffset:r},right:{points:["cl","cr"],overflow:n,offset:[4,0],targetOffset:r},top:{points:["bc","tc"],overflow:n,offset:[0,-4],targetOffset:r},bottom:{points:["tc","bc"],overflow:n,offset:[0,4],targetOffset:r},topLeft:{points:["bl","tl"],overflow:n,offset:[0,-4],targetOffset:r},leftTop:{points:["tr","tl"],overflow:n,offset:[-4,0],targetOffset:r},topRight:{points:["br","tr"],overflow:n,offset:[0,-4],targetOffset:r},rightTop:{points:["tl","tr"],overflow:n,offset:[4,0],targetOffset:r},bottomRight:{points:["tr","br"],overflow:n,offset:[0,4],targetOffset:r},rightBottom:{points:["bl","br"],overflow:n,offset:[4,0],targetOffset:r},bottomLeft:{points:["tl","bl"],overflow:n,offset:[0,4],targetOffset:r},leftBottom:{points:["br","bl"],overflow:n,offset:[-4,0],targetOffset:r}};t["default"]=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(){}function s(e,t){return String((0,C.getPropValue)(t,(0,C.labelCompatible)(this.props.treeNodeFilterProp))).indexOf(e)>-1}function l(e,t){this[e]=t}function u(e){var t=arguments.length<=1||void 0===arguments[1]?0:arguments[1];return e.map(function(e,n){var r=t+"-"+n,o={title:e.label,value:e.value||String(e.key||e.label),key:e.key||e.value||r,disabled:e.disabled||!1,selectable:!e.hasOwnProperty("selectable")||e.selectable},a=void 0;return a=e.children&&e.children.length?f["default"].createElement(E["default"],o,u(e.children,r)):f["default"].createElement(E["default"],c({},o,{isLeaf:e.isLeaf}))})}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},p=n(1),f=r(p),d=n(4),h=r(d),y=n(11),v=n(2),m=r(v),g=n(10),b=r(g),P=n(8),O=r(P),C=n(113),T=n(385),w=r(T),x=n(112),E=r(x),S="SHOW_ALL",k="SHOW_PARENT",j="SHOW_CHILD",_=f["default"].createClass({displayName:"Select",propTypes:{children:p.PropTypes.any,multiple:p.PropTypes.bool,filterTreeNode:p.PropTypes.any,showSearch:p.PropTypes.bool,disabled:p.PropTypes.bool,showArrow:p.PropTypes.bool,tags:p.PropTypes.bool,transitionName:p.PropTypes.string,animation:p.PropTypes.string,choiceTransitionName:p.PropTypes.string,onClick:p.PropTypes.func,onChange:p.PropTypes.func,onSelect:p.PropTypes.func,onDeselect:p.PropTypes.func,onSearch:p.PropTypes.func,searchPlaceholder:p.PropTypes.string,placeholder:p.PropTypes.any,inputValue:p.PropTypes.any,value:p.PropTypes.oneOfType([p.PropTypes.array,p.PropTypes.string,p.PropTypes.object]),defaultValue:p.PropTypes.oneOfType([p.PropTypes.array,p.PropTypes.string,p.PropTypes.object]),label:p.PropTypes.any,defaultLabel:p.PropTypes.any,labelInValue:p.PropTypes.bool,dropdownStyle:p.PropTypes.object,drodownPopupAlign:p.PropTypes.object,maxTagTextLength:p.PropTypes.number,showCheckedStrategy:p.PropTypes.oneOf([S,k,j]),treeCheckStrictly:p.PropTypes.bool,treeIcon:p.PropTypes.bool,treeLine:p.PropTypes.bool,treeDefaultExpandAll:p.PropTypes.bool,treeCheckable:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.node]),treeNodeLabelProp:p.PropTypes.string,treeNodeFilterProp:p.PropTypes.string,treeData:p.PropTypes.array,treeDataSimpleMode:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.object]),loadData:p.PropTypes.func},getDefaultProps:function(){return{prefixCls:"rc-tree-select",filterTreeNode:s,showSearch:!0,allowClear:!1,placeholder:"",searchPlaceholder:"",labelInValue:!1,defaultValue:[],inputValue:"",onClick:i,onChange:i,onSelect:i,onDeselect:i,onSearch:i,showArrow:!0,dropdownMatchSelectWidth:!0,dropdownStyle:{},notFoundContent:"Not Found",showCheckedStrategy:j,treeCheckStrictly:!1,treeIcon:!1,treeLine:!1,treeDataSimpleMode:!1,treeDefaultExpandAll:!1,treeCheckable:!1,treeNodeFilterProp:"value",treeNodeLabelProp:"title"}},getInitialState:function(){var e=this.props,t=[];t="value"in e?(0,C.toArray)(e.value):(0,C.toArray)(e.defaultValue),this.renderedTreeData=this.renderTreeData(),t=this.addLabelToValue(e,t),t=this.getValue(e,t);var n=e.inputValue||"";this.saveInputRef=l.bind(this,"inputInstance");var r=e.open;return void 0===r&&(r=e.defaultOpen),{value:t,inputValue:n,open:r,focused:!1}},componentDidMount:function(){if(this.state.inputValue){var e=this.getInputDOMNode();e&&e.value&&(e.style.width="",e.style.width=e.scrollWidth+"px")}},componentWillReceiveProps:function(e){if("value"in e){"no"!==this._cacheTreeNodesStates&&this._savedValue&&e.value===this._savedValue?this._cacheTreeNodesStates=!0:this._cacheTreeNodesStates=!1;var t=(0,C.toArray)(e.value);this.renderedTreeData=this.renderTreeData(e),t=this.addLabelToValue(e,t),t=this.getValue(e,t),this.setState({value:t})}},componentDidUpdate:function(){var e=this.state,t=this.props;if(e.open&&(0,C.isMultipleOrTags)(t)){var n=this.getInputDOMNode();n.value?(n.style.width="",n.style.width=n.scrollWidth+"px"):n.style.width=""}},componentWillUnmount:function(){this.clearDelayTimer(),this.dropdownContainer&&(h["default"].unmountComponentAtNode(this.dropdownContainer),document.body.removeChild(this.dropdownContainer),this.dropdownContainer=null)},onInputChange:function(e){var t=e.target.value,n=this.props;this.setState({inputValue:t,open:!0}),n.onSearch(t)},onDropdownVisibleChange:function(e){var t=this;!e&&document.activeElement===this.getInputDOMNode(),setTimeout(function(){t.setOpenState(e)},10)},onKeyDown:function(e){var t=this.props;if(!t.disabled){var n=e.keyCode;this.state.open&&!this.getInputDOMNode()?this.onInputKeyDown(e):n!==y.KeyCode.ENTER&&n!==y.KeyCode.DOWN||(this.setOpenState(!0),e.preventDefault())}},onInputBlur:function(){},onInputKeyDown:function(e){var t=this.props;if(!t.disabled){var n=this.state,r=e.keyCode;if(!(0,C.isMultipleOrTags)(t)||e.target.value||r!==y.KeyCode.BACKSPACE){if(r===y.KeyCode.DOWN){if(!n.open)return this.openIfHasChildren(),e.preventDefault(),void e.stopPropagation()}else if(r===y.KeyCode.ESC)return void(n.open&&(this.setOpenState(!1),e.preventDefault(),e.stopPropagation()));n.open}else{var o=n.value.concat();if(o.length){var a=o.pop();t.onDeselect(this.isLabelInValue()?a:a.key),this.fireChange(o)}}}},onSelect:function(e,t){var n=this;if(t.selected===!1)return void this.onDeselect(t);var r=t.node,o=this.state.value,a=this.props,i=(0,C.getValuePropValue)(r),s=this.getLabelFromNode(r),l=i;this.isLabelInValue()&&(l={value:l,label:s}),a.onSelect(l,r,t);var u="check"===t.event;if((0,C.isMultipleOrTags)(a))if(u)o=this.getCheckedNodes(t,a).map(function(e){return{value:(0,C.getValuePropValue)(e),label:n.getLabelFromNode(e)}});else{if(o.some(function(e){return e.value===i}))return;o=o.concat([{value:i,label:s}])}else{if(o.length&&o[0].value===i)return void this.setOpenState(!1);o=[{value:i,label:s}],this.setOpenState(!1)}var c={triggerValue:i,triggerNode:r};if(u){c.checked=t.checked,c.allCheckedNodes=a.treeCheckStrictly?t.checkedNodes:(0,C.flatToHierarchy)(t.checkedNodesPositions),this._checkedNodes=t.checkedNodesPositions;var p=this.refs.trigger.popupEle;this._treeNodesStates=p.checkKeys}else c.selected=t.selected;this.fireChange(o,c),null===a.inputValue&&this.setState({inputValue:""})},onDeselect:function(e){this.removeSelected((0,C.getValuePropValue)(e.node)),(0,C.isMultipleOrTags)(this.props)||this.setOpenState(!1),null===this.props.inputValue&&this.setState({inputValue:""})},onPlaceholderClick:function(){this.getInputDOMNode().focus()},onOuterFocus:function(){},onOuterBlur:function(){},onClearSelection:function(e){var t=this.props,n=this.state;t.disabled||(e.stopPropagation(),(n.inputValue||n.value.length)&&(this.fireChange([]),this.setOpenState(!1),null===t.inputValue&&this.setState({inputValue:""})))},getLabelFromNode:function(e){return(0,C.getPropValue)(e,this.props.treeNodeLabelProp)},getLabelFromProps:function(e,t){var n=this;if(void 0===t)return null;var r=null;return(0,C.loopAllChildren)(this.renderedTreeData||e.children,function(e){(0,C.getValuePropValue)(e)===t&&(r=n.getLabelFromNode(e))}),null===r?t:r},getDropdownContainer:function(){return this.dropdownContainer||(this.dropdownContainer=document.createElement("div"),document.body.appendChild(this.dropdownContainer)),this.dropdownContainer},getSearchPlaceholderElement:function(e){var t=this.props,n=void 0;return n=(0,C.isMultipleOrTagsOrCombobox)(t)?t.placeholder||t.searchPlaceholder:t.searchPlaceholder,n?f["default"].createElement("span",{style:{display:e?"none":"block"},onClick:this.onPlaceholderClick,className:t.prefixCls+"-search__field__placeholder"},n):null},getInputElement:function(){var e=this.props;return f["default"].createElement("span",{className:e.prefixCls+"-search__field__wrap"},f["default"].createElement("input",{ref:this.saveInputRef,onBlur:this.onInputBlur,onChange:this.onInputChange,onKeyDown:this.onInputKeyDown,value:this.state.inputValue,disabled:e.disabled,className:e.prefixCls+"-search__field",role:"textbox"}),(0,C.isMultipleOrTags)(e)?null:this.getSearchPlaceholderElement(!!this.state.inputValue))},getInputDOMNode:function(){return this.inputInstance},getPopupDOMNode:function(){return this.refs.trigger.getPopupDOMNode()},getPopupComponentRefs:function(){return this.refs.trigger.getPopupEleRefs()},getValue:function(e,t){var n=this,r=t;if(e.treeCheckable&&e.treeCheckStrictly&&(this.halfCheckedValues=[],r=[],t.forEach(function(e){e.halfChecked?n.halfCheckedValues.push(e):r.push(e)})),!e.treeCheckable||e.treeCheckStrictly)return r;var o=void 0;this._cachetreeData&&this._cacheTreeNodesStates&&this._checkedNodes?this.checkedTreeNodes=o=this._checkedNodes:(this._treeNodesStates=(0,C.getTreeNodesStates)(this.renderedTreeData||e.children,r.map(function(e){return e.value})),this.checkedTreeNodes=o=this._treeNodesStates.checkedNodes);var a=function(t){return t.map(function(t){return{value:(0,C.getValuePropValue)(t.node),label:(0,C.getPropValue)(t.node,e.treeNodeLabelProp)}})},i=this.props,s=[];return i.showCheckedStrategy===S?s=a(o):i.showCheckedStrategy===k?!function(){var e=(0,C.filterParentPosition)(o.map(function(e){return e.pos}));s=a(o.filter(function(t){return e.indexOf(t.pos)!==-1}))}():s=a(o.filter(function(e){return!e.node.props.children})),s},getCheckedNodes:function(e,t){var n=e.checkedNodes;if(t.treeCheckStrictly)return n;var r=e.checkedNodesPositions;return t.showCheckedStrategy===S?n=n:t.showCheckedStrategy===k?!function(){var e=(0,C.filterParentPosition)(r.map(function(e){return e.pos}));n=r.filter(function(t){return e.indexOf(t.pos)!==-1}).map(function(e){return e.node})}():n=n.filter(function(e){return!e.props.children}),n},getDeselectedValue:function(e){var t=this.checkedTreeNodes,n=void 0;t.forEach(function(t){t.node.props.value===e&&(n=t.pos)});var r=n.split("-"),o=[],a=[];t.forEach(function(e){var t=e.pos.split("-");e.pos===n||r.length>t.length&&(0,C.isInclude)(t,r)||r.length<t.length&&(0,C.isInclude)(r,t)||(a.push(e),o.push(e.node.props.value))}),this.checkedTreeNodes=this._checkedNodes=a;var i=this.state.value.filter(function(e){return o.indexOf(e.value)!==-1});this.fireChange(i,{triggerValue:e,clear:!0})},setOpenState:function(e,t){var n=this;this.clearDelayTimer();var r=this.props,o=this.refs;this.setState({open:e},function(){if(t||e)if(e||(0,C.isMultipleOrTagsOrCombobox)(r)){var a=n.getInputDOMNode();a&&document.activeElement!==a&&a.focus()}else o.selection&&o.selection.focus()})},addLabelToValue:function(e,t){var n=this,r=t;return this.isLabelInValue()?r.forEach(function(t,o){return"[object Object]"!==Object.prototype.toString.call(r[o])?void(r[o]={value:"",label:""}):void(t.label=t.label||n.getLabelFromProps(e,t.value))}):r=r.map(function(t){return{value:t,label:n.getLabelFromProps(e,t)}}),r},clearDelayTimer:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},removeSelected:function(e){var t=this.props;if(!t.disabled){if(this._cacheTreeNodesStates="no",t.treeCheckable&&(t.showCheckedStrategy===S||t.showCheckedStrategy===k)&&!t.treeCheckStrictly)return void this.getDeselectedValue(e);var n=void 0,r=this.state.value.filter(function(t){return t.value===e&&(n=t.label),t.value!==e}),o=(0,C.isMultipleOrTags)(t);if(o){var a=e;this.isLabelInValue()&&(a={value:e,label:n}),t.onDeselect(a)}t.treeCheckable&&this.checkedTreeNodes&&this.checkedTreeNodes.length&&(this.checkedTreeNodes=this._checkedNodes=this.checkedTreeNodes.filter(function(e){return r.some(function(t){return t.value===e.node.props.value})})),this.fireChange(r,{triggerValue:e,clear:!0})}},openIfHasChildren:function(){var e=this.props;(f["default"].Children.count(e.children)||(0,C.isSingleMode)(e))&&this.setOpenState(!0)},fireChange:function(e,t){var n=this,r=this.props;"value"in r||this.setState({value:e});var a=e.map(function(e){return e.value}),i=this.state.value.map(function(e){return e.value});a.length===i.length&&a.every(function(e,t){return i[t]===e})||!function(){var i={preValue:[].concat(o(n.state.value))};t&&(0,b["default"])(i,t);var s=null,l=e;if(n.isLabelInValue()?n.halfCheckedValues.length&&n.halfCheckedValues.forEach(function(e){l.some(function(t){return t.value===e.value})||l.push(e)}):(s=e.map(function(e){return e.label}),l=l.map(function(e){return e.value})),i.clear&&r.treeCheckable){var u=n.renderedTreeData||r.children;i.allCheckedNodes=(0,C.flatToHierarchy)((0,C.filterAllCheckedData)(a,u))}n._savedValue=(0,C.isMultipleOrTags)(r)?l:l[0],r.onChange(n._savedValue,s,i)}()},isLabelInValue:function(){var e=this.props,t=e.treeCheckable,n=e.treeCheckStrictly,r=e.labelInValue;return!(!t||!n)||(r||!1)},renderTopControlNode:function(){var e=this,t=this.state.value,n=this.props,r=n.choiceTransitionName,o=n.prefixCls,a=n.maxTagTextLength;if((0,C.isSingleMode)(n)){var i=f["default"].createElement("span",{key:"placeholder",className:o+"-selection__placeholder"},n.placeholder);return t.length&&(i=f["default"].createElement("span",{key:"value"},t[0].label)),f["default"].createElement("span",{className:o+"-selection__rendered"},i)}var s=[];(0,C.isMultipleOrTags)(n)&&(s=t.map(function(t){var n=t.label,r=n;return a&&"string"==typeof n&&n.length>a&&(n=n.slice(0,a)+"..."),f["default"].createElement("li",c({style:C.UNSELECTABLE_STYLE},C.UNSELECTABLE_ATTRIBUTE,{onMouseDown:C.preventDefaultEvent,className:o+"-selection__choice",key:t.value,title:r}),f["default"].createElement("span",{className:o+"-selection__choice__remove",onClick:e.removeSelected.bind(e,t.value)}),f["default"].createElement("span",{className:o+"-selection__choice__content"},n))})),s.push(f["default"].createElement("li",{className:o+"-search "+o+"-search--inline",key:"__input"},this.getInputElement()));var l=o+"-selection__rendered";return(0,C.isMultipleOrTags)(n)&&r?f["default"].createElement(O["default"],{className:l,component:"ul",transitionName:r},s):f["default"].createElement("ul",{className:l},s)},renderTreeData:function(e){var t=e||this.props;if(t.treeData){if(e&&e.treeData===this.props.treeData&&this.renderedTreeData)return this._cachetreeData=!0,this.renderedTreeData;this._cachetreeData=!1;var n=t.treeData;if(t.treeDataSimpleMode){var r={id:"id",pId:"pId",rootPId:null};"[object Object]"===Object.prototype.toString.call(t.treeDataSimpleMode)&&(0,b["default"])(r,t.treeDataSimpleMode),n=(0,C.processSimpleTreeData)(t.treeData,r)}return u(n)}},render:function(){var e,t=this.props,n=(0,C.isMultipleOrTags)(t),r=this.state,o=t.className,i=t.disabled,s=t.allowClear,l=t.prefixCls,u=this.renderTopControlNode(),p={};(0,C.isMultipleOrTagsOrCombobox)(t)||(p={onKeyDown:this.onKeyDown,tabIndex:0});var d=(e={},a(e,o,!!o),a(e,l,1),a(e,l+"-open",r.open),a(e,l+"-focused",r.open||r.focused),a(e,l+"-disabled",i),a(e,l+"-enabled",!i),e),h=f["default"].createElement("span",{key:"clear",className:l+"-selection__clear",onClick:this.onClearSelection});return f["default"].createElement(w["default"],c({},t,{treeNodes:t.children,treeData:this.renderedTreeData,_cachetreeData:this._cachetreeData,_treeNodesStates:this._treeNodesStates,halfCheckedValues:this.halfCheckedValues,multiple:n,disabled:i,visible:r.open,inputValue:r.inputValue,_inputValue:null===t.inputValue,inputElement:this.getInputElement(),value:r.value,onDropdownVisibleChange:this.onDropdownVisibleChange,onSelect:this.onSelect,ref:"trigger"}),f["default"].createElement("span",{style:t.style,onClick:t.onClick,onBlur:this.onOuterBlur,onFocus:this.onOuterFocus,className:(0,m["default"])(d)},f["default"].createElement("span",c({ref:"selection",key:"selection",className:l+"-selection\n "+l+"-selection--"+(n?"multiple":"single"),role:"combobox","aria-autocomplete":"list","aria-haspopup":"true","aria-expanded":r.open},p),u,s&&!n?h:null,n||!t.showArrow?null:f["default"].createElement("span",{key:"arrow",className:l+"-arrow",style:{outline:"none"}},f["default"].createElement("b",null)),n?this.getSearchPlaceholderElement(!!this.state.inputValue||this.state.value.length):null)))}});_.SHOW_ALL=S,_.SHOW_PARENT=k,_.SHOW_CHILD=j,t["default"]=_,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i=n(1),s=r(i),l=n(4),u=r(l),c=n(2),p=r(c),f=n(14),d=r(f),h=n(114),y=r(h),v=n(113),m=n(11),g=r(m),b={bottomLeft:{points:["tl","bl"],offset:[0,4],overflow:{adjustX:0,adjustY:1}},topLeft:{points:["bl","tl"],offset:[0,-4],overflow:{adjustX:0,adjustY:1}}},P=s["default"].createClass({displayName:"SelectTrigger",propTypes:{dropdownMatchSelectWidth:i.PropTypes.bool,dropdownPopupAlign:i.PropTypes.object,visible:i.PropTypes.bool,filterTreeNode:i.PropTypes.any,treeNodes:i.PropTypes.any,inputValue:i.PropTypes.string,_inputValue:i.PropTypes.bool,prefixCls:i.PropTypes.string,popupClassName:i.PropTypes.string,children:i.PropTypes.any},getInitialState:function(){return{_expandedKeys:[],fireOnExpand:!1}},componentWillReceiveProps:function(e){e.inputValue&&e.inputValue!==this.props.inputValue&&this.setState({_expandedKeys:[],fireOnExpand:!1})},componentDidUpdate:function(){if(this.props.dropdownMatchSelectWidth&&this.props.visible){var e=this.getPopupDOMNode();e&&(e.style.width=u["default"].findDOMNode(this).offsetWidth+"px")}},onExpand:function(e){this.setState({_expandedKeys:e,fireOnExpand:!0})},getPopupEleRefs:function(){return this.popupEle&&this.popupEle.refs},getPopupDOMNode:function(){return this.refs.trigger.getPopupDomNode()},getDropdownTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=this.getDropdownPrefixCls()+"-"+e.animation),t},getDropdownPrefixCls:function(){return this.props.prefixCls+"-dropdown"},highlightTreeNode:function(e){var t=this.props,n=e.props[(0,v.labelCompatible)(t.treeNodeFilterProp)];return"string"==typeof n&&(t.inputValue&&n.indexOf(t.inputValue)>-1)},filterTreeNode:function O(e,t){if(!e)return!0;var O=this.props.filterTreeNode;return!O||!t.props.disabled&&O.call(this,e,t)},savePopupElement:function(e){this.popupEle=e},processTreeNode:function(e){var t=this,n=[];this._expandedKeys=[],(0,v.loopAllChildren)(e,function(e,r,o){t.filterTreeNode(t.props.inputValue,e)&&(n.push(o),t._expandedKeys.push(e.key))});var r=[];n.forEach(function(e){var t=e.split("-");t.reduce(function(e,t){var n=e+"-"+t;return r.indexOf(n)<0&&r.push(n),n})});var o=[];(0,v.loopAllChildren)(e,function(e,t,n){r.indexOf(n)>-1&&o.push({node:e,pos:n})});var a=(0,v.flatToHierarchy)(o),i=function l(e){return e.map(function(e){return e.children?s["default"].cloneElement(e.node,{},l(e.children)):e.node; })};return i(a)},renderTree:function(e,t,n,r){var o=this.props,i={multiple:r,prefixCls:o.prefixCls+"-tree",showIcon:o.treeIcon,showLine:o.treeLine,defaultExpandAll:o.treeDefaultExpandAll,filterTreeNode:this.highlightTreeNode};return o.treeCheckable?(o.inputValue&&!o._inputValue||(i._treeNodesStates=o._treeNodesStates),i.selectable=!1,i.checkable=o.treeCheckable,i.checkStrictly=o.treeCheckStrictly,i.onCheck=o.onSelect,o.treeCheckStrictly&&t.length?i.checkedKeys={checked:e,halfChecked:t}:i.checkedKeys=e):(i.selectedKeys=e,i.onSelect=o.onSelect),i.defaultExpandAll||(i.expandedKeys=e),i.autoExpandParent=!0,i.onExpand=this.onExpand,this._expandedKeys&&this._expandedKeys.length&&(i.expandedKeys=this._expandedKeys),this.state.fireOnExpand&&(i.expandedKeys=this.state._expandedKeys,i.autoExpandParent=!1),o.loadData&&(i.loadData=o.loadData),s["default"].createElement(y["default"],a({ref:this.savePopupElement},i),n)},render:function(){var e,t=this.props,n=t.multiple,r=this.getDropdownPrefixCls(),i=(e={},o(e,t.dropdownClassName,!!t.dropdownClassName),o(e,r+"--"+(n?"multiple":"single"),1),e),l=t.visible,u=n||t.combobox||!t.showSearch?null:s["default"].createElement("span",{className:r+"-search"},t.inputElement),c=function C(e){return g["default"].Children.toArray(e).map(function(e){return e&&e.props.children?s["default"].createElement(h.TreeNode,a({},e.props,{key:e.key}),C(e.props.children)):s["default"].createElement(h.TreeNode,a({},e.props,{key:e.key}))})},f=void 0;t._cachetreeData&&this.treeNodes?f=this.treeNodes:(f=c(t.treeData||t.treeNodes),this.treeNodes=f),t.inputValue&&(f=this.processTreeNode(f));var y=[],m=[];(0,v.loopAllChildren)(f,function(e){t.value.some(function(t){return t.value===(0,v.getValuePropValue)(e)})&&y.push(e.key),t.halfCheckedValues&&t.halfCheckedValues.some(function(t){return t.value===(0,v.getValuePropValue)(e)})&&m.push(e.key)});var P=void 0;f.length||(t.notFoundContent&&(P=s["default"].createElement("span",null,t.notFoundContent)),u||(l=!1));var O=s["default"].createElement("div",null,u,P?P:this.renderTree(y,m,f,n));return s["default"].createElement(d["default"],{action:t.disabled?[]:["click"],ref:"trigger",popupPlacement:"bottomLeft",builtinPlacements:b,popupAlign:this.props.dropdownPopupAlign,prefixCls:r,popupTransitionName:this.getDropdownTransitionName(),onPopupVisibleChange:t.onDropdownVisibleChange,popup:O,popupVisible:l,popupClassName:(0,p["default"])(i),popupStyle:t.dropdownStyle},this.props.children)}});t["default"]=P,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(384),a=r(o),i=n(112),s=r(i);a["default"].TreeNode=s["default"],t["default"]=a["default"],e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),c=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},p=n(1),f=r(p),d=n(10),h=r(d),y=n(2),v=r(y),m=n(115),g=function(e){function t(e){var n=this;a(this,t),c(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),["onKeyDown","onCheck"].forEach(function(e){n[e]=n[e].bind(n)}),this.contextmenuKeys=[],this.checkedKeysChange=!0,this.state={expandedKeys:this.getDefaultExpandedKeys(e),checkedKeys:this.getDefaultCheckedKeys(e),selectedKeys:this.getDefaultSelectedKeys(e),dragNodesKeys:"",dragOverNodeKey:"",dropNodeKey:""}}return i(t,e),u(t,[{key:"componentWillReceiveProps",value:function(e){var t=this.getDefaultExpandedKeys(e,!0),n=this.getDefaultCheckedKeys(e,!0),r=this.getDefaultSelectedKeys(e,!0),o={};t&&(o.expandedKeys=t),n&&(e.checkedKeys===this.props.checkedKeys?this.checkedKeysChange=!1:this.checkedKeysChange=!0,o.checkedKeys=n),r&&(o.selectedKeys=r),this.setState(o)}},{key:"onDragStart",value:function(e,t){this.dragNode=t,this.dragNodesKeys=this.getDragNodes(t);var n={dragNodesKeys:this.dragNodesKeys},r=this.getExpandedKeys(t,!1);r&&(this.getRawExpandedKeys(),n.expandedKeys=r),this.setState(n),this.props.onDragStart({event:e,node:t})}},{key:"onDragEnterGap",value:function(e,t){var n=(0,m.getOffset)(t.refs.selectHandle).top,r=t.refs.selectHandle.offsetHeight,o=e.pageY,a=2;return o>n+r-a?(this.dropPosition=1,1):o<n+a?(this.dropPosition=-1,-1):(this.dropPosition=0,0)}},{key:"onDragEnter",value:function(e,t){var n=this.onDragEnterGap(e,t);if(this.dragNode.props.eventKey===t.props.eventKey&&0===n)return void this.setState({dragOverNodeKey:""});var r={dragOverNodeKey:t.props.eventKey},a=this.getExpandedKeys(t,!0);a&&(this.getRawExpandedKeys(),r.expandedKeys=a),this.setState(r),this.props.onDragEnter({event:e,node:t,expandedKeys:a&&[].concat(o(a))||[].concat(o(this.state.expandedKeys))})}},{key:"onDragOver",value:function(e,t){this.props.onDragOver({event:e,node:t})}},{key:"onDragLeave",value:function(e,t){this.props.onDragLeave({event:e,node:t})}},{key:"onDrop",value:function(e,t){var n=t.props.eventKey;if(this.setState({dragOverNodeKey:"",dropNodeKey:n}),this.dragNodesKeys.indexOf(n)>-1)return console.warn&&console.warn("can not drop to dragNode(include it's children node)"),!1;var r=t.props.pos.split("-"),a={event:e,node:t,dragNode:this.dragNode,dragNodesKeys:[].concat(o(this.dragNodesKeys)),dropPosition:this.dropPosition+Number(r[r.length-1])};0!==this.dropPosition&&(a.dropToGap=!0),"expandedKeys"in this.props&&(a.rawExpandedKeys=[].concat(o(this._rawExpandedKeys))||[].concat(o(this.state.expandedKeys))),this.props.onDrop(a)}},{key:"onExpand",value:function(e){var t=this,n=!e.props.expanded,r="expandedKeys"in this.props,a=[].concat(o(this.state.expandedKeys)),i=a.indexOf(e.props.eventKey);if(n&&i===-1?a.push(e.props.eventKey):!n&&i>-1&&a.splice(i,1),r||this.setState({expandedKeys:a}),this.props.onExpand(a,{node:e,expanded:n}),n&&this.props.loadData)return this.props.loadData(e).then(function(){r||t.setState({expandedKeys:a})})}},{key:"onCheck",value:function(e){var t=this,n=!e.props.checked;e.props.halfChecked&&(n=!0);var r=e.props.eventKey,a=[].concat(o(this.state.checkedKeys)),i=a.indexOf(r),s={event:"check",node:e,checked:n};if(this.props.checkStrictly&&"checkedKeys"in this.props)n&&i===-1&&a.push(r),!n&&i>-1&&a.splice(i,1),s.checkedNodes=[],(0,m.loopAllChildren)(this.props.children,function(e,t,n,r){a.indexOf(r)!==-1&&s.checkedNodes.push(e)}),this.props.onCheck((0,m.getStrictlyValue)(a,this.props.checkedKeys.halfChecked),s);else{n&&i===-1&&!function(){t.treeNodesStates[e.props.pos].checked=!0;var n=[];Object.keys(t.treeNodesStates).forEach(function(e){t.treeNodesStates[e].checked&&n.push(e)}),(0,m.handleCheckState)(t.treeNodesStates,(0,m.filterParentPosition)(n),!0)}(),n||(this.treeNodesStates[e.props.pos].checked=!1,this.treeNodesStates[e.props.pos].halfChecked=!1,(0,m.handleCheckState)(this.treeNodesStates,[e.props.pos],!1));var l=(0,m.getCheck)(this.treeNodesStates);s.checkedNodes=l.checkedNodes,s.checkedNodesPositions=l.checkedNodesPositions,this.checkKeys=l,this._checkedKeys=a=l.checkedKeys,"checkedKeys"in this.props||this.setState({checkedKeys:a}),this.props.onCheck(a,s)}}},{key:"onSelect",value:function(e){var t=this.props,n=[].concat(o(this.state.selectedKeys)),r=e.props.eventKey,a=n.indexOf(r),i=void 0;a!==-1?(i=!1,n.splice(a,1)):(i=!0,t.multiple||(n.length=0),n.push(r));var s=[];n.length&&(0,m.loopAllChildren)(this.props.children,function(e){n.indexOf(e.key)!==-1&&s.push(e)});var l={event:"select",node:e,selected:i,selectedNodes:s};"selectedKeys"in this.props||this.setState({selectedKeys:n}),t.onSelect(n,l)}},{key:"onMouseEnter",value:function(e,t){this.props.onMouseEnter({event:e,node:t})}},{key:"onMouseLeave",value:function(e,t){this.props.onMouseLeave({event:e,node:t})}},{key:"onContextMenu",value:function(e,t){var n=[].concat(o(this.state.selectedKeys)),r=t.props.eventKey;this.contextmenuKeys.indexOf(r)===-1&&this.contextmenuKeys.push(r),this.contextmenuKeys.forEach(function(e){var t=n.indexOf(e);t!==-1&&n.splice(t,1)}),n.indexOf(r)===-1&&n.push(r),this.setState({selectedKeys:n}),this.props.onRightClick({event:e,node:t})}},{key:"onKeyDown",value:function(e){e.preventDefault()}},{key:"getFilterExpandedKeys",value:function(e,t,n){var r=e[t],o=[];e.autoExpandParent&&(0,m.loopAllChildren)(e.children,function(e,t,n,a){r.indexOf(a)>-1&&o.push(n)});var a=[];return(0,m.loopAllChildren)(e.children,function(t,r,i,s){n?a.push(s):e.autoExpandParent&&o.forEach(function(e){(e.split("-").length>i.split("-").length&&(0,m.isInclude)(i.split("-"),e.split("-"))||i===e)&&a.indexOf(s)===-1&&a.push(s)})}),a.length?a:r}},{key:"getDefaultExpandedKeys",value:function(e,t){var n=t?void 0:this.getFilterExpandedKeys(e,"defaultExpandedKeys",e.defaultExpandAll);return"expandedKeys"in e&&(n=(e.autoExpandParent?this.getFilterExpandedKeys(e,"expandedKeys",!1):e.expandedKeys)||[]),n}},{key:"getDefaultCheckedKeys",value:function(e,t){var n=t?void 0:e.defaultCheckedKeys;return"checkedKeys"in e&&(n=e.checkedKeys||[],e.checkStrictly&&(e.checkedKeys.checked?n=e.checkedKeys.checked:Array.isArray(e.checkedKeys)||(n=[]))),n}},{key:"getDefaultSelectedKeys",value:function(e,t){var n=function(t){return e.multiple?[].concat(o(t)):t.length?[t[0]]:t},r=t?void 0:n(e.defaultSelectedKeys);return"selectedKeys"in e&&(r=n(e.selectedKeys)),r}},{key:"getRawExpandedKeys",value:function(){!this._rawExpandedKeys&&"expandedKeys"in this.props&&(this._rawExpandedKeys=[].concat(o(this.state.expandedKeys)))}},{key:"getOpenTransitionName",value:function(){var e=this.props,t=e.openTransitionName,n=e.openAnimation;return t||"string"!=typeof n||(t=e.prefixCls+"-open-"+n),t}},{key:"getDragNodes",value:function(e){var t=[],n=e.props.pos.split("-");return(0,m.loopAllChildren)(this.props.children,function(r,o,a,i){var s=a.split("-");(e.props.pos===a||n.length<s.length&&(0,m.isInclude)(n,s))&&t.push(i)}),t}},{key:"getExpandedKeys",value:function(e,t){var n=e.props.eventKey,r=this.state.expandedKeys,a=r.indexOf(n),i=void 0;return a>-1&&!t?(i=[].concat(o(r)),i.splice(a,1),i):t&&r.indexOf(n)===-1?r.concat([n]):void 0}},{key:"filterTreeNode",value:function n(e){var n=this.props.filterTreeNode;return"function"==typeof n&&!e.props.disabled&&n.call(this,e)}},{key:"renderTreeNode",value:function(e,t){var n=arguments.length<=2||void 0===arguments[2]?0:arguments[2],r=n+"-"+t,o=e.key||r,a=this.state,i=this.props,s=i.selectable;e.props.hasOwnProperty("selectable")&&(s=e.props.selectable);var l={ref:"treeNode-"+o,root:this,eventKey:o,pos:r,selectable:s,loadData:i.loadData,onMouseEnter:i.onMouseEnter,onMouseLeave:i.onMouseLeave,onRightClick:i.onRightClick,prefixCls:i.prefixCls,showLine:i.showLine,showIcon:i.showIcon,draggable:i.draggable,dragOver:a.dragOverNodeKey===o&&0===this.dropPosition,dragOverGapTop:a.dragOverNodeKey===o&&this.dropPosition===-1,dragOverGapBottom:a.dragOverNodeKey===o&&1===this.dropPosition,expanded:a.expandedKeys.indexOf(o)!==-1,selected:a.selectedKeys.indexOf(o)!==-1,openTransitionName:this.getOpenTransitionName(),openAnimation:i.openAnimation,filterTreeNode:this.filterTreeNode.bind(this)};return i.checkable&&(l.checkable=i.checkable,i.checkStrictly?(a.checkedKeys&&(l.checked=a.checkedKeys.indexOf(o)!==-1||!1),i.checkedKeys.halfChecked?l.halfChecked=i.checkedKeys.halfChecked.indexOf(o)!==-1||!1:l.halfChecked=!1):(this.checkedKeys&&(l.checked=this.checkedKeys.indexOf(o)!==-1||!1),l.halfChecked=this.halfCheckedKeys.indexOf(o)!==-1),this.treeNodesStates[r]&&(0,h["default"])(l,this.treeNodesStates[r].siblingPosition)),f["default"].cloneElement(e,l)}},{key:"render",value:function(){var e=this,t=this.props,n={className:(0,v["default"])(t.className,t.prefixCls),role:"tree-node"};return t.focusable&&(n.tabIndex="0",n.onKeyDown=this.onKeyDown),t.checkable&&(this.checkedKeysChange||t.loadData)&&(t.checkStrictly?(this.treeNodesStates={},(0,m.loopAllChildren)(t.children,function(t,n,r,o,a){e.treeNodesStates[r]={siblingPosition:a}})):t._treeNodesStates?(this.treeNodesStates=t._treeNodesStates.treeNodesStates,this.halfCheckedKeys=t._treeNodesStates.halfCheckedKeys,this.checkedKeys=t._treeNodesStates.checkedKeys):!function(){var n=e.state.checkedKeys,r=void 0;!t.loadData&&e.checkKeys&&e._checkedKeys&&(0,m.arraysEqual)(e._checkedKeys,n)?r=e.checkKeys:!function(){var o=[];e.treeNodesStates={},(0,m.loopAllChildren)(t.children,function(t,r,a,i,s){e.treeNodesStates[a]={node:t,key:i,checked:!1,halfChecked:!1,siblingPosition:s},n.indexOf(i)!==-1&&(e.treeNodesStates[a].checked=!0,o.push(a))}),(0,m.handleCheckState)(e.treeNodesStates,(0,m.filterParentPosition)(o),!0),r=(0,m.getCheck)(e.treeNodesStates)}(),e.halfCheckedKeys=r.halfCheckedKeys,e.checkedKeys=r.checkedKeys}()),f["default"].createElement("ul",l({},n,{unselectable:!0,ref:"tree"}),f["default"].Children.map(t.children,this.renderTreeNode,this))}}]),t}(f["default"].Component);g.propTypes={prefixCls:p.PropTypes.string,children:p.PropTypes.any,showLine:p.PropTypes.bool,showIcon:p.PropTypes.bool,selectable:p.PropTypes.bool,multiple:p.PropTypes.bool,checkable:p.PropTypes.oneOfType([p.PropTypes.bool,p.PropTypes.node]),_treeNodesStates:p.PropTypes.object,checkStrictly:p.PropTypes.bool,draggable:p.PropTypes.bool,autoExpandParent:p.PropTypes.bool,defaultExpandAll:p.PropTypes.bool,defaultExpandedKeys:p.PropTypes.arrayOf(p.PropTypes.string),expandedKeys:p.PropTypes.arrayOf(p.PropTypes.string),defaultCheckedKeys:p.PropTypes.arrayOf(p.PropTypes.string),checkedKeys:p.PropTypes.oneOfType([p.PropTypes.arrayOf(p.PropTypes.string),p.PropTypes.object]),defaultSelectedKeys:p.PropTypes.arrayOf(p.PropTypes.string),selectedKeys:p.PropTypes.arrayOf(p.PropTypes.string),onExpand:p.PropTypes.func,onCheck:p.PropTypes.func,onSelect:p.PropTypes.func,loadData:p.PropTypes.func,onMouseEnter:p.PropTypes.func,onMouseLeave:p.PropTypes.func,onRightClick:p.PropTypes.func,onDragStart:p.PropTypes.func,onDragEnter:p.PropTypes.func,onDragOver:p.PropTypes.func,onDragLeave:p.PropTypes.func,onDrop:p.PropTypes.func,filterTreeNode:p.PropTypes.func,openTransitionName:p.PropTypes.string,openAnimation:p.PropTypes.oneOfType([p.PropTypes.string,p.PropTypes.object])},g.defaultProps={prefixCls:"rc-tree",showLine:!1,showIcon:!0,selectable:!0,multiple:!1,checkable:!1,checkStrictly:!1,draggable:!1,autoExpandParent:!0,defaultExpandAll:!1,defaultExpandedKeys:[],defaultCheckedKeys:[],defaultSelectedKeys:[],onExpand:s,onCheck:s,onSelect:s,onDragStart:s,onDragEnter:s,onDragOver:s,onDragLeave:s,onDrop:s},t["default"]=g,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},l=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),u=function(e,t,n){for(var r=!0;r;){var o=e,a=t,i=n;r=!1,null===o&&(o=Function.prototype);var s=Object.getOwnPropertyDescriptor(o,a);if(void 0!==s){if("value"in s)return s.value;var l=s.get;if(void 0===l)return;return l.call(i)}var u=Object.getPrototypeOf(o);if(null===u)return;e=u,t=a,n=i,r=!0,s=u=void 0}},c=n(1),p=r(c),f=n(10),d=r(f),h=n(2),y=r(h),v=n(8),m=r(v),g=n(115),b="undefined"!=typeof window?(0,g.browser)(window.navigator):"",P=/.*(IE|Edge).+/.test(b),O="---",C=function(e){function t(e){var n=this;a(this,t),u(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),["onExpand","onCheck","onContextMenu","onMouseEnter","onMouseLeave","onDragStart","onDragEnter","onDragOver","onDragLeave","onDrop"].forEach(function(e){n[e]=n[e].bind(n)}),this.state={dataLoading:!1,dragNodeHighlight:!1}}return i(t,e),l(t,[{key:"componentDidMount",value:function(){this.props.root._treeNodeInstances||(this.props.root._treeNodeInstances=[]),this.props.root._treeNodeInstances.push(this)}},{key:"onCheck",value:function(){this.props.root.onCheck(this)}},{key:"onSelect",value:function(){this.props.root.onSelect(this)}},{key:"onMouseEnter",value:function(e){e.preventDefault(),this.props.root.onMouseEnter(e,this)}},{key:"onMouseLeave",value:function(e){e.preventDefault(),this.props.root.onMouseLeave(e,this)}},{key:"onContextMenu",value:function(e){e.preventDefault(),this.props.root.onContextMenu(e,this)}},{key:"onDragStart",value:function(e){e.stopPropagation(),this.setState({dragNodeHighlight:!0}),this.props.root.onDragStart(e,this);try{e.dataTransfer.setData("text/plain","firefox-need-it")}finally{}}},{key:"onDragEnter",value:function(e){e.preventDefault(),e.stopPropagation(),this.props.root.onDragEnter(e,this)}},{key:"onDragOver",value:function(e){return e.preventDefault(),e.stopPropagation(),this.props.root.onDragOver(e,this),!1}},{key:"onDragLeave",value:function(e){e.stopPropagation(),this.props.root.onDragLeave(e,this)}},{key:"onDrop",value:function(e){e.preventDefault(),e.stopPropagation(),this.setState({dragNodeHighlight:!1}),this.props.root.onDrop(e,this)}},{key:"onExpand",value:function(){var e=this,t=this.props.root.onExpand(this);t&&"object"==typeof t&&!function(){var n=function(t){e.setState({dataLoading:t})};n(!0),t.then(function(){n(!1)},function(){n(!1)})}()}},{key:"onKeyDown",value:function(e){e.preventDefault()}},{key:"renderSwitcher",value:function(e,t){var n=e.prefixCls,r=o({},n+"-switcher",!0);return e.showLine?"0-0"===e.pos?r[n+"-roots_"+t]=!0:(r[n+"-center_"+t]=!e.last,r[n+"-bottom_"+t]=e.last):r[n+"-noline_"+t]=!0,e.disabled?(r[n+"-switcher-disabled"]=!0,p["default"].createElement("span",{className:(0,y["default"])(r)})):p["default"].createElement("span",{className:(0,y["default"])(r),onClick:this.onExpand})}},{key:"renderCheckbox",value:function(e){var t=e.prefixCls,n=o({},t+"-checkbox",!0);e.checked?n[t+"-checkbox-checked"]=!0:e.halfChecked&&(n[t+"-checkbox-indeterminate"]=!0);var r=null;return"boolean"!=typeof e.checkable&&(r=e.checkable),e.disabled||e.disableCheckbox?(n[t+"-checkbox-disabled"]=!0,p["default"].createElement("span",{ref:"checkbox",className:(0,y["default"])(n)},r)):p["default"].createElement("span",{ref:"checkbox",className:(0,y["default"])(n),onClick:this.onCheck},r)}},{key:"renderChildren",value:function(e){var n=this.renderFirst;this.renderFirst=1;var r=!0;!n&&e.expanded&&(r=!1);var a=e.children,i=a,l=void 0;if(Array.isArray(a)&&(l=a.every(function(e){return e.type===t})),a&&(a.type===t||l)){var u,c=(u={},o(u,e.prefixCls+"-child-tree",!0),o(u,e.prefixCls+"-child-tree-open",e.expanded),u);e.showLine&&(c[e.prefixCls+"-line"]=!e.last);var f={};e.openTransitionName?f.transitionName=e.openTransitionName:"object"==typeof e.openAnimation&&(f.animation=(0,d["default"])({},e.openAnimation),r||delete f.animation.appear),i=p["default"].createElement(m["default"],s({},f,{showProp:"expanded",transitionAppear:r,component:""}),p["default"].createElement("ul",{className:(0,y["default"])(c),expanded:e.expanded},p["default"].Children.map(a,function(t,n){return e.root.renderTreeNode(t,n,e.pos)},e.root)))}return i}},{key:"render",value:function(){var e,t=this,n=this.props,r=n.prefixCls,a=n.expanded?"open":"close",i=(e={},o(e,r+"-iconEle",!0),o(e,r+"-icon_loading",this.state.dataLoading),o(e,r+"-icon__"+a,!0),e),l=!0,u=n.title,c=this.renderChildren(n);c&&c!==n.children||(c=null,n.loadData&&!n.isLeaf||(l=!1)),n.expanded||(c=null);var f=function(){var e=n.showIcon||n.loadData&&t.state.dataLoading?p["default"].createElement("span",{className:(0,y["default"])(i)}):null,o=p["default"].createElement("span",{className:r+"-title"},u),a={};return n.disabled||((n.selected||t.state.dragNodeHighlight)&&(a.className=r+"-node-selected"),a.onClick=function(e){e.preventDefault(),n.selectable&&t.onSelect()},n.onRightClick&&(a.onContextMenu=t.onContextMenu),n.onMouseEnter&&(a.onMouseEnter=t.onMouseEnter),n.onMouseLeave&&(a.onMouseLeave=t.onMouseLeave),n.draggable&&(P&&(a.href="#"),a.draggable=!0,a["aria-grabbed"]=!0,a.onDragStart=t.onDragStart)),p["default"].createElement("a",s({ref:"selectHandle",title:"string"==typeof u?u:""},a),e,o)},d={};n.draggable&&(d.onDragEnter=this.onDragEnter,d.onDragOver=this.onDragOver,d.onDragLeave=this.onDragLeave,d.onDrop=this.onDrop);var h="",v="";n.disabled?h=r+"-treenode-disabled":n.dragOver?v="drag-over":n.dragOverGapTop?v="drag-over-gap-top":n.dragOverGapBottom&&(v="drag-over-gap-bottom");var m=n.filterTreeNode(this)?"filter-node":"",g=function(){var e,t=(e={},o(e,r+"-switcher",!0),o(e,r+"-switcher-noop",!0),e);return n.showLine?(t[r+"-center_docu"]=!n.last,t[r+"-bottom_docu"]=n.last):t[r+"-noline_docu"]=!0,p["default"].createElement("span",{className:(0,y["default"])(t)})};return p["default"].createElement("li",s({},d,{ref:"li",className:(0,y["default"])(n.className,h,v,m)}),l?this.renderSwitcher(n,a):g(),n.checkable?this.renderCheckbox(n):null,f(),c)}}]),t}(p["default"].Component);C.isTreeNode=1,C.propTypes={prefixCls:c.PropTypes.string,disabled:c.PropTypes.bool,disableCheckbox:c.PropTypes.bool,expanded:c.PropTypes.bool,isLeaf:c.PropTypes.bool,root:c.PropTypes.object,onSelect:c.PropTypes.func},C.defaultProps={title:O},t["default"]=C,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(4),l=r(s),u=n(283),c=r(u),p=n(8),f=r(p),d=n(390),h=r(d),y=n(116),v=r(y),m=i["default"].createClass({displayName:"Popup",propTypes:{visible:a.PropTypes.bool,style:a.PropTypes.object,getClassNameFromAlign:a.PropTypes.func,onAlign:a.PropTypes.func,getRootDomNode:a.PropTypes.func,onMouseEnter:a.PropTypes.func,align:a.PropTypes.any,destroyPopupOnHide:a.PropTypes.bool,className:a.PropTypes.string,prefixCls:a.PropTypes.string,onMouseLeave:a.PropTypes.func},componentDidMount:function(){this.rootNode=this.getPopupDomNode()},onAlign:function(e,t){var n=this.props,r=n.getClassNameFromAlign(n.align),o=n.getClassNameFromAlign(t);r!==o&&(this.currentAlignClassName=o,e.className=this.getClassName(o)),n.onAlign(e,t)},getPopupDomNode:function(){return l["default"].findDOMNode(this.refs.popup)},getTarget:function(){return this.props.getRootDomNode()},getMaskTransitionName:function(){var e=this.props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.props,t=e.transitionName;return!t&&e.animation&&(t=e.prefixCls+"-"+e.animation),t},getClassName:function(e){return this.props.prefixCls+" "+this.props.className+" "+e},getPopupElement:function(){var e=this.props,t=e.align,n=e.style,r=e.visible,a=e.prefixCls,s=e.destroyPopupOnHide,l=this.getClassName(this.currentAlignClassName||e.getClassNameFromAlign(t)),u=a+"-hidden";r||(this.currentAlignClassName=null);var p=o({},n,this.getZIndexStyle()),d={className:l,prefixCls:a,ref:"popup",onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:p};return s?i["default"].createElement(f["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName()},r?i["default"].createElement(c["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,align:t,onAlign:this.onAlign},i["default"].createElement(h["default"],o({visible:!0},d),e.children)):null):i["default"].createElement(f["default"],{component:"",exclusive:!0,transitionAppear:!0,transitionName:this.getTransitionName(),showProp:"xVisible"},i["default"].createElement(c["default"],{target:this.getTarget,key:"popup",ref:this.saveAlign,monitorWindowResize:!0,xVisible:r,childrenProps:{visible:"xVisible"},disabled:!r,align:t,onAlign:this.onAlign},i["default"].createElement(h["default"],o({hiddenClassName:u},d),e.children)))},getZIndexStyle:function(){var e={},t=this.props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getMaskElement:function(){var e=this.props,t=void 0;if(e.mask){var n=this.getMaskTransitionName();t=i["default"].createElement(v["default"],{style:this.getZIndexStyle(),key:"mask",className:e.prefixCls+"-mask",hiddenClassName:e.prefixCls+"-mask-hidden",visible:e.visible}),n&&(t=i["default"].createElement(f["default"],{key:"mask",showProp:"visible",transitionAppear:!0,component:"",transitionName:n},t))}return t},saveAlign:function(e){this.alignInstance=e},render:function(){return i["default"].createElement("div",null,this.getMaskElement(),this.getPopupElement())}});t["default"]=m,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(116),s=r(i),l=a["default"].createClass({displayName:"PopupInner",propTypes:{hiddenClassName:o.PropTypes.string,className:o.PropTypes.string,prefixCls:o.PropTypes.string,onMouseEnter:o.PropTypes.func,onMouseLeave:o.PropTypes.func,children:o.PropTypes.any},render:function(){var e=this.props,t=e.className;return e.visible||(t+=" "+e.hiddenClassName),a["default"].createElement("div",{className:t,onMouseEnter:e.onMouseEnter,onMouseLeave:e.onMouseLeave,style:e.style},a["default"].createElement(s["default"],{className:e.prefixCls+"-content",visible:e.visible},e.children))}});t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}function a(){return""}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},l=n(1),u=r(l),c=n(4),p=r(c),f=n(46),d=r(f),h=n(118),y=r(h),v=n(23),m=r(v),g=n(389),b=r(g),P=n(392),O=["onClick","onMouseDown","onTouchStart","onMouseEnter","onMouseLeave","onFocus","onBlur"],C=u["default"].createClass({displayName:"Trigger",propTypes:{action:l.PropTypes.any,showAction:l.PropTypes.any,hideAction:l.PropTypes.any,getPopupClassNameFromAlign:l.PropTypes.any,onPopupVisibleChange:l.PropTypes.func,afterPopupVisibleChange:l.PropTypes.func,popup:l.PropTypes.node.isRequired,popupStyle:l.PropTypes.object,prefixCls:l.PropTypes.string,popupClassName:l.PropTypes.string,popupPlacement:l.PropTypes.string,builtinPlacements:l.PropTypes.object,popupTransitionName:l.PropTypes.string,popupAnimation:l.PropTypes.any,mouseEnterDelay:l.PropTypes.number,mouseLeaveDelay:l.PropTypes.number,zIndex:l.PropTypes.number,focusDelay:l.PropTypes.number,blurDelay:l.PropTypes.number,getPopupContainer:l.PropTypes.func,destroyPopupOnHide:l.PropTypes.bool,mask:l.PropTypes.bool,onPopupAlign:l.PropTypes.func,popupAlign:l.PropTypes.object,popupVisible:l.PropTypes.bool,maskTransitionName:l.PropTypes.string,maskAnimation:l.PropTypes.string},getDefaultProps:function(){return{prefixCls:"rc-trigger-popup",getPopupClassNameFromAlign:a,onPopupVisibleChange:o,afterPopupVisibleChange:o,onPopupAlign:o,popupClassName:"",mouseEnterDelay:0,mouseLeaveDelay:.1,focusDelay:0,blurDelay:.15,popupStyle:{},destroyPopupOnHide:!1,popupAlign:{},defaultPopupVisible:!1,mask:!1,action:[],showAction:[],hideAction:[]}},getInitialState:function(){var e=this.props,t=void 0;return t="popupVisible"in e?!!e.popupVisible:!!e.defaultPopupVisible,{popupVisible:t}},componentDidMount:function(){this.componentDidUpdate({},{popupVisible:this.state.popupVisible})},componentWillReceiveProps:function(e){"popupVisible"in e&&this.setState({popupVisible:!!e.popupVisible})},componentDidUpdate:function(e,t){var n=this,r=this.props,o=this.state;if(this.popupRendered){var a=function(){var e=n;return e.popupInstance=p["default"].unstable_renderSubtreeIntoContainer(n,n.getPopupElement(),n.getPopupContainer(),function(){this.isMounted()?e.popupDomNode=this.getPopupDomNode():e.popupDomNode=null,t.popupVisible!==o.popupVisible&&r.afterPopupVisibleChange(o.popupVisible)}),n.isClickToHide()&&o.popupVisible?(n.clickOutsideHandler||(n.clickOutsideHandler=(0,m["default"])(document,"mousedown",n.onDocumentClick),n.touchOutsideHandler=(0,m["default"])(document,"touchstart",n.onDocumentClick)),{v:void 0}):void(n.clickOutsideHandler&&(n.clickOutsideHandler.remove(),n.touchOutsideHandler.remove(),n.clickOutsideHandler=null,n.touchOutsideHandler=null))}();if("object"===("undefined"==typeof a?"undefined":s(a)))return a.v}},componentWillUnmount:function(){var e=this.popupContainer;e&&(p["default"].unmountComponentAtNode(e),e.parentNode.removeChild(e),this.popupContainer=null),this.clearDelayTimer(),this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.touchOutsideHandler.remove(),this.clickOutsideHandler=null,this.touchOutsideHandler=null)},onMouseEnter:function(){this.delaySetPopupVisible(!0,this.props.mouseEnterDelay)},onMouseLeave:function(e){e.relatedTarget&&!e.relatedTarget.setTimeout&&(0,y["default"])(this.popupContainer,e.relatedTarget)||this.delaySetPopupVisible(!1,this.props.mouseLeaveDelay)},onFocus:function(){this.clearDelayTimer(),this.isFocusToShow()&&(this.focusTime=Date.now(),this.delaySetPopupVisible(!0,this.props.focusDelay))},onMouseDown:function(){this.preClickTime=Date.now()},onTouchStart:function(){this.preTouchTime=Date.now()},onBlur:function(){this.clearDelayTimer(),this.isBlurToHide()&&this.delaySetPopupVisible(!1,this.props.blurDelay)},onClick:function(e){if(this.focusTime){var t=void 0;if(this.preClickTime&&this.preTouchTime?t=Math.min(this.preClickTime,this.preTouchTime):this.preClickTime?t=this.preClickTime:this.preTouchTime&&(t=this.preTouchTime),Math.abs(t-this.focusTime)<20)return;this.focusTime=0}this.preClickTime=0,this.preTouchTime=0,e.preventDefault();var n=!this.state.popupVisible;(this.isClickToHide()&&!n||n&&this.isClickToShow())&&this.setPopupVisible(!this.state.popupVisible)},onDocumentClick:function(e){var t=e.target,n=(0,c.findDOMNode)(this),r=this.getPopupDomNode();(0,y["default"])(n,t)||(0,y["default"])(r,t)||this.setPopupVisible(!1)},getPopupDomNode:function(){return this.popupDomNode},getRootDomNode:function(){return p["default"].findDOMNode(this)},getPopupContainer:function(){if(!this.popupContainer){this.popupContainer=document.createElement("div"); var e=this.props.getPopupContainer?this.props.getPopupContainer((0,c.findDOMNode)(this)):document.body;e.appendChild(this.popupContainer)}return this.popupContainer},getPopupClassNameFromAlign:function(e){var t=[],n=this.props,r=n.popupPlacement,o=n.builtinPlacements,a=n.prefixCls;return r&&o&&t.push((0,P.getPopupClassNameFromAlign)(o,a,e)),n.getPopupClassNameFromAlign&&t.push(n.getPopupClassNameFromAlign(e)),t.join(" ")},getPopupAlign:function(){var e=this.props,t=e.popupPlacement,n=e.popupAlign,r=e.builtinPlacements;return t&&r?(0,P.getAlignFromPlacement)(r,t,n):n},getPopupElement:function(){var e=this.props,t=this.state,n={};return this.isMouseEnterToShow()&&(n.onMouseEnter=this.onMouseEnter),this.isMouseLeaveToHide()&&(n.onMouseLeave=this.onMouseLeave),u["default"].createElement(b["default"],i({prefixCls:e.prefixCls,destroyPopupOnHide:e.destroyPopupOnHide,visible:t.popupVisible,className:e.popupClassName,action:e.action,align:this.getPopupAlign(),onAlign:e.onPopupAlign,animation:e.popupAnimation,getClassNameFromAlign:this.getPopupClassNameFromAlign},n,{getRootDomNode:this.getRootDomNode,style:e.popupStyle,mask:e.mask,zIndex:e.zIndex,transitionName:e.popupTransitionName,maskAnimation:e.maskAnimation,maskTransitionName:e.maskTransitionName}),e.popup)},setPopupVisible:function(e){this.clearDelayTimer(),this.state.popupVisible!==e&&("popupVisible"in this.props||this.setState({popupVisible:e}),this.props.onPopupVisibleChange(e))},delaySetPopupVisible:function(e,t){var n=this,r=1e3*t;this.clearDelayTimer(),r?this.delayTimer=setTimeout(function(){n.setPopupVisible(e),n.clearDelayTimer()},r):this.setPopupVisible(e)},clearDelayTimer:function(){this.delayTimer&&(clearTimeout(this.delayTimer),this.delayTimer=null)},isClickToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isClickToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("click")!==-1||n.indexOf("click")!==-1},isMouseEnterToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("hover")!==-1||n.indexOf("mouseEnter")!==-1},isMouseLeaveToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("hover")!==-1||n.indexOf("mouseLeave")!==-1},isFocusToShow:function(){var e=this.props,t=e.action,n=e.showAction;return t.indexOf("focus")!==-1||n.indexOf("focus")!==-1},isBlurToHide:function(){var e=this.props,t=e.action,n=e.hideAction;return t.indexOf("focus")!==-1||n.indexOf("blur")!==-1},forcePopupAlign:function(){this.state.popupVisible&&this.popupInstance&&this.popupInstance.alignInstance&&this.popupInstance.alignInstance.forceAlign()},render:function(){this.popupRendered=this.popupRendered||this.state.popupVisible;var e=this.props,t=e.children,n=u["default"].Children.only(t),r=n.props||{},o={};return(this.isClickToHide()||this.isClickToShow())&&(o.onClick=(0,d["default"])(this.onClick,r.onClick),o.onMouseDown=(0,d["default"])(this.onMouseDown,r.onMouseDown),o.onTouchStart=(0,d["default"])(this.onTouchStart,r.onTouchStart)),this.isMouseEnterToShow()&&(o.onMouseEnter=(0,d["default"])(this.onMouseEnter,r.onMouseEnter)),this.isMouseLeaveToHide()&&(o.onMouseLeave=(0,d["default"])(this.onMouseLeave,r.onMouseLeave)),(this.isFocusToShow()||this.isBlurToHide())&&(o.onFocus=(0,d["default"])(this.onFocus,r.onFocus),o.onBlur=(0,d["default"])(this.onBlur,r.onBlur)),O.forEach(function(t){var n=void 0;n=e[t]&&o[t]?(0,d["default"])(e[t],o[t]):e[t]||o[t],n&&(o[t]=n)}),u["default"].cloneElement(n,o)}});t["default"]=C,e.exports=t["default"]},function(e,t){"use strict";function n(e,t){return e[0]===t[0]&&e[1]===t[1]}function r(e,t,n){var r=e[t]||{};return a({},r,n)}function o(e,t,r){var o=r.points;for(var a in e)if(e.hasOwnProperty(a)&&n(e[a].points,o))return t+"-placement-"+a;return""}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e};t.getAlignFromPlacement=r,t.getPopupClassNameFromAlign=o},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(397),a=r(o),i=n(1),s=r(i),l=n(117),u=r(l),c=s["default"].createClass({displayName:"AjaxUploader",propTypes:{prefixCls:i.PropTypes.string,multiple:i.PropTypes.bool,onStart:i.PropTypes.func,data:i.PropTypes.oneOfType([i.PropTypes.object,i.PropTypes.func]),headers:i.PropTypes.object,beforeUpload:i.PropTypes.func,withCredentials:i.PropTypes.bool},getInitialState:function(){return{disabled:!1,uid:(0,u["default"])()}},onChange:function(e){if(!this.state.disabled){this.setState({disabled:!0});var t=e.target.files;this.uploadFiles(t)}},onClick:function(){var e=this.refs.file;e&&e.click()},onKeyDown:function(e){"Enter"===e.key&&this.onClick()},onFileDrop:function(e){if("dragover"===e.type)return void e.preventDefault();if(!this.state.disabled){var t=e.dataTransfer.files;this.uploadFiles(t),e.preventDefault()}},uploadFiles:function(e){var t=Array.prototype.slice.call(e);this.props.multiple||(t=t.slice(0,1));var n=t.length;if(n>0){for(var r=0;r<n;r++){var o=t[r];o.uid=(0,u["default"])(),this.upload(o)}this.props.multiple?this.props.onStart(t):this.props.onStart(t[0])}},upload:function(e){var t=this,n=this.props;if(!n.beforeUpload)return this.post(e);var r=n.beforeUpload(e);r&&r.then?r.then(function(n){"[object File]"===Object.prototype.toString.call(n)?t.post(n):t.post(e)},function(){t._reset()}):r!==!1?this.post(e):this._reset()},post:function(e){var t=this,n=this.props,r=n.data;"function"==typeof r&&(r=r(e)),(0,a["default"])({action:n.action,filename:n.name,file:e,data:r,headers:n.headers,withCredentials:n.withCredentials,onProgress:function(t){n.onProgress(t,e)},onSuccess:function(r){n.onSuccess(r,e),t._reset()},onError:function(r,o){n.onError(r,o,e),t._reset()}})},_reset:function(){this.setState({disabled:!1,uid:(0,u["default"])()})},render:function(){var e=this.props;return s["default"].createElement("span",{onClick:this.onClick,onKeyDown:this.onKeyDown,onDrop:this.onFileDrop,onDragOver:this.onFileDrop,role:"button",tabIndex:"0",className:this.state.disabled?this.props.prefixCls+" "+e.prefixCls+"-disabled":""+this.props.prefixCls},s["default"].createElement("input",{type:"file",ref:"file",key:this.state.uid,disabled:this.state.disabled,style:{display:"none"},accept:e.accept,multiple:this.props.multiple,onChange:this.onChange}),e.children)}});t["default"]=c,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(4),l=r(s),u=n(117),c=r(u),p=n(398),f=r(p),d={position:"absolute",top:0,opacity:0,filter:"alpha(opacity=0)",left:0,zIndex:9999},h=i["default"].createClass({displayName:"IframeUploader",propTypes:{prefixCls:a.PropTypes.string,onStart:a.PropTypes.func,multiple:a.PropTypes.bool,children:a.PropTypes.any,data:a.PropTypes.oneOfType([a.PropTypes.object,a.PropTypes.func]),action:a.PropTypes.string,name:a.PropTypes.string},getInitialState:function(){return{disabled:!1}},componentDidMount:function(){this.updateIframeWH(),this.initIframe()},componentDidUpdate:function(){this.updateIframeWH()},onLoad:function(){if(this.state.disabled){var e=this.props,t=void 0,n=this.file;try{var r=this.getIframeDocument(),o=r.getElementsByTagName("script")[0];o&&o.parentNode===r.body&&r.body.removeChild(o),t=r.body.innerHTML,e.onSuccess(t,n)}catch(a){(0,f["default"])(!1,"cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload"),t="cross-domain",e.onError(a,null,n)}this.enableIframe(),this.initIframe()}},onChange:function(){var e=this.getFormInputNode(),t=this.file={uid:(0,c["default"])(),name:e.value};this.props.onStart(this.getFileForMultiple(t));var n=this.getFormNode(),r=this.getFormDataNode(),o=this.props.data;"function"==typeof o&&(o=o(t));var a=[];for(var i in o)o.hasOwnProperty(i)&&a.push('<input name="'+i+'" value="'+o[i]+'"/>');r.innerHTML=a.join(""),this.disabledIframe(),n.submit(),r.innerHTML=""},getIframeNode:function(){return this.refs.iframe},getIframeDocument:function(){return this.getIframeNode().contentDocument},getFormNode:function(){return this.getIframeDocument().getElementById("form")},getFormInputNode:function(){return this.getIframeDocument().getElementById("input")},getFormDataNode:function(){return this.getIframeDocument().getElementById("data")},getFileForMultiple:function(e){return this.props.multiple?[e]:e},getIframeHTML:function(e){var t="",n="";return e&&(t='<script>document.domain="'+e+'";</script>',n='<input name="_documentDomain" value="'+e+'" />'),'\n <!DOCTYPE html>\n <html>\n <head>\n <meta http-equiv="X-UA-Compatible" content="IE=edge" />\n <style>\n body,html {padding:0;margin:0;border:0;overflow:hidden;}\n </style>\n '+t+'\n </head>\n <body>\n <form method="post"\n encType="multipart/form-data"\n action="'+this.props.action+'" id="form" style="display:block;height:9999px;position:relative;overflow:hidden;">\n <input id="input" type="file"\n name="'+this.props.name+'"\n style="position:absolute;top:0;right:0;height:9999px;font-size:9999px;cursor:pointer;"/>\n '+n+'\n <span id="data"></span>\n </form>\n </body>\n </html>\n '},initIframeSrc:function(){this.domain&&(this.getIframeNode().src="javascript:void((function(){\n var d = document;\n d.open();\n d.domain='"+this.domain+"';\n d.write('');\n d.close();\n })())")},initIframe:function(){var e=this.getIframeNode(),t=e.contentWindow,n=void 0;this.domain=this.domain||"",this.initIframeSrc();try{n=t.document}catch(r){this.domain=document.domain,this.initIframeSrc(),t=e.contentWindow,n=t.document}n.open("text/html","replace"),n.write(this.getIframeHTML(this.domain)),n.close(),this.getFormInputNode().onchange=this.onChange},enableIframe:function(){this.state.disabled&&(this.state.disabled=!1,this.setState({disabled:!1}))},disabledIframe:function(){this.state.disabled||(this.state.disabled=!0,this.setState({disabled:!0}))},updateIframeWH:function(){var e=l["default"].findDOMNode(this),t=this.getIframeNode();t.style.height=e.offsetHeight+"px",t.style.width=e.offsetWidth+"px"},render:function(){var e=o({},d,{display:this.state.disabled?"none":""});return i["default"].createElement("span",{className:this.state.disabled?this.props.prefixCls+" "+this.props.prefixCls+"-disabled":""+this.props.prefixCls,style:{position:"relative",zIndex:0}},i["default"].createElement("iframe",{ref:"iframe",onLoad:this.onLoad,style:e}),this.props.children)}});t["default"]=h,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}function o(){}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),i=r(a),s=n(393),l=r(s),u=n(394),c=r(u),p=i["default"].createClass({displayName:"Upload",propTypes:{prefixCls:a.PropTypes.string,action:a.PropTypes.string,name:a.PropTypes.string,multipart:a.PropTypes.bool,onError:a.PropTypes.func,onSuccess:a.PropTypes.func,onProgress:a.PropTypes.func,onStart:a.PropTypes.func,data:a.PropTypes.oneOfType([a.PropTypes.object,a.PropTypes.func]),headers:a.PropTypes.object,accept:a.PropTypes.string,multiple:a.PropTypes.bool,beforeUpload:a.PropTypes.func,onReady:a.PropTypes.func,withCredentials:a.PropTypes.bool,supportServerRender:a.PropTypes.bool},getDefaultProps:function(){return{prefixCls:"rc-upload",data:{},headers:{},name:"file",multipart:!1,onProgress:o,onReady:o,onStart:o,onError:o,onSuccess:o,supportServerRender:!1,multiple:!1,beforeUpload:null,withCredentials:!1}},getInitialState:function(){return{Component:null}},componentDidMount:function(){this.props.supportServerRender&&this.setState({Component:this.getComponent()},this.props.onReady)},getComponent:function(){return"undefined"!=typeof FormData?l["default"]:c["default"]},render:function(){if(this.props.supportServerRender){var e=this.state.Component;return e?i["default"].createElement(e,this.props):null}var t=this.getComponent();return i["default"].createElement(t,this.props)}});t["default"]=p,e.exports=t["default"]},function(e,t,n){"use strict";e.exports=n(395)},function(e,t){"use strict";function n(e,t){var n="cannot post "+e.action+" "+t.status+"'",r=new Error(n);return r.status=t.status,r.method="post",r.url=e.action,r}function r(e){var t=e.responseText||e.response;if(!t)return t;try{return JSON.parse(t)}catch(n){return t}}function o(e){if("undefined"!=typeof XMLHttpRequest){var t=new XMLHttpRequest;t.upload&&(t.upload.onprogress=function(t){t.total>0&&(t.percent=t.loaded/t.total*100),e.onProgress(t)});var o=new FormData;e.data&&Object.keys(e.data).map(function(t){o.append(t,e.data[t])}),o.append(e.filename,e.file),t.onerror=function(t){e.onError(t)},t.onload=function(){return t.status<200||t.status>=300?e.onError(n(e,t),r(t)):void e.onSuccess(r(t))},t.open("post",e.action,!0),e.withCredentials&&"withCredentials"in t&&(t.withCredentials=!0);var a=e.headers||{};null!==a["X-Requested-With"]&&t.setRequestHeader("X-Requested-With","XMLHttpRequest");for(var i in a)a.hasOwnProperty(i)&&null!==a[i]&&t.setRequestHeader(i,a[i]);t.send(o)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o,e.exports=t["default"]},17,function(e,t,n){"use strict";var r=n(1);e.exports=function(e){var t=[];return r.Children.forEach(e,function(e){t.push(e)}),t}},function(e,t,n){"use strict";var r=n(123),o={shouldComponentUpdate:function(e,t){return!r(this.props,e)||!r(this.state,t)}};e.exports=o},function(e,t,n){"use strict";var r=n(124),o=n(2);e.exports=r(o,"`rcUtil.classSet()` is deprecated, use `classNames()` by `require('classnames')` instead")},function(e,t){"use strict";var n=0;e.exports=function(){return Date.now()+"_"+n++}},function(e,t,n){"use strict";var r=n(124),o=n(2);e.exports=r(o,"`rcUtil.joinClasses()` is deprecated, use `classNames()` by `require('classnames')` instead")},function(e,t,n){var r=n(255),o=r&&n(265),a=n(85),i={media:function(e,t){e=a(e),"function"==typeof t&&(t={match:t}),o.register(e,t),this._responsiveMediaHandlers||(this._responsiveMediaHandlers=[]),this._responsiveMediaHandlers.push({query:e,handler:t})},componentWillUnmount:function(){this._responsiveMediaHandlers&&this._responsiveMediaHandlers.forEach(function(e){o.unregister(e.query,e.handler)})}};e.exports=i},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(2),l=r(s),u=i["default"].createClass({displayName:"PrevArrow",clickHandler:function(e,t){t.preventDefault(),this.props.clickHandler(e,t)},render:function(){var e={"slick-prev":!0},t=this.clickHandler.bind(this,{message:"previous"});!this.props.infinite&&(0===this.props.currentSlide||this.props.slideCount<=this.props.slidesToShow)&&(e["slick-disabled"]=!0,t=null);var n,r={key:"0","data-role":"none",className:(0,l["default"])(e),style:{display:"block"},onClick:t};return n=this.props.prevArrow?i["default"].cloneElement(this.props.prevArrow,r):i["default"].createElement("button",o({key:"0",type:"button"},r)," Previous")}});t.PrevArrow=u;var c=i["default"].createClass({displayName:"NextArrow",clickHandler:function(e,t){t.preventDefault(),this.props.clickHandler(e,t)},render:function(){var e={"slick-next":!0},t=this.clickHandler.bind(this,{message:"next"});this.props.infinite||(this.props.centerMode&&this.props.currentSlide>=this.props.slideCount-1?(e["slick-disabled"]=!0,t=null):this.props.currentSlide>=this.props.slideCount-this.props.slidesToShow&&(e["slick-disabled"]=!0,t=null),this.props.slideCount<=this.props.slidesToShow&&(e["slick-disabled"]=!0,t=null));var n,r={key:"1","data-role":"none",className:(0,l["default"])(e),style:{display:"block"},onClick:t};return n=this.props.nextArrow?i["default"].cloneElement(this.props.nextArrow,r):i["default"].createElement("button",o({key:"1",type:"button"},r)," Next")}});t.NextArrow=c},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(2),s=r(i),l=function(e){var t;return t=Math.ceil(e.slideCount/e.slidesToScroll)},u=a["default"].createClass({displayName:"Dots",clickHandler:function(e,t){t.preventDefault(),this.props.clickHandler(e)},render:function(){var e=this,t=l({slideCount:this.props.slideCount,slidesToScroll:this.props.slidesToScroll}),n=Array.apply(null,Array(t+1).join("0").split("")).map(function(t,n){var r=(0,s["default"])({"slick-active":e.props.currentSlide===n*e.props.slidesToScroll}),o={message:"dots",index:n,slidesToScroll:e.props.slidesToScroll,currentSlide:e.props.currentSlide};return a["default"].createElement("li",{key:n,className:r},a["default"].createElement("button",{onClick:e.clickHandler.bind(e,o)},n+1))});return a["default"].createElement("ul",{className:this.props.dotsClass,style:{display:"block"}},n)}});t.Dots=u},function(e,t,n){"use strict";e.exports=n(411)},function(e,t){"use strict";var n={animating:!1,dragging:!1,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,slideCount:null,slideWidth:null,swipeLeft:null,touchObject:{startX:0,startY:0,curX:0,curY:0},lazyLoadedList:[],initialized:!1,edgeDragged:!1,swiped:!1,trackStyle:{},trackWidth:0};e.exports=n},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a=n(1),i=r(a),s=n(410),l=r(s),u=n(121),c=r(u),p=n(408),f=r(p),d=n(119),h=r(d),y=n(2),v=r(y),m=n(412),g=n(406),b=n(405),P=i["default"].createClass({displayName:"InnerSlider",mixins:[c["default"],l["default"]],getInitialState:function(){return f["default"]},getDefaultProps:function(){return h["default"]},componentWillMount:function(){this.props.init&&this.props.init(),this.setState({mounted:!0});for(var e=[],t=0;t<i["default"].Children.count(this.props.children);t++)t>=this.state.currentSlide&&t<this.state.currentSlide+this.props.slidesToShow&&e.push(t);this.props.lazyLoad&&0===this.state.lazyLoadedList.length&&this.setState({lazyLoadedList:e})},componentDidMount:function(){this.initialize(this.props),this.adaptHeight(),window.addEventListener?window.addEventListener("resize",this.onWindowResized):window.attachEvent("onresize",this.onWindowResized)},componentWillUnmount:function(){window.addEventListener?window.removeEventListener("resize",this.onWindowResized):window.detachEvent("onresize",this.onWindowResized),this.state.autoPlayTimer&&window.clearInterval(this.state.autoPlayTimer)},componentWillReceiveProps:function(e){this.props.slickGoTo!=e.slickGoTo?this.changeSlide({message:"index",index:e.slickGoTo,currentSlide:this.state.currentSlide}):this.update(e)},componentDidUpdate:function(){this.adaptHeight()},onWindowResized:function(){this.update(this.props)},render:function(){var e,t=(0,v["default"])("slick-initialized","slick-slider",this.props.className),n={fade:this.props.fade,cssEase:this.props.cssEase,speed:this.props.speed,infinite:this.props.infinite,centerMode:this.props.centerMode,currentSlide:this.state.currentSlide,lazyLoad:this.props.lazyLoad,lazyLoadedList:this.state.lazyLoadedList,rtl:this.props.rtl,slideWidth:this.state.slideWidth,slidesToShow:this.props.slidesToShow,slideCount:this.state.slideCount,trackStyle:this.state.trackStyle,variableWidth:this.props.variableWidth};if(this.props.dots===!0&&this.state.slideCount>this.props.slidesToShow){var r={dotsClass:this.props.dotsClass,slideCount:this.state.slideCount,slidesToShow:this.props.slidesToShow,currentSlide:this.state.currentSlide,slidesToScroll:this.props.slidesToScroll,clickHandler:this.changeSlide};e=i["default"].createElement(g.Dots,r)}var a,s,l={infinite:this.props.infinite,centerMode:this.props.centerMode,currentSlide:this.state.currentSlide,slideCount:this.state.slideCount,slidesToShow:this.props.slidesToShow,prevArrow:this.props.prevArrow,nextArrow:this.props.nextArrow,clickHandler:this.changeSlide};return this.props.arrows&&(a=i["default"].createElement(b.PrevArrow,l),s=i["default"].createElement(b.NextArrow,l)),i["default"].createElement("div",{className:t,onMouseEnter:this.onInnerSliderEnter,onMouseLeave:this.onInnerSliderLeave},i["default"].createElement("div",{ref:"list",className:"slick-list",onMouseDown:this.swipeStart,onMouseMove:this.state.dragging?this.swipeMove:null,onMouseUp:this.swipeEnd,onMouseLeave:this.state.dragging?this.swipeEnd:null,onTouchStart:this.swipeStart,onTouchMove:this.state.dragging?this.swipeMove:null,onTouchEnd:this.swipeEnd,onTouchCancel:this.state.dragging?this.swipeEnd:null},i["default"].createElement(m.Track,o({ref:"track"},n),this.props.children)),a,s,e)}});t.InnerSlider=P},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(122),a=n(121),i=(r(a),n(32)),s=r(i),l={changeSlide:function(e){var t,n,r,o,a;if(o=this.state.slideCount%this.props.slidesToScroll!==0,t=o?0:(this.state.slideCount-this.state.currentSlide)%this.props.slidesToScroll,"previous"===e.message)r=0===t?this.props.slidesToScroll:this.props.slidesToShow-t,a=this.state.currentSlide-r,this.props.lazyLoad&&(n=this.state.currentSlide-r,a=n===-1?this.state.slideCount-1:n);else if("next"===e.message)r=0===t?this.props.slidesToScroll:t,a=this.state.currentSlide+r;else if("dots"===e.message){if(a=e.index*e.slidesToScroll,a===e.currentSlide)return}else if("index"===e.message&&(a=e.index,a===e.currentSlide))return;this.slideHandler(a)},keyHandler:function(e){},selectHandler:function(e){},swipeStart:function(e){var t,n;this.props.swipe===!1||"ontouchend"in document&&this.props.swipe===!1||this.props.draggable===!1&&e.type.indexOf("mouse")!==-1||(t=void 0!==e.touches?e.touches[0].pageX:e.clientX,n=void 0!==e.touches?e.touches[0].pageY:e.clientY,this.setState({dragging:!0,touchObject:{startX:t,startY:n,curX:t,curY:n}}))},swipeMove:function(e){if(this.state.dragging&&!this.state.animating){var t,n,r,a=this.state.touchObject;n=(0,o.getTrackLeft)((0,s["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},this.props,this.state)),a.curX=e.touches?e.touches[0].pageX:e.clientX,a.curY=e.touches?e.touches[0].pageY:e.clientY,a.swipeLength=Math.round(Math.sqrt(Math.pow(a.curX-a.startX,2))),r=(this.props.rtl===!1?1:-1)*(a.curX>a.startX?1:-1);var i=this.state.currentSlide,l=Math.ceil(this.state.slideCount/this.props.slidesToScroll),u=this.swipeDirection(this.state.touchObject),c=a.swipeLength;this.props.infinite===!1&&(0===i&&"right"===u||i+1>=l&&"left"===u)&&(c=a.swipeLength*this.props.edgeFriction,this.state.edgeDragged===!1&&this.props.edgeEvent&&(this.props.edgeEvent(u),this.setState({edgeDragged:!0}))),this.state.swiped===!1&&this.props.swipeEvent&&(this.props.swipeEvent(u),this.setState({swiped:!0})),t=n+c*r,this.setState({touchObject:a,swipeLeft:t,trackStyle:(0,o.getTrackCSS)((0,s["default"])({left:t},this.props,this.state))}),Math.abs(a.curX-a.startX)<.8*Math.abs(a.curY-a.startY)||a.swipeLength>4&&e.preventDefault()}},swipeEnd:function(e){if(this.state.dragging){var t=this.state.touchObject,n=this.state.listWidth/this.props.touchThreshold,r=this.swipeDirection(t);if(this.setState({dragging:!1,edgeDragged:!1,swiped:!1,swipeLeft:null,touchObject:{}}),t.swipeLength)if(t.swipeLength>n)e.preventDefault(),"left"===r?this.slideHandler(this.state.currentSlide+this.props.slidesToScroll):"right"===r?this.slideHandler(this.state.currentSlide-this.props.slidesToScroll):this.slideHandler(this.state.currentSlide);else{var a=(0,o.getTrackLeft)((0,s["default"])({slideIndex:this.state.currentSlide,trackRef:this.refs.track},this.props,this.state));this.setState({trackStyle:(0,o.getTrackAnimateCSS)((0,s["default"])({left:a},this.props,this.state))})}}},onInnerSliderEnter:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.pause()},onInnerSliderLeave:function(e){this.props.autoplay&&this.props.pauseOnHover&&this.autoPlay()}};t["default"]=l,e.exports=t["default"]},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}var o=n(1),a=r(o),i=n(409),s=n(32),l=r(s),u=n(85),c=r(u),p=n(404),f=r(p),d=n(119),h=r(d),y=a["default"].createClass({displayName:"Slider",mixins:[f["default"]],getInitialState:function(){return{breakpoint:null}},componentDidMount:function(){var e=this;if(this.props.responsive){var t=this.props.responsive.map(function(e){return e.breakpoint});t.sort(function(e,t){return e-t}),t.forEach(function(n,r){var o;o=0===r?(0,c["default"])({minWidth:0,maxWidth:n}):(0,c["default"])({minWidth:t[r-1],maxWidth:n}),e.media(o,function(){e.setState({breakpoint:n})})});var n=(0,c["default"])({minWidth:t.slice(-1)[0]});this.media(n,function(){e.setState({breakpoint:null})})}},render:function(){var e,t,n=this;return this.state.breakpoint?(t=this.props.responsive.filter(function(e){return e.breakpoint===n.state.breakpoint}),e="unslick"===t[0].settings?"unslick":(0,l["default"])({},this.props,t[0].settings)):e=(0,l["default"])({},h["default"],this.props),"unslick"===e?a["default"].createElement("div",null,this.props.children):a["default"].createElement(i.InnerSlider,e,this.props.children)}});e.exports=y},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=n(1),a=r(o),i=n(32),s=r(i),l=n(2),u=r(l),c=function(e){var t,n,r,o,a;return a=e.rtl?e.slideCount-1-e.index:e.index,r=a<0||a>=e.slideCount,e.centerMode?(o=Math.floor(e.slidesToShow/2),n=(a-e.currentSlide)%e.slideCount===0,a>e.currentSlide-o-1&&a<=e.currentSlide+o&&(t=!0)):t=e.currentSlide<=a&&a<e.currentSlide+e.slidesToShow,(0,u["default"])({"slick-slide":!0,"slick-active":t,"slick-center":n,"slick-cloned":r})},p=function(e){var t={};return void 0!==e.variableWidth&&e.variableWidth!==!1||(t.width=e.slideWidth),e.fade&&(t.position="relative",t.left=-e.index*e.slideWidth,t.opacity=e.currentSlide===e.index?1:0,t.transition="opacity "+e.speed+"ms "+e.cssEase,t.WebkitTransition="opacity "+e.speed+"ms "+e.cssEase),t},f=function(e,t){return null===e.key||void 0===e.key?t:e.key},d=function(e){var t,n,r=[],o=[],i=[],l=a["default"].Children.count(e.children);return a["default"].Children.forEach(e.children,function(d,h){n=!e.lazyLoad|(e.lazyLoad&&e.lazyLoadedList.indexOf(h)>=0)?d:a["default"].createElement("div",null);var y,v=p((0,s["default"])({},e,{index:h})),m=c((0,s["default"])({index:h},e));if(y=n.props.className?(0,u["default"])(m,n.props.className):m,r.push(a["default"].cloneElement(n,{key:"original"+f(n,h),"data-index":h,className:y,style:(0,s["default"])({},n.props.style||{},v)})),e.infinite&&e.fade===!1){var g=e.variableWidth?e.slidesToShow+1:e.slidesToShow;h>=l-g&&(t=-(l-h),o.push(a["default"].cloneElement(n,{key:"cloned"+f(n,t),"data-index":t,className:y,style:(0,s["default"])({},n.props.style||{},v)}))),h<g&&(t=l+h,i.push(a["default"].cloneElement(n,{key:"cloned"+f(n,t),"data-index":t,className:y,style:(0,s["default"])({},n.props.style||{},v)})))}}),e.rtl?o.concat(r,i).reverse():o.concat(r,i)},h=a["default"].createClass({displayName:"Track",render:function(){var e=d(this.props);return a["default"].createElement("div",{className:"slick-track",style:this.props.trackStyle},e)}});t.Track=h},function(e,t,n){"use strict";var r=n(416),o={shouldComponentUpdate:function(e,t){return r(this,e,t)}};e.exports=o},function(e,t,n){"use strict";function r(){var e=s("animationend"),t=s("transitionend");e&&l.push(e),t&&l.push(t)}function o(e,t,n){e.addEventListener(t,n,!1)}function a(e,t,n){e.removeEventListener(t,n,!1)}var i=n(80),s=n(415),l=[];i.canUseDOM&&r();var u={addEndEventListener:function(e,t){return 0===l.length?void window.setTimeout(t,0):void l.forEach(function(n){o(e,n,t)})},removeEndEventListener:function(e,t){0!==l.length&&l.forEach(function(n){a(e,n,t)})}};e.exports=u},function(e,t,n){"use strict";function r(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n["ms"+e]="MS"+t,n["O"+e]="o"+t.toLowerCase(),n}function o(e){if(s[e])return s[e];if(!i[e])return e;var t=i[e];for(var n in t)if(t.hasOwnProperty(n)&&n in l)return s[e]=t[n];return""}var a=n(80),i={animationend:r("Animation","AnimationEnd"),animationiteration:r("Animation","AnimationIteration"),animationstart:r("Animation","AnimationStart"),transitionend:r("Transition","TransitionEnd")},s={},l={};a.canUseDOM&&(l=document.createElement("div").style,"AnimationEvent"in window||(delete i.animationend.animation,delete i.animationiteration.animation,delete i.animationstart.animation),"TransitionEvent"in window||delete i.transitionend.transition),e.exports=o},function(e,t,n){"use strict";function r(e,t,n){return!o(e.props,t)||!o(e.state,n)}var o=n(266);e.exports=r},function(e,t){var n=function(e){return e.replace(/[A-Z]/g,function(e){return"-"+e.toLowerCase()}).toLowerCase()};e.exports=n},function(e,t,n){var r,o;!function(e){function t(e){var t=e.length,r=n.type(e);return"function"!==r&&!n.isWindow(e)&&(!(1!==e.nodeType||!t)||("array"===r||0===t||"number"==typeof t&&t>0&&t-1 in e))}if(!e.jQuery){var n=function(e,t){return new n.fn.init(e,t)};n.isWindow=function(e){return null!=e&&e==e.window},n.type=function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?o[i.call(e)]||"object":typeof e},n.isArray=Array.isArray||function(e){return"array"===n.type(e)},n.isPlainObject=function(e){var t;if(!e||"object"!==n.type(e)||e.nodeType||n.isWindow(e))return!1;try{if(e.constructor&&!a.call(e,"constructor")&&!a.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}for(t in e);return void 0===t||a.call(e,t)},n.each=function(e,n,r){var o,a=0,i=e.length,s=t(e);if(r){if(s)for(;a<i&&(o=n.apply(e[a],r),o!==!1);a++);else for(a in e)if(o=n.apply(e[a],r),o===!1)break}else if(s)for(;a<i&&(o=n.call(e[a],a,e[a]),o!==!1);a++);else for(a in e)if(o=n.call(e[a],a,e[a]),o===!1)break;return e},n.data=function(e,t,o){if(void 0===o){var a=e[n.expando],i=a&&r[a];if(void 0===t)return i;if(i&&t in i)return i[t]}else if(void 0!==t){var a=e[n.expando]||(e[n.expando]=++n.uuid);return r[a]=r[a]||{},r[a][t]=o,o}},n.removeData=function(e,t){var o=e[n.expando],a=o&&r[o];a&&n.each(t,function(e,t){delete a[t]})},n.extend=function(){var e,t,r,o,a,i,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[l]||{},l++),"object"!=typeof s&&"function"!==n.type(s)&&(s={}),l===u&&(s=this,l--);l<u;l++)if(null!=(a=arguments[l]))for(o in a)e=s[o],r=a[o],s!==r&&(c&&r&&(n.isPlainObject(r)||(t=n.isArray(r)))?(t?(t=!1,i=e&&n.isArray(e)?e:[]):i=e&&n.isPlainObject(e)?e:{},s[o]=n.extend(c,i,r)):void 0!==r&&(s[o]=r));return s},n.queue=function(e,r,o){function a(e,n){var r=n||[];return null!=e&&(t(Object(e))?!function(e,t){for(var n=+t.length,r=0,o=e.length;r<n;)e[o++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[o++]=t[r++];return e.length=o,e}(r,"string"==typeof e?[e]:e):[].push.call(r,e)),r}if(e){r=(r||"fx")+"queue";var i=n.data(e,r);return o?(!i||n.isArray(o)?i=n.data(e,r,a(o)):i.push(o),i):i||[]}},n.dequeue=function(e,t){n.each(e.nodeType?[e]:e,function(e,r){t=t||"fx";var o=n.queue(r,t),a=o.shift();"inprogress"===a&&(a=o.shift()),a&&("fx"===t&&o.unshift("inprogress"),a.call(r,function(){n.dequeue(r,t)}))})},n.fn=n.prototype={init:function(e){if(e.nodeType)return this[0]=e,this;throw new Error("Not a DOM node.")},offset:function(){var t=this[0].getBoundingClientRect?this[0].getBoundingClientRect():{ top:0,left:0};return{top:t.top+(e.pageYOffset||document.scrollTop||0)-(document.clientTop||0),left:t.left+(e.pageXOffset||document.scrollLeft||0)-(document.clientLeft||0)}},position:function(){function e(){for(var e=this.offsetParent||document;e&&"html"===!e.nodeType.toLowerCase&&"static"===e.style.position;)e=e.offsetParent;return e||document}var t=this[0],e=e.apply(t),r=this.offset(),o=/^(?:body|html)$/i.test(e.nodeName)?{top:0,left:0}:n(e).offset();return r.top-=parseFloat(t.style.marginTop)||0,r.left-=parseFloat(t.style.marginLeft)||0,e.style&&(o.top+=parseFloat(e.style.borderTopWidth)||0,o.left+=parseFloat(e.style.borderLeftWidth)||0),{top:r.top-o.top,left:r.left-o.left}}};var r={};n.expando="velocity"+(new Date).getTime(),n.uuid=0;for(var o={},a=o.hasOwnProperty,i=o.toString,s="Boolean Number String Function Array Date RegExp Object Error".split(" "),l=0;l<s.length;l++)o["[object "+s[l]+"]"]=s[l].toLowerCase();n.fn.init.prototype=n.fn,e.Velocity={Utilities:n}}}(window),function(a){"object"==typeof e&&"object"==typeof e.exports?e.exports=a():(r=a,o="function"==typeof r?r.call(t,n,t,e):r,!(void 0!==o&&(e.exports=o)))}(function(){return function(e,t,n,r){function o(e){for(var t=-1,n=e?e.length:0,r=[];++t<n;){var o=e[t];o&&r.push(o)}return r}function a(e){return y.isWrapped(e)?e=[].slice.call(e):y.isNode(e)&&(e=[e]),e}function i(e){var t=f.data(e,"velocity");return null===t?r:t}function s(e){return function(t){return Math.round(t*e)*(1/e)}}function l(e,n,r,o){function a(e,t){return 1-3*t+3*e}function i(e,t){return 3*t-6*e}function s(e){return 3*e}function l(e,t,n){return((a(t,n)*e+i(t,n))*e+s(t))*e}function u(e,t,n){return 3*a(t,n)*e*e+2*i(t,n)*e+s(t)}function c(t,n){for(var o=0;o<y;++o){var a=u(n,e,r);if(0===a)return n;var i=l(n,e,r)-t;n-=i/a}return n}function p(){for(var t=0;t<b;++t)T[t]=l(t*P,e,r)}function f(t,n,o){var a,i,s=0;do i=n+(o-n)/2,a=l(i,e,r)-t,a>0?o=i:n=i;while(Math.abs(a)>m&&++s<g);return i}function d(t){for(var n=0,o=1,a=b-1;o!=a&&T[o]<=t;++o)n+=P;--o;var i=(t-T[o])/(T[o+1]-T[o]),s=n+i*P,l=u(s,e,r);return l>=v?c(t,s):0==l?s:f(t,n,n+P)}function h(){w=!0,e==n&&r==o||p()}var y=4,v=.001,m=1e-7,g=10,b=11,P=1/(b-1),O="Float32Array"in t;if(4!==arguments.length)return!1;for(var C=0;C<4;++C)if("number"!=typeof arguments[C]||isNaN(arguments[C])||!isFinite(arguments[C]))return!1;e=Math.min(e,1),r=Math.min(r,1),e=Math.max(e,0),r=Math.max(r,0);var T=O?new Float32Array(b):new Array(b),w=!1,x=function(t){return w||h(),e===n&&r===o?t:0===t?0:1===t?1:l(d(t),n,o)};x.getControlPoints=function(){return[{x:e,y:n},{x:r,y:o}]};var E="generateBezier("+[e,n,r,o]+")";return x.toString=function(){return E},x}function u(e,t){var n=e;return y.isString(e)?b.Easings[e]||(n=!1):n=y.isArray(e)&&1===e.length?s.apply(null,e):y.isArray(e)&&2===e.length?P.apply(null,e.concat([t])):!(!y.isArray(e)||4!==e.length)&&l.apply(null,e),n===!1&&(n=b.Easings[b.defaults.easing]?b.defaults.easing:g),n}function c(e){if(e){var t=(new Date).getTime(),n=b.State.calls.length;n>1e4&&(b.State.calls=o(b.State.calls));for(var a=0;a<n;a++)if(b.State.calls[a]){var s=b.State.calls[a],l=s[0],u=s[2],d=s[3],h=!!d,v=null;d||(d=b.State.calls[a][3]=t-16);for(var m=Math.min((t-d)/u.duration,1),g=0,P=l.length;g<P;g++){var C=l[g],w=C.element;if(i(w)){var x=!1;if(u.display!==r&&null!==u.display&&"none"!==u.display){if("flex"===u.display){var E=["-webkit-box","-moz-box","-ms-flexbox","-webkit-flex"];f.each(E,function(e,t){O.setPropertyValue(w,"display",t)})}O.setPropertyValue(w,"display",u.display)}u.visibility!==r&&"hidden"!==u.visibility&&O.setPropertyValue(w,"visibility",u.visibility);for(var S in C)if("element"!==S){var k,j=C[S],_=y.isString(j.easing)?b.Easings[j.easing]:j.easing;if(1===m)k=j.endValue;else{var N=j.endValue-j.startValue;if(k=j.startValue+N*_(m,u,N),!h&&k===j.currentValue)continue}if(j.currentValue=k,"tween"===S)v=k;else{if(O.Hooks.registered[S]){var M=O.Hooks.getRoot(S),D=i(w).rootPropertyValueCache[M];D&&(j.rootPropertyValue=D)}var A=O.setPropertyValue(w,S,j.currentValue+(0===parseFloat(k)?"":j.unitType),j.rootPropertyValue,j.scrollData);O.Hooks.registered[S]&&(O.Normalizations.registered[M]?i(w).rootPropertyValueCache[M]=O.Normalizations.registered[M]("extract",null,A[1]):i(w).rootPropertyValueCache[M]=A[1]),"transform"===A[0]&&(x=!0)}}u.mobileHA&&i(w).transformCache.translate3d===r&&(i(w).transformCache.translate3d="(0px, 0px, 0px)",x=!0),x&&O.flushTransformCache(w)}}u.display!==r&&"none"!==u.display&&(b.State.calls[a][2].display=!1),u.visibility!==r&&"hidden"!==u.visibility&&(b.State.calls[a][2].visibility=!1),u.progress&&u.progress.call(s[1],s[1],m,Math.max(0,d+u.duration-t),d,v),1===m&&p(a)}}b.State.isTicking&&T(c)}function p(e,t){if(!b.State.calls[e])return!1;for(var n=b.State.calls[e][0],o=b.State.calls[e][1],a=b.State.calls[e][2],s=b.State.calls[e][4],l=!1,u=0,c=n.length;u<c;u++){var p=n[u].element;if(t||a.loop||("none"===a.display&&O.setPropertyValue(p,"display",a.display),"hidden"===a.visibility&&O.setPropertyValue(p,"visibility",a.visibility)),a.loop!==!0&&(f.queue(p)[1]===r||!/\.velocityQueueEntryFlag/i.test(f.queue(p)[1]))&&i(p)){i(p).isAnimating=!1,i(p).rootPropertyValueCache={};var d=!1;f.each(O.Lists.transforms3D,function(e,t){var n=/^scale/.test(t)?1:0,o=i(p).transformCache[t];i(p).transformCache[t]!==r&&new RegExp("^\\("+n+"[^.]").test(o)&&(d=!0,delete i(p).transformCache[t])}),a.mobileHA&&(d=!0,delete i(p).transformCache.translate3d),d&&O.flushTransformCache(p),O.Values.removeClass(p,"velocity-animating")}if(!t&&a.complete&&!a.loop&&u===c-1)try{a.complete.call(o,o)}catch(h){setTimeout(function(){throw h},1)}s&&a.loop!==!0&&s(o),i(p)&&a.loop===!0&&!t&&(f.each(i(p).tweensContainer,function(e,t){/^rotate/.test(e)&&360===parseFloat(t.endValue)&&(t.endValue=0,t.startValue=360),/^backgroundPosition/.test(e)&&100===parseFloat(t.endValue)&&"%"===t.unitType&&(t.endValue=0,t.startValue=100)}),b(p,"reverse",{loop:!0,delay:a.delay})),a.queue!==!1&&f.dequeue(p,a.queue)}b.State.calls[e]=!1;for(var y=0,v=b.State.calls.length;y<v;y++)if(b.State.calls[y]!==!1){l=!0;break}l===!1&&(b.State.isTicking=!1,delete b.State.calls,b.State.calls=[])}var f,d=function(){if(n.documentMode)return n.documentMode;for(var e=7;e>4;e--){var t=n.createElement("div");if(t.innerHTML="<!--[if IE "+e+"]><span></span><![endif]-->",t.getElementsByTagName("span").length)return t=null,e}return r}(),h=function(){var e=0;return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||function(t){var n,r=(new Date).getTime();return n=Math.max(0,16-(r-e)),e=r+n,setTimeout(function(){t(r+n)},n)}}(),y={isString:function(e){return"string"==typeof e},isArray:Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},isFunction:function(e){return"[object Function]"===Object.prototype.toString.call(e)},isNode:function(e){return e&&e.nodeType},isNodeList:function(e){return"object"==typeof e&&/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(e))&&e.length!==r&&(0===e.length||"object"==typeof e[0]&&e[0].nodeType>0)},isWrapped:function(e){return e&&(e.jquery||t.Zepto&&t.Zepto.zepto.isZ(e))},isSVG:function(e){return t.SVGElement&&e instanceof t.SVGElement},isEmptyObject:function(e){for(var t in e)return!1;return!0}},v=!1;if(e.fn&&e.fn.jquery?(f=e,v=!0):f=t.Velocity.Utilities,d<=8&&!v)throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");if(d<=7)return void(jQuery.fn.velocity=jQuery.fn.animate);var m=400,g="swing",b={State:{isMobile:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),isAndroid:/Android/i.test(navigator.userAgent),isGingerbread:/Android 2\.3\.[3-7]/i.test(navigator.userAgent),isChrome:t.chrome,isFirefox:/Firefox/i.test(navigator.userAgent),prefixElement:n.createElement("div"),prefixMatches:{},scrollAnchor:null,scrollPropertyLeft:null,scrollPropertyTop:null,isTicking:!1,calls:[]},CSS:{},Utilities:f,Redirects:{},Easings:{},Promise:t.Promise,defaults:{queue:"",duration:m,easing:g,begin:r,complete:r,progress:r,display:r,visibility:r,loop:!1,delay:!1,mobileHA:!0,_cacheValues:!0},init:function(e){f.data(e,"velocity",{isSVG:y.isSVG(e),isAnimating:!1,computedStyle:null,tweensContainer:null,rootPropertyValueCache:{},transformCache:{}})},hook:null,mock:!1,version:{major:1,minor:2,patch:2},debug:!1};t.pageYOffset!==r?(b.State.scrollAnchor=t,b.State.scrollPropertyLeft="pageXOffset",b.State.scrollPropertyTop="pageYOffset"):(b.State.scrollAnchor=n.documentElement||n.body.parentNode||n.body,b.State.scrollPropertyLeft="scrollLeft",b.State.scrollPropertyTop="scrollTop");var P=function(){function e(e){return-e.tension*e.x-e.friction*e.v}function t(t,n,r){var o={x:t.x+r.dx*n,v:t.v+r.dv*n,tension:t.tension,friction:t.friction};return{dx:o.v,dv:e(o)}}function n(n,r){var o={dx:n.v,dv:e(n)},a=t(n,.5*r,o),i=t(n,.5*r,a),s=t(n,r,i),l=1/6*(o.dx+2*(a.dx+i.dx)+s.dx),u=1/6*(o.dv+2*(a.dv+i.dv)+s.dv);return n.x=n.x+l*r,n.v=n.v+u*r,n}return function r(e,t,o){var a,i,s,l={x:-1,v:0,tension:null,friction:null},u=[0],c=0,p=1e-4,f=.016;for(e=parseFloat(e)||500,t=parseFloat(t)||20,o=o||null,l.tension=e,l.friction=t,a=null!==o,a?(c=r(e,t),i=c/o*f):i=f;;)if(s=n(s||l,i),u.push(1+s.x),c+=16,!(Math.abs(s.x)>p&&Math.abs(s.v)>p))break;return a?function(e){return u[e*(u.length-1)|0]}:c}}();b.Easings={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},spring:function(e){return 1-Math.cos(4.5*e*Math.PI)*Math.exp(6*-e)}},f.each([["ease",[.25,.1,.25,1]],["ease-in",[.42,0,1,1]],["ease-out",[0,0,.58,1]],["ease-in-out",[.42,0,.58,1]],["easeInSine",[.47,0,.745,.715]],["easeOutSine",[.39,.575,.565,1]],["easeInOutSine",[.445,.05,.55,.95]],["easeInQuad",[.55,.085,.68,.53]],["easeOutQuad",[.25,.46,.45,.94]],["easeInOutQuad",[.455,.03,.515,.955]],["easeInCubic",[.55,.055,.675,.19]],["easeOutCubic",[.215,.61,.355,1]],["easeInOutCubic",[.645,.045,.355,1]],["easeInQuart",[.895,.03,.685,.22]],["easeOutQuart",[.165,.84,.44,1]],["easeInOutQuart",[.77,0,.175,1]],["easeInQuint",[.755,.05,.855,.06]],["easeOutQuint",[.23,1,.32,1]],["easeInOutQuint",[.86,0,.07,1]],["easeInExpo",[.95,.05,.795,.035]],["easeOutExpo",[.19,1,.22,1]],["easeInOutExpo",[1,0,0,1]],["easeInCirc",[.6,.04,.98,.335]],["easeOutCirc",[.075,.82,.165,1]],["easeInOutCirc",[.785,.135,.15,.86]]],function(e,t){b.Easings[t[0]]=l.apply(null,t[1])});var O=b.CSS={RegEx:{isHex:/^#([A-f\d]{3}){1,2}$/i,valueUnwrap:/^[A-z]+\((.*)\)$/i,wrappedValueAlreadyExtracted:/[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,valueSplit:/([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/gi},Lists:{colors:["fill","stroke","stopColor","color","backgroundColor","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor","outlineColor"],transformsBase:["translateX","translateY","scale","scaleX","scaleY","skewX","skewY","rotateZ"],transforms3D:["transformPerspective","translateZ","scaleZ","rotateX","rotateY"]},Hooks:{templates:{textShadow:["Color X Y Blur","black 0px 0px 0px"],boxShadow:["Color X Y Blur Spread","black 0px 0px 0px 0px"],clip:["Top Right Bottom Left","0px 0px 0px 0px"],backgroundPosition:["X Y","0% 0%"],transformOrigin:["X Y Z","50% 50% 0px"],perspectiveOrigin:["X Y","50% 50%"]},registered:{},register:function(){for(var e=0;e<O.Lists.colors.length;e++){var t="color"===O.Lists.colors[e]?"0 0 0 1":"255 255 255 1";O.Hooks.templates[O.Lists.colors[e]]=["Red Green Blue Alpha",t]}var n,r,o;if(d)for(n in O.Hooks.templates){r=O.Hooks.templates[n],o=r[0].split(" ");var a=r[1].match(O.RegEx.valueSplit);"Color"===o[0]&&(o.push(o.shift()),a.push(a.shift()),O.Hooks.templates[n]=[o.join(" "),a.join(" ")])}for(n in O.Hooks.templates){r=O.Hooks.templates[n],o=r[0].split(" ");for(var e in o){var i=n+o[e],s=e;O.Hooks.registered[i]=[n,s]}}},getRoot:function(e){var t=O.Hooks.registered[e];return t?t[0]:e},cleanRootPropertyValue:function(e,t){return O.RegEx.valueUnwrap.test(t)&&(t=t.match(O.RegEx.valueUnwrap)[1]),O.Values.isCSSNullValue(t)&&(t=O.Hooks.templates[e][1]),t},extractValue:function(e,t){var n=O.Hooks.registered[e];if(n){var r=n[0],o=n[1];return t=O.Hooks.cleanRootPropertyValue(r,t),t.toString().match(O.RegEx.valueSplit)[o]}return t},injectValue:function(e,t,n){var r=O.Hooks.registered[e];if(r){var o,a,i=r[0],s=r[1];return n=O.Hooks.cleanRootPropertyValue(i,n),o=n.toString().match(O.RegEx.valueSplit),o[s]=t,a=o.join(" ")}return n}},Normalizations:{registered:{clip:function(e,t,n){switch(e){case"name":return"clip";case"extract":var r;return O.RegEx.wrappedValueAlreadyExtracted.test(n)?r=n:(r=n.toString().match(O.RegEx.valueUnwrap),r=r?r[1].replace(/,(\s+)?/g," "):n),r;case"inject":return"rect("+n+")"}},blur:function(e,t,n){switch(e){case"name":return b.State.isFirefox?"filter":"-webkit-filter";case"extract":var r=parseFloat(n);if(!r&&0!==r){var o=n.toString().match(/blur\(([0-9]+[A-z]+)\)/i);r=o?o[1]:0}return r;case"inject":return parseFloat(n)?"blur("+n+")":"none"}},opacity:function(e,t,n){if(d<=8)switch(e){case"name":return"filter";case"extract":var r=n.toString().match(/alpha\(opacity=(.*)\)/i);return n=r?r[1]/100:1;case"inject":return t.style.zoom=1,parseFloat(n)>=1?"":"alpha(opacity="+parseInt(100*parseFloat(n),10)+")"}else switch(e){case"name":return"opacity";case"extract":return n;case"inject":return n}}},register:function(){d<=9||b.State.isGingerbread||(O.Lists.transformsBase=O.Lists.transformsBase.concat(O.Lists.transforms3D));for(var e=0;e<O.Lists.transformsBase.length;e++)!function(){var t=O.Lists.transformsBase[e];O.Normalizations.registered[t]=function(e,n,o){switch(e){case"name":return"transform";case"extract":return i(n)===r||i(n).transformCache[t]===r?/^scale/i.test(t)?1:0:i(n).transformCache[t].replace(/[()]/g,"");case"inject":var a=!1;switch(t.substr(0,t.length-1)){case"translate":a=!/(%|px|em|rem|vw|vh|\d)$/i.test(o);break;case"scal":case"scale":b.State.isAndroid&&i(n).transformCache[t]===r&&o<1&&(o=1),a=!/(\d)$/i.test(o);break;case"skew":a=!/(deg|\d)$/i.test(o);break;case"rotate":a=!/(deg|\d)$/i.test(o)}return a||(i(n).transformCache[t]="("+o+")"),i(n).transformCache[t]}}}();for(var e=0;e<O.Lists.colors.length;e++)!function(){var t=O.Lists.colors[e];O.Normalizations.registered[t]=function(e,n,o){switch(e){case"name":return t;case"extract":var a;if(O.RegEx.wrappedValueAlreadyExtracted.test(o))a=o;else{var i,s={black:"rgb(0, 0, 0)",blue:"rgb(0, 0, 255)",gray:"rgb(128, 128, 128)",green:"rgb(0, 128, 0)",red:"rgb(255, 0, 0)",white:"rgb(255, 255, 255)"};/^[A-z]+$/i.test(o)?i=s[o]!==r?s[o]:s.black:O.RegEx.isHex.test(o)?i="rgb("+O.Values.hexToRgb(o).join(" ")+")":/^rgba?\(/i.test(o)||(i=s.black),a=(i||o).toString().match(O.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g," ")}return d<=8||3!==a.split(" ").length||(a+=" 1"),a;case"inject":return d<=8?4===o.split(" ").length&&(o=o.split(/\s+/).slice(0,3).join(" ")):3===o.split(" ").length&&(o+=" 1"),(d<=8?"rgb":"rgba")+"("+o.replace(/\s+/g,",").replace(/\.(\d)+(?=,)/g,"")+")"}}}()}},Names:{camelCase:function(e){return e.replace(/-(\w)/g,function(e,t){return t.toUpperCase()})},SVGAttribute:function(e){var t="width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";return(d||b.State.isAndroid&&!b.State.isChrome)&&(t+="|transform"),new RegExp("^("+t+")$","i").test(e)},prefixCheck:function(e){if(b.State.prefixMatches[e])return[b.State.prefixMatches[e],!0];for(var t=["","Webkit","Moz","ms","O"],n=0,r=t.length;n<r;n++){var o;if(o=0===n?e:t[n]+e.replace(/^\w/,function(e){return e.toUpperCase()}),y.isString(b.State.prefixElement.style[o]))return b.State.prefixMatches[e]=o,[o,!0]}return[e,!1]}},Values:{hexToRgb:function(e){var t,n=/^#?([a-f\d])([a-f\d])([a-f\d])$/i,r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i;return e=e.replace(n,function(e,t,n,r){return t+t+n+n+r+r}),t=r.exec(e),t?[parseInt(t[1],16),parseInt(t[2],16),parseInt(t[3],16)]:[0,0,0]},isCSSNullValue:function(e){return 0==e||/^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(e)},getUnitType:function(e){return/^(rotate|skew)/i.test(e)?"deg":/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(e)?"":"px"},getDisplayType:function(e){var t=e&&e.tagName.toString().toLowerCase();return/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(t)?"inline":/^(li)$/i.test(t)?"list-item":/^(tr)$/i.test(t)?"table-row":/^(table)$/i.test(t)?"table":/^(tbody)$/i.test(t)?"table-row-group":"block"},addClass:function(e,t){e.classList?e.classList.add(t):e.className+=(e.className.length?" ":"")+t},removeClass:function(e,t){e.classList?e.classList.remove(t):e.className=e.className.toString().replace(new RegExp("(^|\\s)"+t.split(" ").join("|")+"(\\s|$)","gi")," ")}},getPropertyValue:function(e,n,o,a){function s(e,n){function o(){u&&O.setPropertyValue(e,"display","none")}var l=0;if(d<=8)l=f.css(e,n);else{var u=!1;if(/^(width|height)$/.test(n)&&0===O.getPropertyValue(e,"display")&&(u=!0,O.setPropertyValue(e,"display",O.Values.getDisplayType(e))),!a){if("height"===n&&"border-box"!==O.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var c=e.offsetHeight-(parseFloat(O.getPropertyValue(e,"borderTopWidth"))||0)-(parseFloat(O.getPropertyValue(e,"borderBottomWidth"))||0)-(parseFloat(O.getPropertyValue(e,"paddingTop"))||0)-(parseFloat(O.getPropertyValue(e,"paddingBottom"))||0);return o(),c}if("width"===n&&"border-box"!==O.getPropertyValue(e,"boxSizing").toString().toLowerCase()){var p=e.offsetWidth-(parseFloat(O.getPropertyValue(e,"borderLeftWidth"))||0)-(parseFloat(O.getPropertyValue(e,"borderRightWidth"))||0)-(parseFloat(O.getPropertyValue(e,"paddingLeft"))||0)-(parseFloat(O.getPropertyValue(e,"paddingRight"))||0);return o(),p}}var h;h=i(e)===r?t.getComputedStyle(e,null):i(e).computedStyle?i(e).computedStyle:i(e).computedStyle=t.getComputedStyle(e,null),"borderColor"===n&&(n="borderTopColor"),l=9===d&&"filter"===n?h.getPropertyValue(n):h[n],""!==l&&null!==l||(l=e.style[n]),o()}if("auto"===l&&/^(top|right|bottom|left)$/i.test(n)){var y=s(e,"position");("fixed"===y||"absolute"===y&&/top|left/i.test(n))&&(l=f(e).position()[n]+"px")}return l}var l;if(O.Hooks.registered[n]){var u=n,c=O.Hooks.getRoot(u);o===r&&(o=O.getPropertyValue(e,O.Names.prefixCheck(c)[0])),O.Normalizations.registered[c]&&(o=O.Normalizations.registered[c]("extract",e,o)),l=O.Hooks.extractValue(u,o)}else if(O.Normalizations.registered[n]){var p,h;p=O.Normalizations.registered[n]("name",e),"transform"!==p&&(h=s(e,O.Names.prefixCheck(p)[0]),O.Values.isCSSNullValue(h)&&O.Hooks.templates[n]&&(h=O.Hooks.templates[n][1])),l=O.Normalizations.registered[n]("extract",e,h)}if(!/^[\d-]/.test(l))if(i(e)&&i(e).isSVG&&O.Names.SVGAttribute(n))if(/^(height|width)$/i.test(n))try{l=e.getBBox()[n]}catch(y){l=0}else l=e.getAttribute(n);else l=s(e,O.Names.prefixCheck(n)[0]);return O.Values.isCSSNullValue(l)&&(l=0),b.debug>=2&&console.log("Get "+n+": "+l),l},setPropertyValue:function(e,n,r,o,a){var s=n;if("scroll"===n)a.container?a.container["scroll"+a.direction]=r:"Left"===a.direction?t.scrollTo(r,a.alternateValue):t.scrollTo(a.alternateValue,r);else if(O.Normalizations.registered[n]&&"transform"===O.Normalizations.registered[n]("name",e))O.Normalizations.registered[n]("inject",e,r),s="transform",r=i(e).transformCache[n];else{if(O.Hooks.registered[n]){var l=n,u=O.Hooks.getRoot(n);o=o||O.getPropertyValue(e,u),r=O.Hooks.injectValue(l,r,o),n=u}if(O.Normalizations.registered[n]&&(r=O.Normalizations.registered[n]("inject",e,r),n=O.Normalizations.registered[n]("name",e)),s=O.Names.prefixCheck(n)[0],d<=8)try{e.style[s]=r}catch(c){b.debug&&console.log("Browser does not support ["+r+"] for ["+s+"]")}else i(e)&&i(e).isSVG&&O.Names.SVGAttribute(n)?e.setAttribute(n,r):e.style[s]=r;b.debug>=2&&console.log("Set "+n+" ("+s+"): "+r)}return[s,r]},flushTransformCache:function(e){function t(t){return parseFloat(O.getPropertyValue(e,t))}var n="";if((d||b.State.isAndroid&&!b.State.isChrome)&&i(e).isSVG){var r={translate:[t("translateX"),t("translateY")],skewX:[t("skewX")],skewY:[t("skewY")],scale:1!==t("scale")?[t("scale"),t("scale")]:[t("scaleX"),t("scaleY")],rotate:[t("rotateZ"),0,0]};f.each(i(e).transformCache,function(e){/^translate/i.test(e)?e="translate":/^scale/i.test(e)?e="scale":/^rotate/i.test(e)&&(e="rotate"),r[e]&&(n+=e+"("+r[e].join(" ")+") ",delete r[e])})}else{var o,a;f.each(i(e).transformCache,function(t){return o=i(e).transformCache[t],"transformPerspective"===t?(a=o,!0):(9===d&&"rotateZ"===t&&(t="rotate"),void(n+=t+o+" "))}),a&&(n="perspective"+a+" "+n)}O.setPropertyValue(e,"transform",n)}};O.Hooks.register(),O.Normalizations.register(),b.hook=function(e,t,n){var o=r;return e=a(e),f.each(e,function(e,a){if(i(a)===r&&b.init(a),n===r)o===r&&(o=b.CSS.getPropertyValue(a,t));else{var s=b.CSS.setPropertyValue(a,t,n);"transform"===s[0]&&b.CSS.flushTransformCache(a),o=s}}),o};var C=function(){function e(){return s?S.promise||null:l}function o(){function e(e){function p(e,t){var n=r,o=r,i=r;return y.isArray(e)?(n=e[0],!y.isArray(e[1])&&/^[\d-]/.test(e[1])||y.isFunction(e[1])||O.RegEx.isHex.test(e[1])?i=e[1]:(y.isString(e[1])&&!O.RegEx.isHex.test(e[1])||y.isArray(e[1]))&&(o=t?e[1]:u(e[1],s.duration),e[2]!==r&&(i=e[2]))):n=e,t||(o=o||s.easing),y.isFunction(n)&&(n=n.call(a,w,T)),y.isFunction(i)&&(i=i.call(a,w,T)),[n||0,o,i]}function d(e,t){var n,r;return r=(t||"0").toString().toLowerCase().replace(/[%A-z]+$/,function(e){return n=e,""}),n||(n=O.Values.getUnitType(e)),[r,n]}function m(){var e={myParent:a.parentNode||n.body,position:O.getPropertyValue(a,"position"),fontSize:O.getPropertyValue(a,"fontSize")},r=e.position===A.lastPosition&&e.myParent===A.lastParent,o=e.fontSize===A.lastFontSize;A.lastParent=e.myParent,A.lastPosition=e.position,A.lastFontSize=e.fontSize;var s=100,l={};if(o&&r)l.emToPx=A.lastEmToPx,l.percentToPxWidth=A.lastPercentToPxWidth,l.percentToPxHeight=A.lastPercentToPxHeight;else{var u=i(a).isSVG?n.createElementNS("http://www.w3.org/2000/svg","rect"):n.createElement("div");b.init(u),e.myParent.appendChild(u),f.each(["overflow","overflowX","overflowY"],function(e,t){b.CSS.setPropertyValue(u,t,"hidden")}),b.CSS.setPropertyValue(u,"position",e.position),b.CSS.setPropertyValue(u,"fontSize",e.fontSize),b.CSS.setPropertyValue(u,"boxSizing","content-box"),f.each(["minWidth","maxWidth","width","minHeight","maxHeight","height"],function(e,t){b.CSS.setPropertyValue(u,t,s+"%")}),b.CSS.setPropertyValue(u,"paddingLeft",s+"em"),l.percentToPxWidth=A.lastPercentToPxWidth=(parseFloat(O.getPropertyValue(u,"width",null,!0))||1)/s,l.percentToPxHeight=A.lastPercentToPxHeight=(parseFloat(O.getPropertyValue(u,"height",null,!0))||1)/s,l.emToPx=A.lastEmToPx=(parseFloat(O.getPropertyValue(u,"paddingLeft"))||1)/s,e.myParent.removeChild(u)}return null===A.remToPx&&(A.remToPx=parseFloat(O.getPropertyValue(n.body,"fontSize"))||16),null===A.vwToPx&&(A.vwToPx=parseFloat(t.innerWidth)/100,A.vhToPx=parseFloat(t.innerHeight)/100),l.remToPx=A.remToPx,l.vwToPx=A.vwToPx,l.vhToPx=A.vhToPx,b.debug>=1&&console.log("Unit ratios: "+JSON.stringify(l),a),l}if(s.begin&&0===w)try{s.begin.call(h,h)}catch(P){setTimeout(function(){throw P},1)}if("scroll"===k){var C,x,E,j=/^x$/i.test(s.axis)?"Left":"Top",_=parseFloat(s.offset)||0;s.container?y.isWrapped(s.container)||y.isNode(s.container)?(s.container=s.container[0]||s.container,C=s.container["scroll"+j],E=C+f(a).position()[j.toLowerCase()]+_):s.container=null:(C=b.State.scrollAnchor[b.State["scrollProperty"+j]],x=b.State.scrollAnchor[b.State["scrollProperty"+("Left"===j?"Top":"Left")]],E=f(a).offset()[j.toLowerCase()]+_),l={scroll:{rootPropertyValue:!1,startValue:C,currentValue:C,endValue:E,unitType:"",easing:s.easing,scrollData:{container:s.container,direction:j,alternateValue:x}},element:a},b.debug&&console.log("tweensContainer (scroll): ",l.scroll,a)}else if("reverse"===k){if(!i(a).tweensContainer)return void f.dequeue(a,s.queue);"none"===i(a).opts.display&&(i(a).opts.display="auto"),"hidden"===i(a).opts.visibility&&(i(a).opts.visibility="visible"),i(a).opts.loop=!1,i(a).opts.begin=null,i(a).opts.complete=null,g.easing||delete s.easing,g.duration||delete s.duration,s=f.extend({},i(a).opts,s);var N=f.extend(!0,{},i(a).tweensContainer);for(var M in N)if("element"!==M){var D=N[M].startValue;N[M].startValue=N[M].currentValue=N[M].endValue,N[M].endValue=D,y.isEmptyObject(g)||(N[M].easing=s.easing),b.debug&&console.log("reverse tweensContainer ("+M+"): "+JSON.stringify(N[M]),a)}l=N}else if("start"===k){var N;i(a).tweensContainer&&i(a).isAnimating===!0&&(N=i(a).tweensContainer),f.each(v,function(e,t){if(RegExp("^"+O.Lists.colors.join("$|^")+"$").test(e)){var n=p(t,!0),o=n[0],a=n[1],i=n[2];if(O.RegEx.isHex.test(o)){for(var s=["Red","Green","Blue"],l=O.Values.hexToRgb(o),u=i?O.Values.hexToRgb(i):r,c=0;c<s.length;c++){var f=[l[c]];a&&f.push(a),u!==r&&f.push(u[c]),v[e+s[c]]=f}delete v[e]}}});for(var V in v){var F=p(v[V]),I=F[0],R=F[1],K=F[2];V=O.Names.camelCase(V);var W=O.Hooks.getRoot(V),H=!1;if(i(a).isSVG||"tween"===W||O.Names.prefixCheck(W)[1]!==!1||O.Normalizations.registered[W]!==r){(s.display!==r&&null!==s.display&&"none"!==s.display||s.visibility!==r&&"hidden"!==s.visibility)&&/opacity|filter/.test(V)&&!K&&0!==I&&(K=0),s._cacheValues&&N&&N[V]?(K===r&&(K=N[V].endValue+N[V].unitType),H=i(a).rootPropertyValueCache[W]):O.Hooks.registered[V]?K===r?(H=O.getPropertyValue(a,W),K=O.getPropertyValue(a,V,H)):H=O.Hooks.templates[W][1]:K===r&&(K=O.getPropertyValue(a,V));var B,z,U,Y=!1;if(B=d(V,K),K=B[0],U=B[1],B=d(V,I),I=B[0].replace(/^([+-\/*])=/,function(e,t){return Y=t,""}),z=B[1],K=parseFloat(K)||0,I=parseFloat(I)||0,"%"===z&&(/^(fontSize|lineHeight)$/.test(V)?(I/=100,z="em"):/^scale/.test(V)?(I/=100,z=""):/(Red|Green|Blue)$/i.test(V)&&(I=I/100*255,z="")),/[\/*]/.test(Y))z=U;else if(U!==z&&0!==K)if(0===I)z=U;else{o=o||m();var q=/margin|padding|left|right|width|text|word|letter/i.test(V)||/X$/.test(V)||"x"===V?"x":"y";switch(U){case"%":K*="x"===q?o.percentToPxWidth:o.percentToPxHeight;break;case"px":break;default:K*=o[U+"ToPx"]}switch(z){case"%":K*=1/("x"===q?o.percentToPxWidth:o.percentToPxHeight);break;case"px":break;default:K*=1/o[z+"ToPx"]}}switch(Y){case"+":I=K+I;break;case"-":I=K-I;break;case"*":I=K*I;break;case"/":I=K/I}l[V]={rootPropertyValue:H,startValue:K,currentValue:K,endValue:I,unitType:z,easing:R},b.debug&&console.log("tweensContainer ("+V+"): "+JSON.stringify(l[V]),a)}else b.debug&&console.log("Skipping ["+W+"] due to a lack of browser support.")}l.element=a}l.element&&(O.Values.addClass(a,"velocity-animating"),L.push(l),""===s.queue&&(i(a).tweensContainer=l,i(a).opts=s),i(a).isAnimating=!0,w===T-1?(b.State.calls.push([L,h,s,null,S.resolver]),b.State.isTicking===!1&&(b.State.isTicking=!0,c())):w++)}var o,a=this,s=f.extend({},b.defaults,g),l={};switch(i(a)===r&&b.init(a),parseFloat(s.delay)&&s.queue!==!1&&f.queue(a,s.queue,function(e){b.velocityQueueEntryFlag=!0,i(a).delayTimer={setTimeout:setTimeout(e,parseFloat(s.delay)),next:e}}),s.duration.toString().toLowerCase()){case"fast":s.duration=200;break;case"normal":s.duration=m;break;case"slow":s.duration=600;break;default:s.duration=parseFloat(s.duration)||1}b.mock!==!1&&(b.mock===!0?s.duration=s.delay=1:(s.duration*=parseFloat(b.mock)||1,s.delay*=parseFloat(b.mock)||1)),s.easing=u(s.easing,s.duration),s.begin&&!y.isFunction(s.begin)&&(s.begin=null),s.progress&&!y.isFunction(s.progress)&&(s.progress=null),s.complete&&!y.isFunction(s.complete)&&(s.complete=null),s.display!==r&&null!==s.display&&(s.display=s.display.toString().toLowerCase(),"auto"===s.display&&(s.display=b.CSS.Values.getDisplayType(a))),s.visibility!==r&&null!==s.visibility&&(s.visibility=s.visibility.toString().toLowerCase()),s.mobileHA=s.mobileHA&&b.State.isMobile&&!b.State.isGingerbread,s.queue===!1?s.delay?setTimeout(e,s.delay):e():f.queue(a,s.queue,function(t,n){return n===!0?(S.promise&&S.resolver(h),!0):(b.velocityQueueEntryFlag=!0,void e(t))}),""!==s.queue&&"fx"!==s.queue||"inprogress"===f.queue(a)[0]||f.dequeue(a)}var s,l,d,h,v,g,P=arguments[0]&&(arguments[0].p||f.isPlainObject(arguments[0].properties)&&!arguments[0].properties.names||y.isString(arguments[0].properties));if(y.isWrapped(this)?(s=!1,d=0,h=this,l=this):(s=!0,d=1,h=P?arguments[0].elements||arguments[0].e:arguments[0]),h=a(h)){P?(v=arguments[0].properties||arguments[0].p,g=arguments[0].options||arguments[0].o):(v=arguments[d],g=arguments[d+1]);var T=h.length,w=0;if(!/^(stop|finish|finishAll)$/i.test(v)&&!f.isPlainObject(g)){var x=d+1;g={};for(var E=x;E<arguments.length;E++)y.isArray(arguments[E])||!/^(fast|normal|slow)$/i.test(arguments[E])&&!/^\d/.test(arguments[E])?y.isString(arguments[E])||y.isArray(arguments[E])?g.easing=arguments[E]:y.isFunction(arguments[E])&&(g.complete=arguments[E]):g.duration=arguments[E]}var S={promise:null,resolver:null,rejecter:null};s&&b.Promise&&(S.promise=new b.Promise(function(e,t){S.resolver=e,S.rejecter=t}));var k;switch(v){case"scroll":k="scroll";break;case"reverse":k="reverse";break;case"finish":case"finishAll":case"stop":f.each(h,function(e,t){i(t)&&i(t).delayTimer&&(clearTimeout(i(t).delayTimer.setTimeout),i(t).delayTimer.next&&i(t).delayTimer.next(),delete i(t).delayTimer),"finishAll"!==v||g!==!0&&!y.isString(g)||(f.each(f.queue(t,y.isString(g)?g:""),function(e,t){y.isFunction(t)&&t()}),f.queue(t,y.isString(g)?g:"",[]))});var j=[];return f.each(b.State.calls,function(e,t){t&&f.each(t[1],function(n,o){var a=g===r?"":g;return a!==!0&&t[2].queue!==a&&(g!==r||t[2].queue!==!1)||void f.each(h,function(n,r){r===o&&((g===!0||y.isString(g))&&(f.each(f.queue(r,y.isString(g)?g:""),function(e,t){y.isFunction(t)&&t(null,!0)}),f.queue(r,y.isString(g)?g:"",[])),"stop"===v?(i(r)&&i(r).tweensContainer&&a!==!1&&f.each(i(r).tweensContainer,function(e,t){t.endValue=t.currentValue}),j.push(e)):"finish"!==v&&"finishAll"!==v||(t[2].duration=1))})})}),"stop"===v&&(f.each(j,function(e,t){p(t,!0)}),S.promise&&S.resolver(h)),e();default:if(!f.isPlainObject(v)||y.isEmptyObject(v)){if(y.isString(v)&&b.Redirects[v]){var _=f.extend({},g),N=_.duration,M=_.delay||0;return _.backwards===!0&&(h=f.extend(!0,[],h).reverse()),f.each(h,function(e,t){parseFloat(_.stagger)?_.delay=M+parseFloat(_.stagger)*e:y.isFunction(_.stagger)&&(_.delay=M+_.stagger.call(t,e,T)),_.drag&&(_.duration=parseFloat(N)||(/^(callout|transition)/.test(v)?1e3:m),_.duration=Math.max(_.duration*(_.backwards?1-e/T:(e+1)/T),.75*_.duration,200)),b.Redirects[v].call(t,t,_||{},e,T,h,S.promise?S:r)}),e()}var D="Velocity: First argument ("+v+") was not a property map, a known action, or a registered redirect. Aborting.";return S.promise?S.rejecter(new Error(D)):console.log(D),e()}k="start"}var A={lastParent:null,lastPosition:null,lastFontSize:null,lastPercentToPxWidth:null,lastPercentToPxHeight:null,lastEmToPx:null,remToPx:null,vwToPx:null,vhToPx:null},L=[];f.each(h,function(e,t){y.isNode(t)&&o.call(t)});var V,_=f.extend({},b.defaults,g);if(_.loop=parseInt(_.loop),V=2*_.loop-1,_.loop)for(var F=0;F<V;F++){var I={delay:_.delay,progress:_.progress};F===V-1&&(I.display=_.display,I.visibility=_.visibility,I.complete=_.complete),C(h,"reverse",I)}return e()}};b=f.extend(C,b),b.animate=C;var T=t.requestAnimationFrame||h;return b.State.isMobile||n.hidden===r||n.addEventListener("visibilitychange",function(){n.hidden?(T=function(e){return setTimeout(function(){e(!0)},16)},c()):T=t.requestAnimationFrame||h}),e.Velocity=b,e!==t&&(e.fn.velocity=C,e.fn.velocity.defaults=b.defaults),f.each(["Down","Up"],function(e,t){b.Redirects["slide"+t]=function(e,n,o,a,i,s){var l=f.extend({},n),u=l.begin,c=l.complete,p={height:"",marginTop:"",marginBottom:"",paddingTop:"",paddingBottom:""},d={};l.display===r&&(l.display="Down"===t?"inline"===b.CSS.Values.getDisplayType(e)?"inline-block":"block":"none"),l.begin=function(){u&&u.call(i,i);for(var n in p){d[n]=e.style[n];var r=b.CSS.getPropertyValue(e,n);p[n]="Down"===t?[r,0]:[0,r]}d.overflow=e.style.overflow,e.style.overflow="hidden"},l.complete=function(){for(var t in d)e.style[t]=d[t];c&&c.call(i,i),s&&s.resolver(i)},b(e,p,l)}}),f.each(["In","Out"],function(e,t){ b.Redirects["fade"+t]=function(e,n,o,a,i,s){var l=f.extend({},n),u={opacity:"In"===t?1:0},c=l.complete;o!==a-1?l.complete=l.begin=null:l.complete=function(){c&&c.call(i,i),s&&s.resolver(i)},l.display===r&&(l.display="In"===t?"auto":"none"),b(this,u,l)}}),b}(window.jQuery||window.Zepto||window,window,document)})},3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,function(e,t,n,r){"use strict";n(3),n(r)},function(e,t,n,r){"use strict";n(3),n(r),n(13)},function(e,t,n,r){"use strict";n(3),n(r),n(25)}]))}); //# sourceMappingURL=antd.min.js.map
src/components/Resume/Games.js
angeloocana/angeloocana
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import H2 from '../H2'; import Game from './Game'; import { FormattedMessage } from 'react-intl'; const Ul = styled.ul` display: flex; flex-flow: row wrap; justify-content: space-around; margin: 1rem 0 0 0; padding: 0; `; const Games = ({ games }) => { return ( <section> <header> <FormattedMessage id="resume.games"> {(txt) => ( <H2> {txt} </H2> )} </FormattedMessage> </header> <Ul> { games.map((game, i) => <Game key={i} {...game} /> ) } </Ul> </section> ); }; Games.propTypes = { games: PropTypes.array.isRequired }; export default Games;
src/svg-icons/image/broken-image.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageBrokenImage = (props) => ( <SvgIcon {...props}> <path d="M21 5v6.59l-3-3.01-4 4.01-4-4-4 4-3-3.01V5c0-1.1.9-2 2-2h14c1.1 0 2 .9 2 2zm-3 6.42l3 3.01V19c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2v-6.58l3 2.99 4-4 4 4 4-3.99z"/> </SvgIcon> ); ImageBrokenImage = pure(ImageBrokenImage); ImageBrokenImage.displayName = 'ImageBrokenImage'; ImageBrokenImage.muiName = 'SvgIcon'; export default ImageBrokenImage;
app/components/ConfirmationModal/index.js
projectcashmere/admin
import React from 'react'; import Modal from 'react-modal'; import { FormattedMessage } from 'react-intl'; import Header from './Header'; import Body from './Body'; import Button from './Button'; import messages from './messages'; import modalStyle from './modalStyle'; function ConfirmationModal({ isOpen, closeModal, headerMessage, confirmationMessage, actionMessage, onConfirmClick, }) { return ( <Modal contentLabel="confirmationModal" isOpen={isOpen} onRequestClose={closeModal} style={modalStyle} shouldCloseOnOverlayClick > <Header>{headerMessage}</Header> <Body>{confirmationMessage}</Body> <Button primary onClick={onConfirmClick}> {actionMessage} </Button> <Button onClick={closeModal}> <FormattedMessage {...messages.cancel} /> </Button> </Modal> ); } export default ConfirmationModal;
src/components/Webcam/index.js
hamsterbacke23/webcamdisplay-react
import React from 'react'; import DragResize from '../DragResize'; import Timer from '../Timer'; import Display from '../Display'; export class Webcam extends React.PureComponent { constructor(props) { super(props); this.state = { streams: [], devices: [], }; } componentDidMount() { this.startDevices(); } setDevices(devices) { this.setState({ devices }); this.startWebcams(); } setNewError(error) { const errors = this.state.errors ? this.state.errors.slice() : []; errors.push(error); this.setState({ errors, }); } startVideo(deviceId) { const constraints = { video: { width: 1280, height: 720 }, deviceId: { exact: deviceId }, }; navigator.mediaDevices.getUserMedia({ video: constraints }) .then(this.startVideoCb.bind(this)) .catch(this.setNewError.bind(this)); } startVideoCb(stream) { const streams = this.state.streams.slice(); streams.push(stream); this.setState({ streams }); } startWebcams() { let videoInputExists = false; this.state.devices.forEach((device) => { if (device.kind === 'videoinput') { this.startVideo(device.deviceId); videoInputExists = true; } }); if (!videoInputExists) { this.setNewError({ message: 'No video input found, please connect a webcam.' }); } } startDevices() { if (!navigator || !navigator.mediaDevices) { this.setNewError({ message: 'Sorry, navigator or navigator.mediaDevices does not seem to be available in this browser!' }); return; } navigator.mediaDevices.enumerateDevices() .then(this.setDevices.bind(this)) .catch(this.setNewError.bind(this)); } render() { if (!this.state) { return null; } if (this.state.errors) { return ( <div style={{ marginLeft: 20 }}> <h3>Error</h3> <ul className="errors"> {this.state.errors.map((error, key) => ( <li key={key}> <p>{error.name}</p> <p>{error.message}</p> </li> ) )} </ul> </div> ); } return ( <React.Fragment> <DragResize initialWidth={100} initialHeight={100} x={window.innerWidth - 150} y={50}> <Timer /> </DragResize> {this.state.streams.map((stream, index) => ( <DragResize key={index} initialWidth={400} initialHeight={300} x={((window.innerWidth / 2)) * index + 50} y={(window.innerHeight / 2) - 150}> <Display srcObject={stream} /> </DragResize> ) )} </React.Fragment> ); } } export default Webcam;
plop-templates/component.test.tmpl.js
jonniespratley/px-components-react
import { expect } from 'chai'; import React from 'react'; import {shallow} from 'enzyme'; import {{pascalCase name}} from './'; describe('{{dashCase name}}', () => { test('should...', () =>{ const wrapper = shallow( <{{pascalCase name}}/> ); console.log(wrapper.debug()); expect(true).to.equal(true); }); //expect(wrapper.find('.label')).to.have.length(1); //expect(wrapper.find('.delta')).to.have.length(1); //expect(wrapper.find('.alpha')).to.have.length(1); //expect(wrapper.contains(<div className='label'/>)).to.equal(true); });
example/DioryExample.js
DioryMe/diory-react-components
import React from 'react' import { Diory } from '../lib' const diory = { text: 'Hello, I am a diory. Take me home!', image: 'https://gravatar.com/avatar/ff80f8f9bc52f1b79e468a41f2239001', link: 'http://tampere.fi', style: { display: 'inline-block', width: '20em', height: '20em', backgroundColor: 'green', margin: '1em', text: { fontSize: '2em', fontFamily: 'sans-serif', color: 'white', textAlign: 'center', textShadow: '1px 1px green' }, image: { opacity: 0.6, filter: 'blur(5px)' } } } const dioryGrid = { text: 'This is a grid:', image: 'https://gravatar.com/avatar/ff80f8f9bc52f1b79e468a41f2239001', style: { text: { fontSize: '2em', fontFamily: 'sans-serif', color: 'white' } }, diorys: { 1: diory, 2: diory, 3: diory, 4: diory, 5: diory, 6: diory } } const dioryButton = { text: 'This is a button that returns the clicked diory!', style: { backgroundColor: 'green', width: '100%', cursor: 'pointer', text: { fontSize: '2em', fontFamily: 'sans-serif', color: 'white', textAlign: 'center' } } } const DioryExample = ({}) => ( <div> <Diory { ...diory } /> <Diory { ...dioryButton } onClick={ console.log }/> </div> ) export default DioryExample
ajax/libs/video.js/5.0.0-rc.83/alt/video.novtt.js
samthor/cdnjs
/** * @license * Video.js 5.0.0-rc.83 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvZG9jdW1lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdG9wTGV2ZWwgPSB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6XG4gICAgdHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcgPyB3aW5kb3cgOiB7fVxudmFyIG1pbkRvYyA9IHJlcXVpcmUoJ21pbi1kb2N1bWVudCcpO1xuXG5pZiAodHlwZW9mIGRvY3VtZW50ICE9PSAndW5kZWZpbmVkJykge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZG9jdW1lbnQ7XG59IGVsc2Uge1xuICAgIHZhciBkb2NjeSA9IHRvcExldmVsWydfX0dMT0JBTF9ET0NVTUVOVF9DQUNIRUA0J107XG5cbiAgICBpZiAoIWRvY2N5KSB7XG4gICAgICAgIGRvY2N5ID0gdG9wTGV2ZWxbJ19fR0xPQkFMX0RPQ1VNRU5UX0NBQ0hFQDQnXSA9IG1pbkRvYztcbiAgICB9XG5cbiAgICBtb2R1bGUuZXhwb3J0cyA9IGRvY2N5O1xufVxuIl19 },{"min-document":3}],2:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvd2luZG93LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiaWYgKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIpIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIikge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZ2xvYmFsO1xufSBlbHNlIGlmICh0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIil7XG4gICAgbW9kdWxlLmV4cG9ydHMgPSBzZWxmO1xufSBlbHNlIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHt9O1xufVxuIl19 },{}],3:[function(_dereq_,module,exports){ },{}],4:[function(_dereq_,module,exports){ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; },{}],5:[function(_dereq_,module,exports){ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; },{}],6:[function(_dereq_,module,exports){ /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; },{}],7:[function(_dereq_,module,exports){ /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; },{}],8:[function(_dereq_,module,exports){ var createBaseFor = _dereq_('./createBaseFor'); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; },{"./createBaseFor":15}],9:[function(_dereq_,module,exports){ var baseFor = _dereq_('./baseFor'), keysIn = _dereq_('../object/keysIn'); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } module.exports = baseForIn; },{"../object/keysIn":36,"./baseFor":8}],10:[function(_dereq_,module,exports){ var arrayEach = _dereq_('./arrayEach'), baseMergeDeep = _dereq_('./baseMergeDeep'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isObject = _dereq_('../lang/isObject'), isObjectLike = _dereq_('./isObjectLike'), isTypedArray = _dereq_('../lang/isTypedArray'), keys = _dereq_('../object/keys'); /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? undefined : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } module.exports = baseMerge; },{"../lang/isArray":27,"../lang/isObject":30,"../lang/isTypedArray":33,"../object/keys":35,"./arrayEach":6,"./baseMergeDeep":11,"./isArrayLike":18,"./isObjectLike":23}],11:[function(_dereq_,module,exports){ var arrayCopy = _dereq_('./arrayCopy'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isPlainObject = _dereq_('../lang/isPlainObject'), isTypedArray = _dereq_('../lang/isTypedArray'), toPlainObject = _dereq_('../lang/toPlainObject'); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } module.exports = baseMergeDeep; },{"../lang/isArguments":26,"../lang/isArray":27,"../lang/isPlainObject":31,"../lang/isTypedArray":33,"../lang/toPlainObject":34,"./arrayCopy":5,"./isArrayLike":18}],12:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } module.exports = baseProperty; },{"./toObject":25}],13:[function(_dereq_,module,exports){ var identity = _dereq_('../utility/identity'); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; },{"../utility/identity":39}],14:[function(_dereq_,module,exports){ var bindCallback = _dereq_('./bindCallback'), isIterateeCall = _dereq_('./isIterateeCall'), restParam = _dereq_('../function/restParam'); /** * Creates a `_.assign`, `_.defaults`, or `_.merge` function. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner; },{"../function/restParam":4,"./bindCallback":13,"./isIterateeCall":21}],15:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; },{"./toObject":25}],16:[function(_dereq_,module,exports){ var baseProperty = _dereq_('./baseProperty'); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; },{"./baseProperty":12}],17:[function(_dereq_,module,exports){ var isNative = _dereq_('../lang/isNative'); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; },{"../lang/isNative":29}],18:[function(_dereq_,module,exports){ var getLength = _dereq_('./getLength'), isLength = _dereq_('./isLength'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; },{"./getLength":16,"./isLength":22}],19:[function(_dereq_,module,exports){ /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); module.exports = isHostObject; },{}],20:[function(_dereq_,module,exports){ /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; },{}],21:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('./isArrayLike'), isIndex = _dereq_('./isIndex'), isObject = _dereq_('../lang/isObject'); /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } module.exports = isIterateeCall; },{"../lang/isObject":30,"./isArrayLike":18,"./isIndex":20}],22:[function(_dereq_,module,exports){ /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],23:[function(_dereq_,module,exports){ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; },{}],24:[function(_dereq_,module,exports){ var isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isIndex = _dereq_('./isIndex'), isLength = _dereq_('./isLength'), isString = _dereq_('../lang/isString'), keysIn = _dereq_('../object/keysIn'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; },{"../lang/isArguments":26,"../lang/isArray":27,"../lang/isString":32,"../object/keysIn":36,"./isIndex":20,"./isLength":22}],25:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } module.exports = toObject; },{"../lang/isObject":30,"../lang/isString":32,"../support":38}],26:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('../internal/isArrayLike'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; },{"../internal/isArrayLike":18,"../internal/isObjectLike":23}],27:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; },{"../internal/getNative":17,"../internal/isLength":22,"../internal/isObjectLike":23}],28:[function(_dereq_,module,exports){ var isObject = _dereq_('./isObject'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 which returns 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } module.exports = isFunction; },{"./isObject":30}],29:[function(_dereq_,module,exports){ var isFunction = _dereq_('./isFunction'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; },{"../internal/isHostObject":19,"../internal/isObjectLike":23,"./isFunction":28}],30:[function(_dereq_,module,exports){ /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; },{}],31:[function(_dereq_,module,exports){ var baseForIn = _dereq_('../internal/baseForIn'), isArguments = _dereq_('./isArguments'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { var Ctor; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; if (support.ownLast) { baseForIn(value, function(subValue, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } module.exports = isPlainObject; },{"../internal/baseForIn":9,"../internal/isHostObject":19,"../internal/isObjectLike":23,"../support":38,"./isArguments":26}],32:[function(_dereq_,module,exports){ var isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } module.exports = isString; },{"../internal/isObjectLike":23}],33:[function(_dereq_,module,exports){ var isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; },{"../internal/isLength":22,"../internal/isObjectLike":23}],34:[function(_dereq_,module,exports){ var baseCopy = _dereq_('../internal/baseCopy'), keysIn = _dereq_('../object/keysIn'); /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } module.exports = toPlainObject; },{"../internal/baseCopy":7,"../object/keysIn":36}],35:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArrayLike = _dereq_('../internal/isArrayLike'), isObject = _dereq_('../lang/isObject'), shimKeys = _dereq_('../internal/shimKeys'), support = _dereq_('../support'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; },{"../internal/getNative":17,"../internal/isArrayLike":18,"../internal/shimKeys":24,"../lang/isObject":30,"../support":38}],36:[function(_dereq_,module,exports){ var arrayEach = _dereq_('../internal/arrayEach'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isFunction = _dereq_('../lang/isFunction'), isIndex = _dereq_('../internal/isIndex'), isLength = _dereq_('../internal/isLength'), isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** `Object#toString` result references. */ var arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used for native method references. */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it's iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } module.exports = keysIn; },{"../internal/arrayEach":6,"../internal/isIndex":20,"../internal/isLength":22,"../lang/isArguments":26,"../lang/isArray":27,"../lang/isFunction":28,"../lang/isObject":30,"../lang/isString":32,"../support":38}],37:[function(_dereq_,module,exports){ var baseMerge = _dereq_('../internal/baseMerge'), createAssigner = _dereq_('../internal/createAssigner'); /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it's invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); module.exports = merge; },{"../internal/baseMerge":10,"../internal/createAssigner":14}],38:[function(_dereq_,module,exports){ /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; }(1, 0)); module.exports = support; },{}],39:[function(_dereq_,module,exports){ /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; },{}],40:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es6-shim var keys = _dereq_('object-keys'); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var defineProperties = _dereq_('define-properties'); var toObject = Object; var push = Array.prototype.push; var propIsEnumerable = Object.prototype.propertyIsEnumerable; var assignShim = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = toObject(target); var s, source, i, props, syms; for (s = 1; s < arguments.length; ++s) { source = toObject(arguments[s]); props = keys(source); if (hasSymbols && Object.getOwnPropertySymbols) { syms = Object.getOwnPropertySymbols(source); for (i = 0; i < syms.length; ++i) { if (propIsEnumerable.call(source, syms[i])) { push.call(props, syms[i]); } } } for (i = 0; i < props.length; ++i) { objTarget[props[i]] = source[props[i]]; } } return objTarget; }; defineProperties(assignShim, { shim: function shimObjectAssign() { var assignHasPendingExceptions = function () { if (!Object.assign || !Object.preventExtensions) { return false; } // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } }; defineProperties( Object, { assign: assignShim }, { assign: assignHasPendingExceptions } ); return Object.assign || assignShim; } }); module.exports = assignShim; },{"define-properties":41,"object-keys":43}],41:[function(_dereq_,module,exports){ 'use strict'; var keys = _dereq_('object-keys'); var foreach = _dereq_('foreach'); var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { value: obj, enumerable: false }); /* eslint-disable no-unused-vars */ for (var _ in obj) { return false; } /* eslint-enable no-unused-vars */ return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = props.concat(Object.getOwnPropertySymbols(map)); } foreach(props, function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; },{"foreach":42,"object-keys":43}],42:[function(_dereq_,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; },{}],43:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = _dereq_('./isArguments'); var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString'); var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var blacklistedKeys = { $window: true, $console: true, $parent: true, $self: true, $frames: true, $webkitIndexedDB: true, $webkitStorageInfo: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' && !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (!Object.keys) { Object.keys = keysShim; } else { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } return Object.keys || keysShim; }; module.exports = keysShim; },{"./isArguments":44}],44:[function(_dereq_,module,exports){ 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; },{}],45:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],46:[function(_dereq_,module,exports){ /** * @file big-play-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('./button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Button * @class BigPlayButton */ var BigPlayButton = (function (_Button) { _inherits(BigPlayButton, _Button); function BigPlayButton(player, options) { _classCallCheck(this, BigPlayButton); _Button.call(this, player, options); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * Handles click for play * * @method handleClick */ BigPlayButton.prototype.handleClick = function handleClick() { this.player_.play(); }; return BigPlayButton; })(_buttonJs2['default']); BigPlayButton.prototype.controlText_ = 'Play Video'; _componentJs2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; module.exports = exports['default']; },{"./button.js":47,"./component.js":48}],47:[function(_dereq_,module,exports){ /** * @file button.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * Base class for all buttons * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class Button */ var Button = (function (_Component) { _inherits(Button, _Component); function Button(player, options) { _classCallCheck(this, Button); _Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); } /** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of element attributes that should be set on the element Tag name * @return {Element} * @method createEl */ Button.prototype.createEl = function createEl() { var tag = arguments.length <= 0 || arguments[0] === undefined ? 'button' : arguments[0]; var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // Add standard Aria and Tabindex info props = _objectAssign2['default']({ className: this.buildCSSClass(), 'role': 'button', 'type': 'button', // Necessary since the default button type is "submit" 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); var el = _Component.prototype.createEl.call(this, tag, props); this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); el.appendChild(this.controlTextEl_); this.controlText(this.controlText_); return el; }; /** * Controls text - both request and localize * * @param {String} text Text for button * @return {String} * @method controlText */ Button.prototype.controlText = function controlText(text) { if (!text) return this.controlText_ || 'Need Text'; this.controlText_ = text; this.controlTextEl_.innerHTML = this.localize(this.controlText_); return this; }; /** * Allows sub components to stack CSS class names * * @return {String} * @method buildCSSClass */ Button.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handle Click - Override with specific functionality for button * * @method handleClick */ Button.prototype.handleClick = function handleClick() {}; /** * Handle Focus - Add keyboard functionality to element * * @method handleFocus */ Button.prototype.handleFocus = function handleFocus() { Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Handle KeyPress (document level) - Trigger click when keys are pressed * * @method handleKeyPress */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(event); } }; /** * Handle Blur - Remove keyboard triggers * * @method handleBlur */ Button.prototype.handleBlur = function handleBlur() { Events.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return Button; })(_component2['default']); _component2['default'].registerComponent('Button', Button); exports['default'] = Button; module.exports = exports['default']; },{"./component":48,"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"global/document":1,"object.assign":40}],48:[function(_dereq_,module,exports){ /** * @file component.js * * Player Component - Base class for all UI objects */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * Base UI Component class * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * ```js * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * ``` * ```html * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * ``` * Components are also event targets. * ```js * button.on('click', function(){ * console.log('Button Clicked!'); * }); * button.trigger('customevent'); * ``` * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @class Component */ var Component = (function () { function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = _utilsMergeOptionsJs2['default']({}, this.options_); // Updated options with supplied options options = this.options_ = _utilsMergeOptionsJs2['default'](this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the component and all child components * * @method dispose */ Component.prototype.dispose = function dispose() { this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the component's player * * @return {Player} * @method player */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects * Whenever a property is an object on both options objects * the two properties will be merged using mergeOptions. * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * ```js * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * ``` * RESULT * ```js * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * ``` * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged * @method options */ Component.prototype.options = function options(obj) { _utilsLogJs2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = _utilsMergeOptionsJs2['default'](this.options_, obj); return this.options_; }; /** * Get the component's DOM element * ```js * var domEl = myComponent.el(); * ``` * * @return {Element} * @method el */ Component.prototype.el = function el() { return this.el_; }; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} * @method createEl */ Component.prototype.createEl = function createEl(tagName, attributes) { return Dom.createEl(tagName, attributes); }; Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the component's DOM element where children are inserted. * Will either be the same as el() or a new element defined in createEl(). * * @return {Element} * @method contentEl */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get the component's ID * ```js * var id = myComponent.id(); * ``` * * @return {String} * @method id */ Component.prototype.id = function id() { return this.id_; }; /** * Get the component's name. The name is often used to reference the component. * ```js * var name = myComponent.name(); * ``` * * @return {String} * @method name */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * ```js * var kids = myComponent.children(); * ``` * * @return {Array} The children * @method children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns a child component with the provided ID * * @return {Component} * @method getChildById */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns a child component with the provided name * * @return {Component} * @method getChild */ Component.prototype.getChild = function getChild(name) { return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * ```js * myComponent.el(); * // -> <div class='my-component'></div> * myComponent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * ``` * Pass in options for child constructors and options for children of the child * ```js * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * ``` * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {Component} The child component (created by this process if a string was used) * @method addChild */ Component.prototype.addChild = function addChild(child) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var component = undefined; var componentName = undefined; // If child is a string, create nt with options if (typeof child === 'string') { componentName = child; // Options can also be specified as a boolean, so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _utilsLogJs2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.'); options = {}; } // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) var componentClassName = options.componentClass || _utilsToTitleCaseJs2['default'](componentName); // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && component.name(); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { this.contentEl().appendChild(component.el()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {Component} component Component to remove * @method removeChild */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * ```js * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } * ``` * // Or when creating the component * ```js * var myComp = new MyComponent(player, { * children: { * myChildComponent: { * myChildOption: true * } * } * }); * ``` * The children option can also be an Array of child names or * child options objects (that also include a 'name' key). * ```js * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * ``` * * @method initChildren */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { (function () { // `this` is `parent` var parentOptions = _this.options_; var handleAdd = function handleAdd(name, opts) { // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each _this[name] = _this.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; var _name = undefined; var opts = undefined; if (typeof child === 'string') { // ['myComponent'] _name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] _name = child.name; opts = child; } handleAdd(_name, opts); } } else { Object.getOwnPropertyNames(children).forEach(function (name) { handleAdd(name, children[name]); }); } })(); } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an event listener to this component's element * ```js * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * ``` * The context of myFunc will be myComponent unless previously bound. * Alternatively, you can add a listener to another element or component. * ```js * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * ``` * The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `myComponent.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {Component} * @method on */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this2, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; _this2.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } })(); } return this; }; /** * Remove an event listener from this component's element * ```js * myComponent.off('eventType', myFunc); * ``` * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * ```js * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * ``` * * @param {String=|Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {Component} * @method off */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * ```js * myComponent.one('eventName', myFunc); * ``` * Alternatively you can add a listener to another element or component * that will be triggered only once. * ```js * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * ``` * * @param {String|Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {Component} * @method one */ Component.prototype.one = function one(first, second, third) { var _this3 = this, _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this3, third); var newFunc = function newFunc() { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; _this3.on(target, type, newFunc); })(); } return this; }; /** * Trigger an event on an element * ```js * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * myComponent.trigger('eventName', {data: 'some data'}); * myComponent.trigger({'type':'eventName'}, {data: 'some data'}); * ``` * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Component} self * @method trigger */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @param {Boolean} sync Exec the listener synchronously if component is ready * @return {Component} * @method ready */ Component.prototype.ready = function ready(fn) { var sync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (fn) { if (this.isReady_) { if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {Component} * @method triggerReady */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); // Reset Ready Queue this.readyQueue_ = []; } // Allow for using event listeners also this.trigger('ready'); }, 1); }; /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {Component} * @method hasClass */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {Component} * @method addClass */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove and return a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {Component} * @method removeClass */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {Component} * @method show */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {Component} * @method hide */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method lockShowing */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method unlockShowing */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Set or get the width of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {Component} This component, when setting the width * @return {Number|String} The width, when getting * @method width */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {Component} This component, when setting the height * @return {Number|String} The height, when getting * @method height */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width Width of player * @param {Number|String} height Height of player * @return {Component} The component * @method dimensions */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private * @method dimension */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + _utilsToTitleCaseJs2['default'](widthOrHeight)], 10); }; /** * Emit 'tap' events when touch events are supported * This is used to support toggling the controls through a tap on the video. * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * * @private * @method emitTapEvents */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = undefined; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy the touches object to prevent modifying the original firstTouch = _objectAssign2['default']({}, event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. * * @method enableTouchActivity */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = undefined; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID * @method setTimeout */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = _globalWindow2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID * @method clearTimeout */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _globalWindow2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID * @method setInterval */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _globalWindow2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID * @method clearInterval */ Component.prototype.clearInterval = function clearInterval(intervalId) { _globalWindow2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Registers a component * * @param {String} name Name of the component to register * @param {Object} comp The component to register * @static * @method registerComponent */ Component.registerComponent = function registerComponent(name, comp) { if (!Component.components_) { Component.components_ = {}; } Component.components_[name] = comp; return comp; }; /** * Gets a component by name * * @param {String} name Name of the component to get * @return {Component} * @static * @method getComponent */ Component.getComponent = function getComponent(name) { if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) { _utilsLogJs2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _globalWindow2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method * or uses the init of the parent object * * @param {Object} props An object of properties * @static * @deprecated * @method extend */ Component.extend = function extend(props) { props = props || {}; _utilsLogJs2['default'].warn('Component.extend({}) has been deprecated, use videojs.extends(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var _name2 in props) { if (props.hasOwnProperty(_name2)) { subObj.prototype[_name2] = props[_name2]; } } return subObj; }; return Component; })(); Component.registerComponent('Component', Component); exports['default'] = Component; module.exports = exports['default']; },{"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"./utils/guid.js":111,"./utils/log.js":112,"./utils/merge-options.js":113,"./utils/to-title-case.js":116,"global/window":2,"object.assign":40}],49:[function(_dereq_,module,exports){ /** * @file control-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _playToggleJs = _dereq_('./play-toggle.js'); var _playToggleJs2 = _interopRequireDefault(_playToggleJs); var _timeControlsCurrentTimeDisplayJs = _dereq_('./time-controls/current-time-display.js'); var _timeControlsCurrentTimeDisplayJs2 = _interopRequireDefault(_timeControlsCurrentTimeDisplayJs); var _timeControlsDurationDisplayJs = _dereq_('./time-controls/duration-display.js'); var _timeControlsDurationDisplayJs2 = _interopRequireDefault(_timeControlsDurationDisplayJs); var _timeControlsTimeDividerJs = _dereq_('./time-controls/time-divider.js'); var _timeControlsTimeDividerJs2 = _interopRequireDefault(_timeControlsTimeDividerJs); var _timeControlsRemainingTimeDisplayJs = _dereq_('./time-controls/remaining-time-display.js'); var _timeControlsRemainingTimeDisplayJs2 = _interopRequireDefault(_timeControlsRemainingTimeDisplayJs); var _liveDisplayJs = _dereq_('./live-display.js'); var _liveDisplayJs2 = _interopRequireDefault(_liveDisplayJs); var _progressControlProgressControlJs = _dereq_('./progress-control/progress-control.js'); var _progressControlProgressControlJs2 = _interopRequireDefault(_progressControlProgressControlJs); var _fullscreenToggleJs = _dereq_('./fullscreen-toggle.js'); var _fullscreenToggleJs2 = _interopRequireDefault(_fullscreenToggleJs); var _volumeControlVolumeControlJs = _dereq_('./volume-control/volume-control.js'); var _volumeControlVolumeControlJs2 = _interopRequireDefault(_volumeControlVolumeControlJs); var _volumeMenuButtonJs = _dereq_('./volume-menu-button.js'); var _volumeMenuButtonJs2 = _interopRequireDefault(_volumeMenuButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _textTrackControlsChaptersButtonJs = _dereq_('./text-track-controls/chapters-button.js'); var _textTrackControlsChaptersButtonJs2 = _interopRequireDefault(_textTrackControlsChaptersButtonJs); var _textTrackControlsSubtitlesButtonJs = _dereq_('./text-track-controls/subtitles-button.js'); var _textTrackControlsSubtitlesButtonJs2 = _interopRequireDefault(_textTrackControlsSubtitlesButtonJs); var _textTrackControlsCaptionsButtonJs = _dereq_('./text-track-controls/captions-button.js'); var _textTrackControlsCaptionsButtonJs2 = _interopRequireDefault(_textTrackControlsCaptionsButtonJs); var _playbackRateMenuPlaybackRateMenuButtonJs = _dereq_('./playback-rate-menu/playback-rate-menu-button.js'); var _playbackRateMenuPlaybackRateMenuButtonJs2 = _interopRequireDefault(_playbackRateMenuPlaybackRateMenuButtonJs); var _spacerControlsCustomControlSpacerJs = _dereq_('./spacer-controls/custom-control-spacer.js'); var _spacerControlsCustomControlSpacerJs2 = _interopRequireDefault(_spacerControlsCustomControlSpacerJs); /** * Container of main controls * * @extends Component * @class ControlBar */ var ControlBar = (function (_Component) { _inherits(ControlBar, _Component); function ControlBar() { _classCallCheck(this, ControlBar); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar' }); }; return ControlBar; })(_componentJs2['default']); ControlBar.prototype.options_ = { loadEvent: 'play', children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle'] }; _componentJs2['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; module.exports = exports['default']; },{"../component.js":48,"./fullscreen-toggle.js":50,"./live-display.js":51,"./mute-toggle.js":52,"./play-toggle.js":53,"./playback-rate-menu/playback-rate-menu-button.js":54,"./progress-control/progress-control.js":58,"./spacer-controls/custom-control-spacer.js":60,"./text-track-controls/captions-button.js":63,"./text-track-controls/chapters-button.js":64,"./text-track-controls/subtitles-button.js":67,"./time-controls/current-time-display.js":70,"./time-controls/duration-display.js":71,"./time-controls/remaining-time-display.js":72,"./time-controls/time-divider.js":73,"./volume-control/volume-control.js":75,"./volume-menu-button.js":77}],50:[function(_dereq_,module,exports){ /** * @file fullscreen-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Toggle fullscreen video * * @extends Button * @class FullscreenToggle */ var FullscreenToggle = (function (_Button) { _inherits(FullscreenToggle, _Button); function FullscreenToggle() { _classCallCheck(this, FullscreenToggle); _Button.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles click for full screen * * @method handleClick */ FullscreenToggle.prototype.handleClick = function handleClick() { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText('Fullscreen'); } }; return FullscreenToggle; })(_buttonJs2['default']); FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _componentJs2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; module.exports = exports['default']; },{"../button.js":47,"../component.js":48}],51:[function(_dereq_,module,exports){ /** * @file live-display.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Displays the live indicator * TODO - Future make it click to snap to live * * @extends Component * @class LiveDisplay */ var LiveDisplay = (function (_Component) { _inherits(LiveDisplay, _Component); function LiveDisplay(player, options) { _classCallCheck(this, LiveDisplay); _Component.call(this, player, options); this.updateShowing(); this.on(this.player(), 'durationchange', this.updateShowing); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'), 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; LiveDisplay.prototype.updateShowing = function updateShowing() { if (this.player().duration() === Infinity) { this.show(); } else { this.hide(); } }; return LiveDisplay; })(_component2['default']); _component2['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; module.exports = exports['default']; },{"../component":48,"../utils/dom.js":107}],52:[function(_dereq_,module,exports){ /** * @file mute-toggle.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _button = _dereq_('../button'); var _button2 = _interopRequireDefault(_button); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * A button component for muting the audio * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MuteToggle */ var MuteToggle = (function (_Button) { _inherits(MuteToggle, _Button); function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); _Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { this.update(); // We need to update the button to account for a default muted state. if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click on mute * * @method handleClick */ MuteToggle.prototype.handleClick = function handleClick() { this.player_.muted(this.player_.muted() ? false : true); }; /** * Update volume * * @method update */ MuteToggle.prototype.update = function update() { var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; var localizedMute = this.localize(toMute); if (this.controlText() !== localizedMute) { this.controlText(localizedMute); } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { Dom.removeElClass(this.el_, 'vjs-vol-' + i); } Dom.addElClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; })(_button2['default']); MuteToggle.prototype.controlText_ = 'Mute'; _component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; module.exports = exports['default']; },{"../button":47,"../component":48,"../utils/dom.js":107}],53:[function(_dereq_,module,exports){ /** * @file play-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Button to toggle between play and pause * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PlayToggle */ var PlayToggle = (function (_Button) { _inherits(PlayToggle, _Button); function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); _Button.call(this, player, options); this.on(player, 'play', this.handlePlay); this.on(player, 'pause', this.handlePause); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click to toggle between play and pause * * @method handleClick */ PlayToggle.prototype.handleClick = function handleClick() { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance * * @method handlePlay */ PlayToggle.prototype.handlePlay = function handlePlay() { this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.controlText('Pause'); // change the button text to "Pause" }; /** * Add the vjs-paused class to the element so it can change appearance * * @method handlePause */ PlayToggle.prototype.handlePause = function handlePause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.controlText('Play'); // change the button text to "Play" }; return PlayToggle; })(_buttonJs2['default']); PlayToggle.prototype.controlText_ = 'Play'; _componentJs2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; module.exports = exports['default']; },{"../button.js":47,"../component.js":48}],54:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-button.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _playbackRateMenuItemJs = _dereq_('./playback-rate-menu-item.js'); var _playbackRateMenuItemJs2 = _interopRequireDefault(_playbackRateMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * The component for controlling the playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class PlaybackRateMenuButton */ var PlaybackRateMenuButton = (function (_MenuButton) { _inherits(PlaybackRateMenuButton, _MenuButton); function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); _MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} Menu object populated with items * @method createMenu */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _menuMenuJs2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _playbackRateMenuItemJs2['default'](this.player(), { 'rate': rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes * * @method updateARIAAttributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * Handle menu item click * * @method handleClick */ PlaybackRateMenuButton.prototype.handleClick = function handleClick() { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} Possible playback rates * @method playbackRates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_['playbackRates'] || this.options_.playerOptions && this.options_.playerOptions['playbackRates']; }; /** * Get supported playback rates * * @return {Array} Supported playback rates * @method playbackRateSupported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech && this.player().tech['featuresPlaybackRate'] && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @method updateVisibility */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @method updateLabel */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; })(_menuMenuButtonJs2['default']); PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _componentJs2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-button.js":84,"../../menu/menu.js":86,"../../utils/dom.js":107,"./playback-rate-menu-item.js":55}],55:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The specific menu item type for selecting a playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class PlaybackRateMenuItem */ var PlaybackRateMenuItem = (function (_MenuItem) { _inherits(PlaybackRateMenuItem, _MenuItem); function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options['rate']; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; _MenuItem.call(this, player, options); this.label = label; this.rate = rate; this.on(player, 'ratechange', this.update); } /** * Handle click on menu item * * @method handleClick */ PlaybackRateMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update playback rate with selected rate * * @method update */ PlaybackRateMenuItem.prototype.update = function update() { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; })(_menuMenuItemJs2['default']); PlaybackRateMenuItem.prototype.contentElType = 'button'; _componentJs2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-item.js":85}],56:[function(_dereq_,module,exports){ /** * @file load-progress-bar.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Shows load progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class LoadProgressBar */ var LoadProgressBar = (function (_Component) { _inherits(LoadProgressBar, _Component); function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); _Component.call(this, player, options); this.on(player, 'progress', this.update); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @method update */ LoadProgressBar.prototype.update = function update() { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.el_.children; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { var percent = time / end || 0; // no NaN return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i - 1]); } }; return LoadProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107}],57:[function(_dereq_,module,exports){ /** * @file play-progress-bar.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Shows play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class PlayProgressBar */ var PlayProgressBar = (function (_Component) { _inherits(PlayProgressBar, _Component); function PlayProgressBar(player, options) { _classCallCheck(this, PlayProgressBar); _Component.call(this, player, options); this.updateDataAttr(); this.on(player, 'timeupdate', this.updateDataAttr); player.ready(Fn.bind(this, this.updateDataAttr)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('data-current-time', _utilsFormatTimeJs2['default'](time, this.player_.duration())); }; return PlayProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; module.exports = exports['default']; },{"../../component.js":48,"../../utils/fn.js":109,"../../utils/format-time.js":110}],58:[function(_dereq_,module,exports){ /** * @file progress-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _seekBarJs = _dereq_('./seek-bar.js'); var _seekBarJs2 = _interopRequireDefault(_seekBarJs); /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class ProgressControl */ var ProgressControl = (function (_Component) { _inherits(ProgressControl, _Component); function ProgressControl() { _classCallCheck(this, ProgressControl); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; return ProgressControl; })(_componentJs2['default']); ProgressControl.prototype.options_ = { children: { 'seekBar': {} } }; _componentJs2['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; module.exports = exports['default']; },{"../../component.js":48,"./seek-bar.js":59}],59:[function(_dereq_,module,exports){ /** * @file seek-bar.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _loadProgressBarJs = _dereq_('./load-progress-bar.js'); var _loadProgressBarJs2 = _interopRequireDefault(_loadProgressBarJs); var _playProgressBarJs = _dereq_('./play-progress-bar.js'); var _playProgressBarJs2 = _interopRequireDefault(_playProgressBarJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Seek Bar and holder for the progress bars * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class SeekBar */ var SeekBar = (function (_Slider) { _inherits(SeekBar, _Slider); function SeekBar(player, options) { _classCallCheck(this, SeekBar); _Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext', _utilsFormatTimeJs2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete) }; /** * Get percentage of video played * * @return {Number} Percentage played * @method getPercent */ SeekBar.prototype.getPercent = function getPercent() { var percent = this.player_.currentTime() / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @method handleMouseDown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { _Slider.prototype.handleMouseDown.call(this, event); this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; /** * Handle mouse move on seek bar * * @method handleMouseMove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @method handleMouseUp */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users * * @method stepForward */ SeekBar.prototype.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; /** * Move more quickly rewind for keyboard-only users * * @method stepBack */ SeekBar.prototype.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; return SeekBar; })(_sliderSliderJs2['default']); SeekBar.prototype.options_ = { children: { 'loadProgressBar': {}, 'playProgressBar': {} }, 'barName': 'playProgressBar' }; SeekBar.prototype.playerEvent = 'timeupdate'; _componentJs2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; module.exports = exports['default']; },{"../../component.js":48,"../../slider/slider.js":91,"../../utils/fn.js":109,"../../utils/format-time.js":110,"./load-progress-bar.js":56,"./play-progress-bar.js":57}],60:[function(_dereq_,module,exports){ /** * @file custom-control-spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _spacerJs = _dereq_('./spacer.js'); var _spacerJs2 = _interopRequireDefault(_spacerJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer * @class CustomControlSpacer */ var CustomControlSpacer = (function (_Spacer) { _inherits(CustomControlSpacer, _Spacer); function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); _Spacer.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ CustomControlSpacer.prototype.createEl = function createEl() { var el = _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. el.innerHTML = '&nbsp;'; return el; }; return CustomControlSpacer; })(_spacerJs2['default']); _componentJs2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; module.exports = exports['default']; },{"../../component.js":48,"./spacer.js":61}],61:[function(_dereq_,module,exports){ /** * @file spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component * @class Spacer */ var Spacer = (function (_Component) { _inherits(Spacer, _Component); function Spacer() { _classCallCheck(this, Spacer); _Component.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @param {Object} props An object of properties * @return {Element} * @method createEl */ Spacer.prototype.createEl = function createEl(props) { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; module.exports = exports['default']; },{"../../component.js":48}],62:[function(_dereq_,module,exports){ /** * @file caption-settings-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The menu item for caption track settings menu * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class CaptionSettingsMenuItem */ var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) { _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' settings', 'default': false, mode: 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); } /** * Handle click on menu item * * @method handleClick */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick() { this.player().getChild('textTrackSettings').show(); }; return CaptionSettingsMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; module.exports = exports['default']; },{"../../component.js":48,"./text-track-menu-item.js":69}],63:[function(_dereq_,module,exports){ /** * @file captions-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _captionSettingsMenuItemJs = _dereq_('./caption-settings-menu-item.js'); var _captionSettingsMenuItemJs2 = _interopRequireDefault(_captionSettingsMenuItemJs); /** * The button component for toggling and selecting captions * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class CaptionsButton */ var CaptionsButton = (function (_TextTrackButton) { _inherits(CaptionsButton, _TextTrackButton); function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Captions Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update caption menu items * * @method update */ CaptionsButton.prototype.update = function update() { var threshold = 2; _TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech && this.player().tech['featuresNativeTextTracks']) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * Create caption menu items * * @return {Array} Array of menu items * @method createItems */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech && this.player().tech['featuresNativeTextTracks'])) { items.push(new _captionSettingsMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; })(_textTrackButtonJs2['default']); CaptionsButton.prototype.kind_ = 'captions'; CaptionsButton.prototype.controlText_ = 'Captions'; _componentJs2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; module.exports = exports['default']; },{"../../component.js":48,"./caption-settings-menu-item.js":62,"./text-track-button.js":68}],64:[function(_dereq_,module,exports){ /** * @file chapters-button.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _chaptersTrackMenuItemJs = _dereq_('./chapters-track-menu-item.js'); var _chaptersTrackMenuItemJs2 = _interopRequireDefault(_chaptersTrackMenuItemJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class ChaptersButton */ var ChaptersButton = (function (_TextTrackButton) { _inherits(ChaptersButton, _TextTrackButton); function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Chapters Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each text track * * @return {Array} Array of menu items * @method createItems */ ChaptersButton.prototype.createItems = function createItems() { var items = []; var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { 'track': track })); } } return items; }; /** * Create menu from chapter buttons * * @return {Menu} Menu of chapter buttons * @method createMenu */ ChaptersButton.prototype.createMenu = function createMenu() { var tracks = this.player_.textTracks() || []; var chaptersTrack = undefined; var items = this.items = []; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { if (!track.cues) { track['mode'] = 'hidden'; /* jshint loopfunc:true */ // TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864 _globalWindow2['default'].setTimeout(Fn.bind(this, function () { this.createMenu(); }), 100); /* jshint loopfunc:false */ } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new _menuMenuJs2['default'](this.player_); menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.kind_), tabIndex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack['cues'], cue = undefined; for (var i = 0, l = cues.length; i < l; i++) { cue = cues[i]; var mi = new _chaptersTrackMenuItemJs2['default'](this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; return ChaptersButton; })(_textTrackButtonJs2['default']); ChaptersButton.prototype.kind_ = 'chapters'; ChaptersButton.prototype.controlText_ = 'Chapters'; _componentJs2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu.js":86,"../../utils/dom.js":107,"../../utils/fn.js":109,"../../utils/to-title-case.js":116,"./chapters-track-menu-item.js":65,"./text-track-button.js":68,"./text-track-menu-item.js":69,"global/window":2}],65:[function(_dereq_,module,exports){ /** * @file chapters-track-menu-item.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); /** * The chapter track menu item * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class ChaptersTrackMenuItem */ var ChaptersTrackMenuItem = (function (_MenuItem) { _inherits(ChaptersTrackMenuItem, _MenuItem); function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options['track']; var cue = options['cue']; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = cue['startTime'] <= currentTime && currentTime < cue['endTime']; _MenuItem.call(this, player, options); this.track = track; this.cue = cue; track.addEventListener('cuechange', Fn.bind(this, this.update)); } /** * Handle click on menu item * * @method handleClick */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @method update */ ChaptersTrackMenuItem.prototype.update = function update() { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']); }; return ChaptersTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-item.js":85,"../../utils/fn.js":109}],66:[function(_dereq_,module,exports){ /** * @file off-text-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * A special menu item for turning of a specific type of text track * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class OffTextTrackMenuItem */ var OffTextTrackMenuItem = (function (_TextTrackMenuItem) { _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' off', 'default': false, 'mode': 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.selected(true); } /** * Handle text track change * * @param {Object} event Event object * @method handleTracksChange */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":48,"./text-track-menu-item.js":69}],67:[function(_dereq_,module,exports){ /** * @file subtitles-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The button component for toggling and selecting subtitles * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class SubtitlesButton */ var SubtitlesButton = (function (_TextTrackButton) { _inherits(SubtitlesButton, _TextTrackButton); function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Subtitles Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; })(_textTrackButtonJs2['default']); SubtitlesButton.prototype.kind_ = 'subtitles'; SubtitlesButton.prototype.controlText_ = 'Subtitles'; _componentJs2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; module.exports = exports['default']; },{"../../component.js":48,"./text-track-button.js":68}],68:[function(_dereq_,module,exports){ /** * @file text-track-button.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _offTextTrackMenuItemJs = _dereq_('./off-text-track-menu-item.js'); var _offTextTrackMenuItemJs2 = _interopRequireDefault(_offTextTrackMenuItemJs); /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class TextTrackButton */ var TextTrackButton = (function (_MenuButton) { _inherits(TextTrackButton, _MenuButton); function TextTrackButton(player, options) { _classCallCheck(this, TextTrackButton); _MenuButton.call(this, player, options); var tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } var updateHandler = Fn.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } // Create a menu item for each text track TextTrackButton.prototype.createItems = function createItems() { var items = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; // Add an OFF menu item to turn all tracks off items.push(new _offTextTrackMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { 'track': track })); } } return items; }; return TextTrackButton; })(_menuMenuButtonJs2['default']); _componentJs2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-button.js":84,"../../utils/fn.js":109,"./off-text-track-menu-item.js":66,"./text-track-menu-item.js":69}],69:[function(_dereq_,module,exports){ /** * @file text-track-menu-item.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * The specific menu item type for selecting a language within a text track kind * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class TextTrackMenuItem */ var TextTrackMenuItem = (function (_MenuItem) { _inherits(TextTrackMenuItem, _MenuItem); function TextTrackMenuItem(player, options) { var _this = this; _classCallCheck(this, TextTrackMenuItem); var track = options['track']; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options['label'] = track['label'] || track['language'] || 'Unknown'; options['selected'] = track['default'] || track['mode'] === 'showing'; _MenuItem.call(this, player, options); this.track = track; if (tracks) { (function () { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); })(); } // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { (function () { var event = undefined; _this.on(['tap', 'click'], function () { if (typeof _globalWindow2['default'].Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _globalWindow2['default'].Event('change'); } catch (err) {} } if (!event) { event = _globalDocument2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); })(); } } /** * Handle click on text track * * @method handleClick */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track['kind']; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) return; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] !== kind) { continue; } if (track === this.track) { track['mode'] = 'showing'; } else { track['mode'] = 'disabled'; } } }; /** * Handle text track change * * @method handleTracksChange */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track['mode'] === 'showing'); }; return TextTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-item.js":85,"../../utils/fn.js":109,"global/document":1,"global/window":2}],70:[function(_dereq_,module,exports){ /** * @file current-time-display.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the current time * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class CurrentTimeDisplay */ var CurrentTimeDisplay = (function (_Component) { _inherits(CurrentTimeDisplay, _Component); function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @method updateContent */ CurrentTimeDisplay.prototype.updateContent = function updateContent() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = _utilsFormatTimeJs2['default'](time, this.player_.duration()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; }; return CurrentTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107,"../../utils/format-time.js":110}],71:[function(_dereq_,module,exports){ /** * @file duration-display.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the duration * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class DurationDisplay */ var DurationDisplay = (function (_Component) { _inherits(DurationDisplay, _Component); function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); _Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display * * @method updateContent */ DurationDisplay.prototype.updateContent = function updateContent() { var duration = this.player_.duration(); if (duration) { var localizedText = this.localize('Duration Time'); var formattedTime = _utilsFormatTimeJs2['default'](duration); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users } }; return DurationDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107,"../../utils/format-time.js":110}],72:[function(_dereq_,module,exports){ /** * @file remaining-time-display.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the time left in the video * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class RemainingTimeDisplay */ var RemainingTimeDisplay = (function (_Component) { _inherits(RemainingTimeDisplay, _Component); function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display * * @method updateContent */ RemainingTimeDisplay.prototype.updateContent = function updateContent() { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = _utilsFormatTimeJs2['default'](this.player_.remainingTime()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107,"../../utils/format-time.js":110}],73:[function(_dereq_,module,exports){ /** * @file time-divider.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class TimeDivider */ var TimeDivider = (function (_Component) { _inherits(TimeDivider, _Component); function TimeDivider() { _classCallCheck(this, TimeDivider); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; module.exports = exports['default']; },{"../../component.js":48}],74:[function(_dereq_,module,exports){ /** * @file volume-bar.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); // Required children var _volumeLevelJs = _dereq_('./volume-level.js'); var _volumeLevelJs2 = _interopRequireDefault(_volumeLevelJs); /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class VolumeBar */ var VolumeBar = (function (_Slider) { _inherits(VolumeBar, _Slider); function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); _Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; /** * Handle mouse move on volume bar * * @method handleMouseMove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; /** * Get percent of volume level * * @retun {Number} Volume level percent * @method getPercent */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; /** * Increase volume level for keyboard users * * @method stepForward */ VolumeBar.prototype.stepForward = function stepForward() { this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users * * @method stepBack */ VolumeBar.prototype.stepBack = function stepBack() { this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current value of volume bar as a percentage var volume = (this.player_.volume() * 100).toFixed(2); this.el_.setAttribute('aria-valuenow', volume); this.el_.setAttribute('aria-valuetext', volume + '%'); }; return VolumeBar; })(_sliderSliderJs2['default']); VolumeBar.prototype.options_ = { children: { 'volumeLevel': {} }, 'barName': 'volumeLevel' }; VolumeBar.prototype.playerEvent = 'volumechange'; _componentJs2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; module.exports = exports['default']; },{"../../component.js":48,"../../slider/slider.js":91,"../../utils/fn.js":109,"./volume-level.js":76}],75:[function(_dereq_,module,exports){ /** * @file volume-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _volumeBarJs = _dereq_('./volume-bar.js'); var _volumeBarJs2 = _interopRequireDefault(_volumeBarJs); /** * The component for controlling the volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeControl */ var VolumeControl = (function (_Component) { _inherits(VolumeControl, _Component); function VolumeControl(player, options) { _classCallCheck(this, VolumeControl); _Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; return VolumeControl; })(_componentJs2['default']); VolumeControl.prototype.options_ = { children: { 'volumeBar': {} } }; _componentJs2['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; module.exports = exports['default']; },{"../../component.js":48,"./volume-bar.js":74}],76:[function(_dereq_,module,exports){ /** * @file volume-level.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Shows volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeLevel */ var VolumeLevel = (function (_Component) { _inherits(VolumeLevel, _Component); function VolumeLevel() { _classCallCheck(this, VolumeLevel); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; })(_componentJs2['default']); _componentJs2['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; module.exports = exports['default']; },{"../../component.js":48}],77:[function(_dereq_,module,exports){ /** * @file volume-menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _menuMenuJs = _dereq_('../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _menuMenuButtonJs = _dereq_('../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _volumeControlVolumeBarJs = _dereq_('./volume-control/volume-bar.js'); var _volumeControlVolumeBarJs2 = _interopRequireDefault(_volumeControlVolumeBarJs); /** * Button for volume menu * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class VolumeMenuButton */ var VolumeMenuButton = (function (_MenuButton) { _inherits(VolumeMenuButton, _MenuButton); function VolumeMenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, VolumeMenuButton); // Default to inline if (options.inline === undefined) { options.inline = true; } // If the vertical option isn't passed at all, default to true. if (options.vertical === undefined) { // If an inline volumeMenuButton is used, we should default to using // a horizontal slider for obvious reasons. if (options.inline) { options.vertical = false; } else { options.vertical = true; } } // The vertical option needs to be set on the volumeBar as well, // since that will need to be passed along to the VolumeBar constructor options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = !!options.vertical; _MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); this.on(player, 'loadstart', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control function updateVisibility() { if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } } updateVisibility.call(this); this.on(player, 'loadstart', updateVisibility); this.on(this.volumeBar, ['slideractive', 'focus'], function () { this.addClass('vjs-slider-active'); }); this.on(this.volumeBar, ['sliderinactive', 'blur'], function () { this.removeClass('vjs-slider-active'); }); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() { var orientationClass = ''; if (!!this.options_.vertical) { orientationClass = 'vjs-volume-menu-button-vertical'; } else { orientationClass = 'vjs-volume-menu-button-horizontal'; } return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass; }; /** * Allow sub components to stack CSS class names * * @return {Menu} The volume menu button * @method createMenu */ VolumeMenuButton.prototype.createMenu = function createMenu() { var menu = new _menuMenuJs2['default'](this.player_, { contentElType: 'div' }); var vb = new _volumeControlVolumeBarJs2['default'](this.player_, this.options_.volumeBar); menu.addChild(vb); this.volumeBar = vb; return menu; }; /** * Handle click on volume menu and calls super * * @method handleClick */ VolumeMenuButton.prototype.handleClick = function handleClick() { _muteToggleJs2['default'].prototype.handleClick.call(this); _MenuButton.prototype.handleClick.call(this); }; return VolumeMenuButton; })(_menuMenuButtonJs2['default']); VolumeMenuButton.prototype.volumeUpdate = _muteToggleJs2['default'].prototype.update; VolumeMenuButton.prototype.controlText_ = 'Mute'; _componentJs2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton); exports['default'] = VolumeMenuButton; module.exports = exports['default']; },{"../button.js":47,"../component.js":48,"../menu/menu-button.js":84,"../menu/menu.js":86,"./mute-toggle.js":52,"./volume-control/volume-bar.js":74}],78:[function(_dereq_,module,exports){ /** * @file error-display.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Display that an error has occurred making the video unplayable * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class ErrorDisplay */ var ErrorDisplay = (function (_Component) { _inherits(ErrorDisplay, _Component); function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); _Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ErrorDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = Dom.createEl('div'); el.appendChild(this.contentEl_); return el; }; /** * Update the error message in localized language * * @method update */ ErrorDisplay.prototype.update = function update() { if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; return ErrorDisplay; })(_component2['default']); _component2['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; module.exports = exports['default']; },{"./component":48,"./utils/dom.js":107}],79:[function(_dereq_,module,exports){ /** * @file event-target.js */ 'use strict'; exports.__esModule = true; 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; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var EventTarget = function EventTarget() {}; EventTarget.prototype.allowedEvents_ = {}; EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; Events.on(this, type, fn); this.addEventListener = ael; }; EventTarget.prototype.addEventListener = EventTarget.prototype.on; EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; EventTarget.prototype.removeEventListener = EventTarget.prototype.off; EventTarget.prototype.one = function (type, fn) { Events.one(this, type, fn); }; EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; module.exports = exports['default']; },{"./utils/events.js":108}],80:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsLog = _dereq_('./utils/log'); var _utilsLog2 = _interopRequireDefault(_utilsLog); /* * @file extends.js * * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. */ var _inherits = function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { // node subClass.super_ = superClass; } }; /* * Function for subclassing using the same inheritance that * videojs uses internally * ```js * var Button = videojs.getComponent('Button'); * ``` * ```js * var MyButton = videojs.extends(Button, { * constructor: function(player, options) { * Button.call(this, player, options); * }, * onClick: function() { * // doSomething * } * }); * ``` */ var extendsFn = function extendsFn(superClass) { var subClassMethods = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if (typeof subClassMethods === 'object') { if (typeof subClassMethods.init === 'function') { _utilsLog2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.'); subClassMethods.constructor = subClassMethods.init; } if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendsFn; module.exports = exports['default']; },{"./utils/log":112}],81:[function(_dereq_,module,exports){ /** * @file fullscreen-api.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ var FullscreenApi = {}; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js var apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html ['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = undefined; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _globalDocument2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var i = 0; i < browserApi.length; i++) { FullscreenApi[specApi[i]] = browserApi[i]; } } exports['default'] = FullscreenApi; module.exports = exports['default']; },{"global/document":1}],82:[function(_dereq_,module,exports){ /** * @file loading-spinner.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * * @extends Component * @class LoadingSpinner */ var LoadingSpinner = (function (_Component) { _inherits(LoadingSpinner, _Component); function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @method createEl */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; return LoadingSpinner; })(_component2['default']); _component2['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; module.exports = exports['default']; },{"./component":48}],83:[function(_dereq_,module,exports){ /** * @file media-error.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /* * Custom MediaError to mimic the HTML5 MediaError * * @param {Number} code The media error code */ var MediaError = function MediaError(code) { if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object _objectAssign2['default'](this, code); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } }; /* * The error code that refers two one of the defined * MediaError types * * @type {Number} */ MediaError.prototype.code = 0; /* * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /* * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * * @type {Array} */ MediaError.prototype.status = null; MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } exports['default'] = MediaError; module.exports = exports['default']; },{"object.assign":40}],84:[function(_dereq_,module,exports){ /** * @file menu-button.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _menuJs = _dereq_('./menu.js'); var _menuJs2 = _interopRequireDefault(_menuJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * A button class with a popup menu * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuButton */ var MenuButton = (function (_Button) { _inherits(MenuButton, _Button); function MenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, MenuButton); _Button.call(this, player, options); this.update(); this.on('keydown', this.handleKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } /** * Update menu * * @method update */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create menu * * @return {Menu} The constructed menu * @method createMenu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _menuJs2['default'](this.player_); // Add a title list item to the top if (this.options_.title) { menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.options_.title), tabIndex: -1 })); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @method createItems */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the component's DOM element * * @return {Element} * @method createEl */ MenuButton.prototype.createEl = function createEl() { return _Button.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _Button.prototype.buildCSSClass.call(this); }; /** * Focus - Add keyboard functionality to element * This function is not needed anymore. Instead, the * keyboard functionality is handled by * treating the button as triggering a submenu. * When the button is pressed, the submenu * appears. Pressing the button again makes * the submenu disappear. * * @method handleFocus */ MenuButton.prototype.handleFocus = function handleFocus() {}; /** * Can't turn off list display that we turned * on with focus, because list would go away. * * @method handleBlur */ MenuButton.prototype.handleBlur = function handleBlur() {}; /** * When you click the button it adds focus, which * will show the menu indefinitely. * So we'll remove focus when the mouse leaves the button. * Focus is needed for tab navigation. * Allow sub components to stack CSS class names * * @method handleClick */ MenuButton.prototype.handleClick = function handleClick() { this.one('mouseout', Fn.bind(this, function () { this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle key press on menu * * @param {Object} Key press event * @method handleKeyPress */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which === 27) { if (this.buttonPressed_) { this.unpressButton(); } event.preventDefault(); } }; /** * Makes changes based on button pressed * * @method pressButton */ MenuButton.prototype.pressButton = function pressButton() { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; /** * Makes changes based on button unpressed * * @method unpressButton */ MenuButton.prototype.unpressButton = function unpressButton() { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; return MenuButton; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; module.exports = exports['default']; },{"../button.js":47,"../component.js":48,"../utils/dom.js":107,"../utils/fn.js":109,"../utils/to-title-case.js":116,"./menu.js":86}],85:[function(_dereq_,module,exports){ /** * @file menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The component for a menu item. `<li>` * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuItem */ var MenuItem = (function (_Button) { _inherits(MenuItem, _Button); function MenuItem(player, options) { _classCallCheck(this, MenuItem); _Button.call(this, player, options); this.selected(options['selected']); } /** * Create the component's DOM element * * @param {String=} type Desc * @param {Object=} props Desc * @return {Element} * @method createEl */ MenuItem.prototype.createEl = function createEl(type, props) { return _Button.prototype.createEl.call(this, 'li', _objectAssign2['default']({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']) }, props)); }; /** * Handle a click on the menu item, and set it to selected * * @method handleClick */ MenuItem.prototype.handleClick = function handleClick() { this.selected(true); }; /** * Set this menu item as selected or not * * @param {Boolean} selected * @method selected */ MenuItem.prototype.selected = function selected(_selected) { if (_selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected', true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected', false); } }; return MenuItem; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; module.exports = exports['default']; },{"../button.js":47,"../component.js":48,"object.assign":40}],86:[function(_dereq_,module,exports){ /** * @file menu.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @extends Component * @class Menu */ var Menu = (function (_Component) { _inherits(Menu, _Component); function Menu() { _classCallCheck(this, Menu); _Component.apply(this, arguments); } /** * Add a menu item to the menu * * @param {Object|String} component Component or component type to add * @method addItem */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); })); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; return Menu; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Menu', Menu); exports['default'] = Menu; module.exports = exports['default']; },{"../component.js":48,"../utils/dom.js":107,"../utils/events.js":108,"../utils/fn.js":109}],87:[function(_dereq_,module,exports){ /** * @file player.js */ // Subclasses Component 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsBufferJs = _dereq_('./utils/buffer.js'); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _fullscreenApiJs = _dereq_('./fullscreen-api.js'); var _fullscreenApiJs2 = _interopRequireDefault(_fullscreenApiJs); var _mediaErrorJs = _dereq_('./media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); var _tracksTextTrackListConverterJs = _dereq_('./tracks/text-track-list-converter.js'); var _tracksTextTrackListConverterJs2 = _interopRequireDefault(_tracksTextTrackListConverterJs); // Include required child components (importing also registers them) var _techLoaderJs = _dereq_('./tech/loader.js'); var _techLoaderJs2 = _interopRequireDefault(_techLoaderJs); var _posterImageJs = _dereq_('./poster-image.js'); var _posterImageJs2 = _interopRequireDefault(_posterImageJs); var _tracksTextTrackDisplayJs = _dereq_('./tracks/text-track-display.js'); var _tracksTextTrackDisplayJs2 = _interopRequireDefault(_tracksTextTrackDisplayJs); var _loadingSpinnerJs = _dereq_('./loading-spinner.js'); var _loadingSpinnerJs2 = _interopRequireDefault(_loadingSpinnerJs); var _bigPlayButtonJs = _dereq_('./big-play-button.js'); var _bigPlayButtonJs2 = _interopRequireDefault(_bigPlayButtonJs); var _controlBarControlBarJs = _dereq_('./control-bar/control-bar.js'); var _controlBarControlBarJs2 = _interopRequireDefault(_controlBarControlBarJs); var _errorDisplayJs = _dereq_('./error-display.js'); var _errorDisplayJs2 = _interopRequireDefault(_errorDisplayJs); var _tracksTextTrackSettingsJs = _dereq_('./tracks/text-track-settings.js'); var _tracksTextTrackSettingsJs2 = _interopRequireDefault(_tracksTextTrackSettingsJs); // Require html5 tech, at least for disposing the original video tag var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); /** * An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video. * ```js * var myPlayer = videojs('example_video_1'); * ``` * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class Player */ var Player = (function (_Component) { _inherits(Player, _Component); /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ function Player(tag, options, ready) { var _this = this; _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = _objectAssign2['default'](Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options _Component.call(this, null, options, ready); // if the global option object was accidentally blown away by // someone, bail early with an informative error if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } this.tag = tag; // Store the original tag used to set options // Store the tag attributes used to restore html5 element this.tagAttributes = tag && Dom.getElAttributes(tag); // Update current language this.language(this.options_.language); // Update Supported Languages if (options.languages) { (function () { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; })(); } else { this.languages_ = Player.prototype.options_.languages; } // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options.poster || ''; // Set controls this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ this.scrubbing_ = false; this.el_ = this.createEl(); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = _utilsMergeOptionsJs2['default'](this.options_); // Load plugins if (options.plugins) { (function () { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _utilsLogJs2['default'].error('Unable to find plugin:', name); } }, _this); })(); } this.options_.playerOptions = playerOptionsCopy; this.initChildren(); // Set isAudio based on whether or not an audio tag was used this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } if (this.flexNotSupported_()) { this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID Player.players[this.id_] = this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed this.userActive(true); this.reportUserActivity(); this.listenForUserActivity(); this.on('fullscreenchange', this.handleFullscreenChange); this.on('stageclick', this.handleStageClick); } /* * Global player list * * @type {Object} */ /** * Destroys the video player and does any necessary cleanup * ```js * myPlayer.dispose(); * ``` * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @method dispose */ Player.prototype.dispose = function dispose() { this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); if (this.styleEl_) { this.styleEl_.parentNode.removeChild(this.styleEl_); } // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech) { this.tech.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Player.prototype.createEl = function createEl() { var el = this.el_ = _Component.prototype.createEl.call(this, 'div'); var tag = this.tag; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = _globalDocument2['default'].querySelector('.vjs-styles-defaults'); var head = _globalDocument2['default'].querySelector('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. this.el_ = el; return el; }; /** * Get/set player width * * @param {Number=} value Value for width * @return {Number} Width when getting * @method width */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * Get/set player height * * @param {Number=} value Value for height * @return {Number} Height when getting * @method height */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * Get/set dimension for player * * @param {String} dimension Either width or height * @param {Number=} value Value for dimension * @return {Component} * @method dimension */ Player.prototype.dimension = function dimension(_dimension, value) { var privDimension = _dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _utilsLogJs2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }; /** * Add/remove the vjs-fluid class * * @param {Boolean} bool Value of true adds the class, value of false removes the class * @method fluid */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } }; /** * Get/Set the aspect ratio * * @param {String=} ratio Aspect ratio for player * @return aspectRatio * @method aspectRatio */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the player element (height, width and aspect ratio) * * @method updateStyleEl_ */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { var width = undefined; var height = undefined; var aspectRatio = undefined; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth()) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } var idClass = this.id() + '-dimensions'; // Ensure the right class is still on the player for the style element this.addClass(idClass); stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n '); }; /** * Load the Media Playback Technology (tech) * Load/Create an instance of playback technology including element and API methods * And append playback element in player div. * * @param {String} techName Name of the playback technology * @param {String} source Video source * @method loadTech */ Player.prototype.loadTech = function loadTech(techName, source) { // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _componentJs2['default'].getComponent('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = Fn.bind(this, function () { this.triggerReady(); }); // Grab tech-specific options from player options and add source and parent element to use. var techOptions = _objectAssign2['default']({ 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'source': source, 'playerId': this.id(), 'techId': this.id() + '_' + techName + '_api', 'textTracks': this.textTracks_, 'autoplay': this.options_.autoplay, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'vtt.js': this.options_['vtt.js'] }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance var techComponent = _componentJs2['default'].getComponent(techName); this.tech = new techComponent(techOptions); _tracksTextTrackListConverterJs2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech); this.on(this.tech, 'ready', this.handleTechReady); // Listen to every HTML5 events and trigger them back on the player for the plugins this.on(this.tech, 'loadstart', this.handleTechLoadStart); this.on(this.tech, 'waiting', this.handleTechWaiting); this.on(this.tech, 'canplay', this.handleTechCanPlay); this.on(this.tech, 'canplaythrough', this.handleTechCanPlayThrough); this.on(this.tech, 'playing', this.handleTechPlaying); this.on(this.tech, 'ended', this.handleTechEnded); this.on(this.tech, 'seeking', this.handleTechSeeking); this.on(this.tech, 'seeked', this.handleTechSeeked); this.on(this.tech, 'play', this.handleTechPlay); this.on(this.tech, 'firstplay', this.handleTechFirstPlay); this.on(this.tech, 'pause', this.handleTechPause); this.on(this.tech, 'progress', this.handleTechProgress); this.on(this.tech, 'durationchange', this.handleTechDurationChange); this.on(this.tech, 'fullscreenchange', this.handleTechFullscreenChange); this.on(this.tech, 'error', this.handleTechError); this.on(this.tech, 'suspend', this.handleTechSuspend); this.on(this.tech, 'abort', this.handleTechAbort); this.on(this.tech, 'emptied', this.handleTechEmptied); this.on(this.tech, 'stalled', this.handleTechStalled); this.on(this.tech, 'loadedmetadata', this.handleTechLoadedMetaData); this.on(this.tech, 'loadeddata', this.handleTechLoadedData); this.on(this.tech, 'timeupdate', this.handleTechTimeUpdate); this.on(this.tech, 'ratechange', this.handleTechRateChange); this.on(this.tech, 'volumechange', this.handleTechVolumeChange); this.on(this.tech, 'texttrackchange', this.onTextTrackChange); this.on(this.tech, 'loadedmetadata', this.updateStyleEl_); this.usingNativeControls(this.techGet('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } // player.triggerReady is always async, so don't need this to be async this.tech.ready(techReady, true); }; /** * Unload playback technology * * @method unloadTech */ Player.prototype.unloadTech = function unloadTech() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.textTracks_ = this.textTracks(); this.textTracksJson_ = _tracksTextTrackListConverterJs2['default'].textTracksToJson(this); this.isReady_ = false; this.tech.dispose(); this.tech = false; }; /** * Add playback technology listeners * * @method addTechControlsListeners */ Player.prototype.addTechControlsListeners = function addTechControlsListeners() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech, 'mousedown', this.handleTechClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech, 'touchstart', this.handleTechTouchStart); this.on(this.tech, 'touchmove', this.handleTechTouchMove); this.on(this.tech, 'touchend', this.handleTechTouchEnd); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech, 'tap', this.handleTechTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @method removeTechControlsListeners */ Player.prototype.removeTechControlsListeners = function removeTechControlsListeners() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech, 'tap', this.handleTechTap); this.off(this.tech, 'touchstart', this.handleTechTouchStart); this.off(this.tech, 'touchmove', this.handleTechTouchMove); this.off(this.tech, 'touchend', this.handleTechTouchEnd); this.off(this.tech, 'mousedown', this.handleTechClick); }; /** * Player waits for the tech to be ready * * @private * @method handleTechReady */ Player.prototype.handleTechReady = function handleTechReady() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall('setVolume', this.cache_.volume); } // Update the duration if available this.handleTechDurationChange(); // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if (this.tag && this.options_.autoplay && this.paused()) { delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16. this.play(); } }; /** * Fired when the user agent begins looking for media data * * @event loadstart */ Player.prototype.handleTechLoadStart = function handleTechLoadStart() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @param {Boolean} hasStarted The value of true adds the class the value of false remove the class * @return {Boolean} Boolean value if has started * @method hasStarted */ Player.prototype.hasStarted = function hasStarted(_hasStarted) { if (_hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== _hasStarted) { this.hasStarted_ = _hasStarted; if (_hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }; /** * Fired whenever the media begins or resumes playback * * @event play */ Player.prototype.handleTechPlay = function handleTechPlay() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); this.trigger('play'); }; /** * Fired whenever the media begins waiting * * @event waiting */ Player.prototype.handleTechWaiting = function handleTechWaiting() { this.addClass('vjs-waiting'); this.trigger('waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplay */ Player.prototype.handleTechCanPlay = function handleTechCanPlay() { this.removeClass('vjs-waiting'); this.trigger('canplay'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplaythrough */ Player.prototype.handleTechCanPlayThrough = function handleTechCanPlayThrough() { this.removeClass('vjs-waiting'); this.trigger('canplaythrough'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event playing */ Player.prototype.handleTechPlaying = function handleTechPlaying() { this.removeClass('vjs-waiting'); this.trigger('playing'); }; /** * Fired whenever the player is jumping to a new time * * @event seeking */ Player.prototype.handleTechSeeking = function handleTechSeeking() { this.addClass('vjs-seeking'); this.trigger('seeking'); }; /** * Fired when the player has finished jumping to a new time * * @event seeked */ Player.prototype.handleTechSeeked = function handleTechSeeked() { this.removeClass('vjs-seeking'); this.trigger('seeked'); }; /** * Fired the first time a video is played * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ Player.prototype.handleTechFirstPlay = function handleTechFirstPlay() { //If the first starttime attribute is specified //then we will start at the given offset in seconds if (this.options_.starttime) { this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); this.trigger('firstplay'); }; /** * Fired whenever the media has been paused * * @event pause */ Player.prototype.handleTechPause = function handleTechPause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.trigger('pause'); }; /** * Fired while the user agent is downloading media data * * @event progress */ Player.prototype.handleTechProgress = function handleTechProgress() { this.trigger('progress'); // Add custom event for when source is finished downloading. if (this.bufferedPercent() === 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event ended */ Player.prototype.handleTechEnded = function handleTechEnded() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @event durationchange */ Player.prototype.handleTechDurationChange = function handleTechDurationChange() { this.duration(this.techGet('duration')); }; /** * Handle a click on the media element to play/pause * * @param {Object=} event Event object * @method handleTechClick */ Player.prototype.handleTechClick = function handleTechClick(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @method handleTechTap */ Player.prototype.handleTechTap = function handleTechTap() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @method handleTechTouchStart */ Player.prototype.handleTechTouchStart = function handleTechTouchStart() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @method handleTechTouchMove */ Player.prototype.handleTechTouchMove = function handleTechTouchMove() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @method handleTechTouchEnd */ Player.prototype.handleTechTouchEnd = function handleTechTouchEnd(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Fired when the player switches in or out of fullscreen mode * * @event fullscreenchange */ Player.prototype.handleFullscreenChange = function handleFullscreenChange() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @method handleStageClick */ Player.prototype.handleStageClick = function handleStageClick() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @method handleTechFullscreenChange */ Player.prototype.handleTechFullscreenChange = function handleTechFullscreenChange(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video * * @event error */ Player.prototype.handleTechError = function handleTechError() { var error = this.tech.error(); this.error(error && error.code); }; /** * Fires when the browser is intentionally not getting media data * * @event suspend */ Player.prototype.handleTechSuspend = function handleTechSuspend() { this.trigger('suspend'); }; /** * Fires when the loading of an audio/video is aborted * * @event abort */ Player.prototype.handleTechAbort = function handleTechAbort() { this.trigger('abort'); }; /** * Fires when the current playlist is empty * * @event emptied */ Player.prototype.handleTechEmptied = function handleTechEmptied() { this.trigger('emptied'); }; /** * Fires when the browser is trying to get media data, but data is not available * * @event stalled */ Player.prototype.handleTechStalled = function handleTechStalled() { this.trigger('stalled'); }; /** * Fires when the browser has loaded meta data for the audio/video * * @event loadedmetadata */ Player.prototype.handleTechLoadedMetaData = function handleTechLoadedMetaData() { this.trigger('loadedmetadata'); }; /** * Fires when the browser has loaded the current frame of the audio/video * * @event loaddata */ Player.prototype.handleTechLoadedData = function handleTechLoadedData() { this.trigger('loadeddata'); }; /** * Fires when the current playback position has changed * * @event timeupdate */ Player.prototype.handleTechTimeUpdate = function handleTechTimeUpdate() { this.trigger('timeupdate'); }; /** * Fires when the playing speed of the audio/video is changed * * @event ratechange */ Player.prototype.handleTechRateChange = function handleTechRateChange() { this.trigger('ratechange'); }; /** * Fires when the volume has been changed * * @event volumechange */ Player.prototype.handleTechVolumeChange = function handleTechVolumeChange() { this.trigger('volumechange'); }; /** * Fires when the text track has been changed * * @event texttrackchange */ Player.prototype.onTextTrackChange = function onTextTrackChange() { this.trigger('texttrackchange'); }; /** * Get object for cached values. * * @return {Object} * @method getCache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {String=} method Method * @param {Object=} arg Argument * @method techCall */ Player.prototype.techCall = function techCall(method, arg) { // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function () { this[method](arg); }, true); // Otherwise call method now } else { try { this.tech[method](arg); } catch (e) { _utilsLogJs2['default'](e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {String} method Tech method * @return {Method} * @method techGet */ Player.prototype.techGet = function techGet(method) { if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { _utilsLogJs2['default']('Video.js: ' + method + ' method not defined for ' + this.techName + ' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name === 'TypeError') { _utilsLogJs2['default']('Video.js: ' + method + ' unavailable on ' + this.techName + ' playback technology element.', e); this.tech.isReady_ = false; } else { _utilsLogJs2['default'](e); } } throw e; } } return; }; /** * start media playback * ```js * myPlayer.play(); * ``` * * @return {Player} self * @method play */ Player.prototype.play = function play() { this.techCall('play'); return this; }; /** * Pause the video playback * ```js * myPlayer.pause(); * ``` * * @return {Player} self * @method pause */ Player.prototype.pause = function pause() { this.techCall('pause'); return this; }; /** * Check if the player is paused * ```js * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * ``` * * @return {Boolean} false if the media is currently playing, or true otherwise * @method paused */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is when the user * has clicked the progress bar handle and is dragging it along the progress bar. * * @param {Boolean} isScrubbing True/false the user is scrubbing * @return {Boolean} The scrubbing status when getting * @return {Object} The player when setting * @method scrubbing */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * ```js * // get * var whereYouAt = myPlayer.currentTime(); * // set * myPlayer.currentTime(120); // 2 minutes into the video * ``` * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {Player} self, when the current time is set * @method currentTime */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = this.techGet('currentTime') || 0; }; /** * Get the length in time of the video in seconds * ```js * var lengthOfVideo = myPlayer.duration(); * ``` * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @param {Number} seconds Duration when setting * @return {Number} The duration of the video in seconds when getting * @method duration */ Player.prototype.duration = function duration(seconds) { if (seconds === undefined) { return this.cache_.duration || 0; } seconds = parseFloat(seconds) || 0; // Standardize on Inifity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } this.trigger('durationchange'); } return this; }; /** * Calculates how much time is left. * ```js * var timeLeft = myPlayer.remainingTime(); * ``` * Not a native video element function, but useful * * @return {Number} The time remaining in seconds * @method remainingTime */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * ```js * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * ``` * * @return {Object} A mock TimeRange object (following HTML spec) * @method buffered */ Player.prototype.buffered = function buffered() { var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = _utilsTimeRangesJs.createTimeRange(0, 0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * ```js * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * ``` * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent * @method bufferedPercent */ Player.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration()); }; /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {Number} The end of the last buffered time range * @method bufferedEnd */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * ```js * // get * var howLoudIsIt = myPlayer.volume(); * // set * myPlayer.volume(0.5); // Set volume to half * ``` * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume when getting * @return {Player} self when setting * @method volume */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = undefined; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * ```js * // get * var isVolumeMuted = myPlayer.muted(); * // set * myPlayer.muted(true); // mute the volume * ``` * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not when getting * @return {Player} self when setting mute * @method muted */ Player.prototype.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall('setMuted', _muted); return this; } return this.techGet('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) /** * Check to see if fullscreen is supported * * @return {Boolean} * @method supportsFullScreen */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode * ```js * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * ``` * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen false if not when getting * @return {Player} self when setting * @method isFullscreen */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * ```js * myPlayer.requestFullscreen(); * ``` * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {Player} self * @method requestFullscreen */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_globalDocument2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_globalDocument2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_globalDocument2['default'], fsApi.fullscreenchange, documentFullscreenChange); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * ```js * myPlayer.exitFullscreen(); * ``` * * @return {Player} self * @method exitFullscreen */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _globalDocument2['default'][fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. * * @method enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _globalDocument2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _globalDocument2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_globalDocument2['default'].body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or full screen on ESC key * * @param {String} event Event to check for key press * @method fullWindowOnEscKey */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @method exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_globalDocument2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _globalDocument2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_globalDocument2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; /** * Select source based on tech order * * @param {Array} sources The sources for a media asset * @return {Object|Boolean} Object of source and tech order, otherwise false * @method selectSource */ Player.prototype.selectSource = function selectSource(sources) { // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _componentJs2['default'].getComponent(techName); // Check if the current tech is defined before continuing if (!tech) { _utilsLogJs2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a = 0, b = sources; a < b.length; a++) { var source = b[a]; // Check if source can be played with this technology if (tech.canPlaySource(source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * ```js * myPlayer.src("http://www.example.com/path/to/video.mp4"); * ``` * **Source Object (or element):* * A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * ```js * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * ``` * **Array of Source Objects:* * To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * ```js * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * ``` * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting * @method src */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet('src'); } var currentTech = _componentJs2['default'].getComponent(this.techName); // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall('setSource', source); } else { this.techCall('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } // Set the source synchronously if possible (#2326) }, true); } } return this; }; /** * Handle an array of source objects * * @param {Array} sources Array of source objects * @private * @method sourceList_ */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} Returns the player * @method load */ Player.prototype.load = function load() { this.techCall('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {String} The current source * @method currentSrc */ Player.prototype.currentSrc = function currentSrc() { return this.techGet('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {String} The source MIME type * @method currentType */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The preload attribute value when getting * @return {Player} Returns the player when setting * @method preload */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall('setPreload', value); this.options_.preload = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The autoplay attribute value when getting * @return {Player} Returns the player when setting * @method autoplay */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The loop attribute value when getting * @return {Player} Returns the player when setting * @method loop */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet('loop'); }; /** * get or set the poster image source url * ##### EXAMPLE: * ```js * // get * var currentPoster = myPlayer.poster(); * // set * myPlayer.poster('http://example.com/myImage.jpg'); * ``` * * @param {String=} src Poster image source URL * @return {String} poster URL when getting * @return {Player} self when setting * @method poster */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Get or set whether or not the controls are showing. * * @param {Boolean} bool Set controls to showing or not * @return {Boolean} Controls are showing * @method controls */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {Player} Returns the player * @private * @method usingNativeControls */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {MediaError|null} when getting * @return {Player} when setting * @method error */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _utilsLogJs2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaErrorJs2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method ended */ Player.prototype.ended = function ended() { return this.techGet('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method seeking */ Player.prototype.seeking = function seeking() { return this.techGet('seeking'); }; /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method seekable */ Player.prototype.seekable = function seekable() { return this.techGet('seekable'); }; /** * Report user activity * * @param {Object} event Event object * @method reportUserActivity */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @param {Boolean} bool Value when setting * @return {Boolean} Value if user is active user when getting * @method userActive */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech) { this.tech.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @method listenForUserActivity */ Player.prototype.listenForUserActivity = function listenForUserActivity() { var mouseInProgress = undefined, lastMoveX = undefined, lastMoveY = undefined; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = undefined; var activityCheck = this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_['inactivityTimeout']; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {Number} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting * @method playbackRate */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech['featuresPlaybackRate']) { return this.techGet('playbackRate'); } else { return 1.0; } }; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {Player} Returns the player if setting * @private * @method isAudio */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {Number} the current network activity state * @method networkState */ Player.prototype.networkState = function networkState() { return this.techGet('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {Number} the current playback rendering state * @method readyState */ Player.prototype.readyState = function readyState() { return this.techGet('readyState'); }; /* * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {Array} Array of track objects * @method textTracks */ Player.prototype.textTracks = function textTracks() { // cannot use techGet directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech && this.tech['textTracks'](); }; /** * Get an array of remote text tracks * * @return {Array} * @method remoteTextTracks */ Player.prototype.remoteTextTracks = function remoteTextTracks() { return this.tech && this.tech['remoteTextTracks'](); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @method addTextTrack */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { return this.tech && this.tech['addTextTrack'](kind, label, language); }; /** * Add a remote text track * * @param {Object} options Options for remote text track * @method addRemoteTextTrack */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { return this.tech && this.tech['addRemoteTextTrack'](options); }; /** * Remove a remote text track * * @param {Object} track Remote text track to remove * @method removeRemoteTextTrack */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.tech && this.tech['removeRemoteTextTrack'](track); }; /** * Get video width * * @return {Number} Video width * @method videoWidth */ Player.prototype.videoWidth = function videoWidth() { return this.tech && this.tech.videoWidth && this.tech.videoWidth() || 0; }; /** * Get video height * * @return {Number} Video height * @method videoHeight */ Player.prototype.videoHeight = function videoHeight() { return this.tech && this.tech.videoHeight && this.tech.videoHeight() || 0; }; // Methods to add support for // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {String} code The locale string * @return {String} The locale string when getting * @return {Player} self when setting * @method language */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = ('' + code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} Array of languages * @method languages */ Player.prototype.languages = function languages() { return _utilsMergeOptionsJs2['default'](Player.prototype.options_.languages, this.languages_); }; /** * Converts track info to JSON * * @return {Object} JSON object of options * @method toJSON */ Player.prototype.toJSON = function toJSON() { var options = _utilsMergeOptionsJs2['default'](this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = _utilsMergeOptionsJs2['default'](track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Gets tag settings * * @param {Element} tag The player tag * @return {Array} An array of sources and track objects * @static * @method getTagSettings */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { 'sources': [], 'tracks': [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON var _safeParseTuple = _safeJsonParseTuple2['default'](dataSetup || '{}'); var err = _safeParseTuple[0]; var data = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } _objectAssign2['default'](tagOptions, data); } _objectAssign2['default'](baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; return Player; })(_componentJs2['default']); Player.players = {}; var navigator = _globalWindow2['default'].navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0.00, // The freakin seaguls are driving me crazy! // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: { mediaLoader: {}, posterImage: {}, textTrackDisplay: {}, loadingSpinner: {}, bigPlayButton: {}, controlBar: {}, errorDisplay: {}, textTrackSettings: {} }, language: _globalDocument2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this video.' }; /** * Fired when the player has initial duration and dimension information * * @event loadedmetadata */ Player.prototype.handleLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * * @event loadeddata */ Player.prototype.handleLoadedData; /** * Fired when the player has finished downloading the source data * * @event loadedalldata */ Player.prototype.handleLoadedAllData; /** * Fired when the user is active, e.g. moves the mouse over the player * * @event useractive */ Player.prototype.handleUserActive; /** * Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction * * @event userinactive */ Player.prototype.handleUserInactive; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event timeupdate */ Player.prototype.handleTimeUpdate; /** * Fired when the volume changes * * @event volumechange */ Player.prototype.handleVolumeChange; /** * Fired when an error occurs * * @event error */ Player.prototype.handleError; Player.prototype.flexNotSupported_ = function () { var elem = _globalDocument2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style) /* IE10-specific (2012 flex spec) */; }; _componentJs2['default'].registerComponent('Player', Player); exports['default'] = Player; module.exports = exports['default']; // If empty string, make it a parsable json object. },{"./big-play-button.js":46,"./component.js":48,"./control-bar/control-bar.js":49,"./error-display.js":78,"./fullscreen-api.js":81,"./loading-spinner.js":82,"./media-error.js":83,"./poster-image.js":89,"./tech/html5.js":94,"./tech/loader.js":95,"./tracks/text-track-display.js":98,"./tracks/text-track-list-converter.js":100,"./tracks/text-track-settings.js":102,"./utils/browser.js":104,"./utils/buffer.js":105,"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"./utils/guid.js":111,"./utils/log.js":112,"./utils/merge-options.js":113,"./utils/stylesheet.js":114,"./utils/time-ranges.js":115,"./utils/to-title-case.js":116,"global/document":1,"global/window":2,"object.assign":40,"safe-json-parse/tuple":45}],88:[function(_dereq_,module,exports){ /** * @file plugins.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _playerJs = _dereq_('./player.js'); var _playerJs2 = _interopRequireDefault(_playerJs); /** * The method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits * @method plugin */ var plugin = function plugin(name, init) { _playerJs2['default'].prototype[name] = init; }; exports['default'] = plugin; module.exports = exports['default']; },{"./player.js":87}],89:[function(_dereq_,module,exports){ /** * @file poster-image.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('./button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); /** * The component that handles showing the poster image. * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PosterImage */ var PosterImage = (function (_Button) { _inherits(PosterImage, _Button); function PosterImage(player, options) { _classCallCheck(this, PosterImage); _Button.call(this, player, options); this.update(); player.on('posterchange', Fn.bind(this, this.update)); } /** * Clean up the poster image * * @method dispose */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _Button.prototype.dispose.call(this); }; /** * Create the poster's image element * * @return {Element} * @method createEl */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source * * @method update */ PosterImage.prototype.update = function update() { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method * * @param {String} url The URL to the poster source * @method setSrc */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image * * @method handleClick */ PosterImage.prototype.handleClick = function handleClick() { // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; module.exports = exports['default']; },{"./button.js":47,"./component.js":48,"./utils/browser.js":104,"./utils/dom.js":107,"./utils/fn.js":109}],90:[function(_dereq_,module,exports){ /** * @file setup.js * * Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _windowLoaded = false; var videojs = undefined; // Automatically set up any tags that have a data-setup attribute var autoSetup = function autoSetup() { // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = _globalDocument2['default'].getElementsByTagName('video'); var audios = _globalDocument2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var i = 0, e = audios.length; i < e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var i = 0, e = mediaEls.length; i < e; i++) { var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl['player'] === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. var player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; // Pause to let the DOM keep processing var autoSetupTimeout = function autoSetupTimeout(wait, vjs) { videojs = vjs; setTimeout(autoSetup, wait); }; if (_globalDocument2['default'].readyState === 'complete') { _windowLoaded = true; } else { Events.one(_globalWindow2['default'], 'load', function () { _windowLoaded = true; }); } var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"./utils/events.js":108,"global/document":1,"global/window":2}],91:[function(_dereq_,module,exports){ /** * @file slider.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The base functionality for sliders like the volume bar and seek bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class Slider */ var Slider = (function (_Component) { _inherits(Slider, _Component); function Slider(player, options) { _classCallCheck(this, Slider); _Component.call(this, player, options); // Set property names to bar to match with the child Slider class is looking for this.bar = this.getChild(this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type this.vertical(!!this.options_.vertical); this.on('mousedown', this.handleMouseDown); this.on('touchstart', this.handleMouseDown); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); this.on('click', this.handleClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } /** * Create the component's DOM element * * @param {String} type Type of element to create * @param {Object=} props List of properties in Object form * @return {Element} * @method createEl */ Slider.prototype.createEl = function createEl(type) { var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = _objectAssign2['default']({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return _Component.prototype.createEl.call(this, type, props); }; /** * Handle mouse down on slider * * @param {Object} event Mouse down event object * @method handleMouseDown */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); this.trigger('slideractive'); this.on(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.on(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.on(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.on(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * To be overridden by a subclass * * @method handleMouseMove */ Slider.prototype.handleMouseMove = function handleMouseMove() {}; /** * Handle mouse up on Slider * * @method handleMouseUp */ Slider.prototype.handleMouseUp = function handleMouseUp() { Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); this.trigger('sliderinactive'); this.off(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.off(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.off(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.off(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.update(); }; /** * Update slider * * @method update */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) return; // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; // Set the new bar width or height if (this.vertical()) { bar.el().style.height = percentage; } else { bar.el().style.width = percentage; } }; /** * Calculate distance for slider * * @param {Object} event Event object * @method calculateDistance */ Slider.prototype.calculateDistance = function calculateDistance(event) { var el = this.el_; var box = Dom.findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; if (this.vertical()) { var boxY = box.top; var pageY = undefined; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); } else { var boxX = box.left; var pageX = undefined; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; /** * Handle on focus for slider * * @method handleFocus */ Slider.prototype.handleFocus = function handleFocus() { this.on(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Handle key press for slider * * @param {Object} event Event object * @method handleKeyPress */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { if (event.which === 37 || event.which === 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which === 38 || event.which === 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; /** * Handle on blur for slider * * @method handleBlur */ Slider.prototype.handleBlur = function handleBlur() { this.off(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event Event object * @method handleClick */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {Boolean} bool True if slider is vertical, false is horizontal * @return {Boolean} True if slider is vertical, false is horizontal * @method vertical */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } return this; }; return Slider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Slider', Slider); exports['default'] = Slider; module.exports = exports['default']; },{"../component.js":48,"../utils/dom.js":107,"global/document":1,"object.assign":40}],92:[function(_dereq_,module,exports){ /** * @file flash-rtmp.js */ 'use strict'; exports.__esModule = true; function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) return parts; // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin = undefined; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid Flash.RTMP_RE = /^rtmp[set]?:\/\//i; Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source) { if (Flash.isStreamingType(source.type) || Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.rtmpSourceHandler.handleSource = function (source, tech) { var srcParts = Flash.streamToParts(source.src); tech['setRtmpConnection'](srcParts.connection); tech['setRtmpStream'](srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; module.exports = exports['default']; },{}],93:[function(_dereq_,module,exports){ /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _tech = _dereq_('./tech'); var _tech2 = _interopRequireDefault(_tech); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _flashRtmp = _dereq_('./flash-rtmp'); var _flashRtmp2 = _interopRequireDefault(_flashRtmp); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var navigator = _globalWindow2['default'].navigator; /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Flash */ var Flash = (function (_Tech) { _inherits(Flash, _Tech); function Flash(options, ready) { _classCallCheck(this, Flash); _Tech.call(this, options, ready); // Set the source when ready if (options.source) { this.ready(function () { this.setSource(options.source); }, true); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }, true); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _globalWindow2['default'].videojs = _globalWindow2['default'].videojs || {}; _globalWindow2['default'].videojs.Flash = _globalWindow2['default'].videojs.Flash || {}; _globalWindow2['default'].videojs.Flash.onReady = Flash.onReady; _globalWindow2['default'].videojs.Flash.onEvent = Flash.onEvent; _globalWindow2['default'].videojs.Flash.onError = Flash.onError; this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); } // Create setters and getters for attributes /** * Create the component's DOM element * * @return {Element} * @method createEl */ Flash.prototype.createEl = function createEl() { var options = this.options_; // If video.js is hosted locally you should also set the location // for the hosted swf, which should be relative to the page (not video.js) // Otherwise this adds a CDN url. // The CDN also auto-adds a swf URL for that specific version. if (!options.swf) { options.swf = '//vjs.zencdn.net/swf/5.0.0-rc1/video-js.swf'; } // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = _objectAssign2['default']({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': options.autoplay, 'preload': options.preload, 'loop': options.loop, 'muted': options.muted }, options.flashVars); // Merge default parames with ones passed in var params = _objectAssign2['default']({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options.params); // Merge default attributes with ones passed in var attributes = _objectAssign2['default']({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Play for flash tech * * @method play */ Flash.prototype.play = function play() { if (this.ended()) { this.setCurrentTime(0); } this.el_.vjs_play(); }; /** * Pause for flash tech * * @method pause */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Flash.prototype.src = function src(_src) { if (_src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(_src); }; /** * Set video * * @param {Object=} src Source object * @deprecated * @method setSrc */ Flash.prototype.setSrc = function setSrc(src) { // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { var tech = this; this.setTimeout(function () { tech.play(); }, 0); } }; /** * Returns true if the tech is currently seeking. * @return {boolean} true if seeking */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Set current time * * @param {Number} time Current time of video * @method setCurrentTime */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get current time * * @param {Number=} time Current time of video * @return {Number} Current time * @method currentTime */ Flash.prototype.currentTime = function currentTime(time) { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get current source * * @method currentSrc */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; /** * Load media into player * * @method load */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get poster * * @method poster */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this a no-op * * @method setPoster */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine if can seek in media * * @return {TimeRangeObject} * @method seekable */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(0, duration); }; /** * Get buffered time range * * @return {TimeRangeObject} * @method buffered */ Flash.prototype.buffered = function buffered() { var ranges = this.el_.vjs_getProperty('buffered'); if (ranges.length === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(ranges[0][0], ranges[0][1]); }; /** * Get fullscreen support - * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method supportsFullScreen */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { return false; // Flash does not allow fullscreen through javascript }; /** * Request to enter fullscreen * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method enterFullScreen */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; })(_tech2['default']); var _api = Flash.prototype; var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','); var _readOnly = 'networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','); function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var i = 0; i < _readOnly.length; i++) { _createGetter(_readOnly[i]); } /* Flash Support Testing -------------------------------------------------------- */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech _tech2['default'].withSourceHandlers(Flash); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /* * Check Flash can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canHandleSource = function (source) { var type; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } if (type in Flash.formats) { return 'maybe'; } return ''; }; /* * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; Flash.onReady = function (currSwf) { var el = Dom.getEl(currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player Flash.onEvent = function (swfID, eventName) { var tech = Dom.getEl(swfID).tech; tech.trigger(eventName); }; // Log errors from the swf Flash.onError = function (swfID, err) { var tech = Dom.getEl(swfID).tech; // trigger MEDIA_ERR_SRC_NOT_SUPPORTED if (err === 'srcnotfound') { return tech.error(4); } // trigger a custom error tech.error('FLASH: ' + err); }; // Flash Version Check Flash.version = function () { var version = '0,0,0'; // IE try { version = new _globalWindow2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = _objectAssign2['default']({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = _objectAssign2['default']({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += key + '="' + attributes[key] + '" '; }); return '' + objTag + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator _flashRtmp2['default'](Flash); _component2['default'].registerComponent('Flash', Flash); exports['default'] = Flash; module.exports = exports['default']; },{"../component":48,"../utils/dom.js":107,"../utils/time-ranges.js":115,"../utils/url.js":117,"./flash-rtmp":92,"./tech":96,"global/window":2,"object.assign":40}],94:[function(_dereq_,module,exports){ /** * @file html5.js * HTML5 Media Controller - Wrapper for HTML5 Media API */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _techJs = _dereq_('./tech.js'); var _techJs2 = _interopRequireDefault(_techJs); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Html5 */ var Html5 = (function (_Tech) { _inherits(Html5, _Tech); function Html5(options, ready) { _classCallCheck(this, Html5); _Tech.call(this, options, ready); var source = options.source; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { this.setSource(source); } if (this.el_.hasChildNodes()) { var nodes = this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { this.remoteTextTracks().addTrack_(node.track); } } } for (var i = 0; i < removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this.featuresNativeTextTracks) { this.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange); this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd); this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove); this.proxyNativeTextTracks_(); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) { this.setControls(true); } this.triggerReady(); } /* HTML5 Support Testing ---------------------------------------------------- */ /* * Element for testing browser HTML5 video capabilities * * @type {Element} * @constant * @private */ /** * Dispose of html5 media element * * @method dispose */ Html5.prototype.dispose = function dispose() { var tt = this.el().textTracks; var emulatedTt = this.textTracks(); // remove native event listeners if (tt && tt.removeEventListener) { tt.removeEventListener('change', this.handleTextTrackChange_); tt.removeEventListener('addtrack', this.handleTextTrackAdd_); tt.removeEventListener('removetrack', this.handleTextTrackRemove_); } // clearout the emulated text track list. var i = emulatedTt.length; while (i--) { emulatedTt.removeTrack_(emulatedTt[i]); } Html5.disposeMediaElement(this.el_); _Tech.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(true); el.parentNode.insertBefore(clone, el); Html5.disposeMediaElement(el); el = clone; } else { el = _globalDocument2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); var attributes = _utilsMergeOptionsJs2['default']({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, _objectAssign2['default'](attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() { var tt = this.el().textTracks; if (tt && tt.addEventListener) { tt.addEventListener('change', this.handleTextTrackChange_); tt.addEventListener('addtrack', this.handleTextTrackAdd_); tt.addEventListener('removetrack', this.handleTextTrackRemove_); } }; Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) { var tt = this.textTracks(); this.textTracks().trigger({ type: 'change', target: tt, currentTarget: tt, srcElement: tt }); }; Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) { this.textTracks().addTrack_(e.track); }; Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) { this.textTracks().removeTrack_(e.track); }; /** * Play for html5 tech * * @method play */ Html5.prototype.play = function play() { this.el_.play(); }; /** * Pause for html5 tech * * @method pause */ Html5.prototype.pause = function pause() { this.el_.pause(); }; /** * Paused for html5 tech * * @return {Boolean} * @method paused */ Html5.prototype.paused = function paused() { return this.el_.paused; }; /** * Get current time * * @return {Number} * @method currentTime */ Html5.prototype.currentTime = function currentTime() { return this.el_.currentTime; }; /** * Set current time * * @param {Number} seconds Current time of video * @method setCurrentTime */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { _utilsLogJs2['default'](e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get duration * * @return {Number} * @method duration */ Html5.prototype.duration = function duration() { return this.el_.duration || 0; }; /** * Get a TimeRange object that represents the intersection * of the time ranges for which the user agent has all * relevant media * * @return {TimeRangeObject} * @method buffered */ Html5.prototype.buffered = function buffered() { return this.el_.buffered; }; /** * Get volume level * * @return {Number} * @method volume */ Html5.prototype.volume = function volume() { return this.el_.volume; }; /** * Set volume level * * @param {Number} percentAsDecimal Volume percent as a decimal * @method setVolume */ Html5.prototype.setVolume = function setVolume(percentAsDecimal) { this.el_.volume = percentAsDecimal; }; /** * Get if muted * * @return {Boolean} * @method muted */ Html5.prototype.muted = function muted() { return this.el_.muted; }; /** * Set muted * * @param {Boolean} If player is to be muted or note * @method setMuted */ Html5.prototype.setMuted = function setMuted(muted) { this.el_.muted = muted; }; /** * Get player width * * @return {Number} * @method width */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get player height * * @return {Number} * @method height */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Get if there is fullscreen support * * @return {Boolean} * @method supportsFullScreen */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _globalWindow2['default'].navigator.userAgent; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request to enter fullscreen * * @method enterFullScreen */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function () { this.one('webkitendfullscreen', function () { this.trigger('fullscreenchange', { isFullscreen: false }); }); this.trigger('fullscreenchange', { isFullscreen: true }); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request to exit fullscreen * * @method exitFullScreen */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Html5.prototype.src = function src(_src) { if (_src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(_src); } }; /** * Set video * * @param {Object} src Source object * @deprecated * @method setSrc */ Html5.prototype.setSrc = function setSrc(src) { this.el_.src = src; }; /** * Load media into player * * @method load */ Html5.prototype.load = function load() { this.el_.load(); }; /** * Get current source * * @return {Object} * @method currentSrc */ Html5.prototype.currentSrc = function currentSrc() { return this.el_.currentSrc; }; /** * Get poster * * @return {String} * @method poster */ Html5.prototype.poster = function poster() { return this.el_.poster; }; /** * Set poster * * @param {String} val URL to poster image * @method */ Html5.prototype.setPoster = function setPoster(val) { this.el_.poster = val; }; /** * Get preload attribute * * @return {String} * @method preload */ Html5.prototype.preload = function preload() { return this.el_.preload; }; /** * Set preload attribute * * @param {String} val Value for preload attribute * @method setPreload */ Html5.prototype.setPreload = function setPreload(val) { this.el_.preload = val; }; /** * Get autoplay attribute * * @return {String} * @method autoplay */ Html5.prototype.autoplay = function autoplay() { return this.el_.autoplay; }; /** * Set autoplay attribute * * @param {String} val Value for preload attribute * @method setAutoplay */ Html5.prototype.setAutoplay = function setAutoplay(val) { this.el_.autoplay = val; }; /** * Get controls attribute * * @return {String} * @method controls */ Html5.prototype.controls = function controls() { return this.el_.controls; }; /** * Set controls attribute * * @param {String} val Value for controls attribute * @method setControls */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Get loop attribute * * @return {String} * @method loop */ Html5.prototype.loop = function loop() { return this.el_.loop; }; /** * Set loop attribute * * @param {String} val Value for loop attribute * @method setLoop */ Html5.prototype.setLoop = function setLoop(val) { this.el_.loop = val; }; /** * Get error value * * @return {String} * @method error */ Html5.prototype.error = function error() { return this.el_.error; }; /** * Get whether or not the player is in the "seeking" state * * @return {Boolean} * @method seeking */ Html5.prototype.seeking = function seeking() { return this.el_.seeking; }; /** * Get a TimeRanges object that represents the * ranges of the media resource to which it is possible * for the user agent to seek. * * @return {TimeRangeObject} * @method seekable */ Html5.prototype.seekable = function seekable() { return this.el_.seekable; }; /** * Get if video ended * * @return {Boolean} * @method ended */ Html5.prototype.ended = function ended() { return this.el_.ended; }; /** * Get the value of the muted content attribute * This attribute has no dynamic effect, it only * controls the default state of the element * * @return {Boolean} * @method defaultMuted */ Html5.prototype.defaultMuted = function defaultMuted() { return this.el_.defaultMuted; }; /** * Get desired speed at which the media resource is to play * * @return {Number} * @method playbackRate */ Html5.prototype.playbackRate = function playbackRate() { return this.el_.playbackRate; }; /** * Returns a TimeRanges object that represents the ranges of the * media resource that the user agent has played. * @return {TimeRangeObject} the range of points on the media * timeline that has been reached through normal playback * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played */ Html5.prototype.played = function played() { return this.el_.played; }; /** * Set desired speed at which the media resource is to play * * @param {Number} val Speed at which the media resource is to play * @method setPlaybackRate */ Html5.prototype.setPlaybackRate = function setPlaybackRate(val) { this.el_.playbackRate = val; }; /** * Get the current state of network activity for the element, from * the list below * NETWORK_EMPTY (numeric value 0) * NETWORK_IDLE (numeric value 1) * NETWORK_LOADING (numeric value 2) * NETWORK_NO_SOURCE (numeric value 3) * * @return {Number} * @method networkState */ Html5.prototype.networkState = function networkState() { return this.el_.networkState; }; /** * Get a value that expresses the current state of the element * with respect to rendering the current playback position, from * the codes in the list below * HAVE_NOTHING (numeric value 0) * HAVE_METADATA (numeric value 1) * HAVE_CURRENT_DATA (numeric value 2) * HAVE_FUTURE_DATA (numeric value 3) * HAVE_ENOUGH_DATA (numeric value 4) * * @return {Number} * @method readyState */ Html5.prototype.readyState = function readyState() { return this.el_.readyState; }; /** * Get width of video * * @return {Number} * @method videoWidth */ Html5.prototype.videoWidth = function videoWidth() { return this.el_.videoWidth; }; /** * Get height of video * * @return {Number} * @method videoHeight */ Html5.prototype.videoHeight = function videoHeight() { return this.el_.videoHeight; }; /** * Get text tracks * * @return {TextTrackList} * @method textTracks */ Html5.prototype.textTracks = function textTracks() { return _Tech.prototype.textTracks.call(this); }; /** * Creates and returns a text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addRemoteTextTrack.call(this, options); } var track = _globalDocument2['default'].createElement('track'); if (options['kind']) { track['kind'] = options['kind']; } if (options['label']) { track['label'] = options['label']; } if (options['language'] || options['srclang']) { track['srclang'] = options['language'] || options['srclang']; } if (options['default']) { track['default'] = options['default']; } if (options['id']) { track['id'] = options['id']; } if (options['src']) { track['src'] = options['src']; } this.el().appendChild(track); this.remoteTextTracks().addTrack_(track.track); return track; }; /** * Remove remote text track from TextTrackList object * * @param {TextTrackObject} track Texttrack object to remove * @method removeRemoteTextTrack */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.removeRemoteTextTrack.call(this, track); } var tracks, i; this.remoteTextTracks().removeTrack_(track); tracks = this.el().querySelectorAll('track'); i = tracks.length; while (i--) { if (track === tracks[i] || track === tracks[i].track) { this.el().removeChild(tracks[i]); } } }; return Html5; })(_techJs2['default']); Html5.TEST_VID = _globalDocument2['default'].createElement('video'); var track = _globalDocument2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); /* * Check if HTML5 video is supported by this browser/device * * @return {Boolean} */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!Html5.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech _techJs2['default'].withSourceHandlers(Html5); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Html5} tech The instance of the HTML5 tech */ Html5.nativeSourceHandler = {}; /* * Check if the video element can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canHandleSource = function (source) { var match, ext; function canPlayType(type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' ext = Url.getFileExtension(source.src); return canPlayType('video/' + ext); } return ''; }; /* * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Html5} tech The instance of the Html5 tech */ Html5.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); /* * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {Boolean} */ Html5.canControlVolume = function () { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; }; /* * Check if playbackRate is supported in this browser/device. * * @return {Number} [description] */ Html5.canControlPlaybackRate = function () { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; }; /* * Check to see if native text tracks are supported by this browser/device * * @return {Boolean} */ Html5.supportsNativeTextTracks = function () { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!Html5.TEST_VID.textTracks; if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof Html5.TEST_VID.textTracks[0]['mode'] !== 'number'; } if (supportsTextTracks && browser.IS_FIREFOX) { supportsTextTracks = false; } if (supportsTextTracks && !('onremovetrack' in Html5.TEST_VID.textTracks)) { supportsTextTracks = false; } return supportsTextTracks; }; /** * An array of events available on the Html5 tech. * * @private * @type {Array} */ Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange']; /* * Set the tech's volume control support status * * @type {Boolean} */ Html5.prototype['featuresVolumeControl'] = Html5.canControlVolume(); /* * Set the tech's playbackRate support status * * @type {Boolean} */ Html5.prototype['featuresPlaybackRate'] = Html5.canControlPlaybackRate(); /* * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * * @type {Boolean} */ Html5.prototype['movingMediaElementInDOM'] = !browser.IS_IOS; /* * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ Html5.prototype['featuresFullscreenResize'] = true; /* * Set the tech's progress event support status * (this disables the manual progress events of the Tech) */ Html5.prototype['featuresProgressEvents'] = true; /* * Sets the tech's status on native text track support * * @type {Boolean} */ Html5.prototype['featuresNativeTextTracks'] = Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = undefined; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (browser.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // not supported } })(); } }; _component2['default'].registerComponent('Html5', Html5); exports['default'] = Html5; module.exports = exports['default']; },{"../component":48,"../utils/browser.js":104,"../utils/dom.js":107,"../utils/fn.js":109,"../utils/log.js":112,"../utils/merge-options.js":113,"../utils/url.js":117,"./tech.js":96,"global/document":1,"global/window":2,"object.assign":40}],95:[function(_dereq_,module,exports){ /** * @file loader.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class MediaLoader */ var MediaLoader = (function (_Component) { _inherits(MediaLoader, _Component); function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); _Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) { for (var i = 0, j = options.playerOptions['techOrder']; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _component2['default'].getComponent(techName); // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions['sources']); } } return MediaLoader; })(_component2['default']); _component2['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; module.exports = exports['default']; },{"../component":48,"../utils/to-title-case.js":116,"global/window":2}],96:[function(_dereq_,module,exports){ /** * @file tech.js * Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _tracksTextTrack = _dereq_('../tracks/text-track'); var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack); var _tracksTextTrackList = _dereq_('../tracks/text-track-list'); var _tracksTextTrackList2 = _interopRequireDefault(_tracksTextTrackList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _utilsBufferJs = _dereq_('../utils/buffer.js'); var _mediaErrorJs = _dereq_('../media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Base class for media (HTML5 Video, Flash) controllers * * @param {Object=} options Options object * @param {Function=} ready Ready callback function * @extends Component * @class Tech */ var Tech = (function (_Component) { _inherits(Tech, _Component); function Tech() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var ready = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1]; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; _Component.call(this, null, options, ready); // keep track of whether the current source has played at all to // implement a very limited played() this.hasStarted_ = false; this.on('playing', function () { this.hasStarted_ = true; }); this.on('loadstart', function () { this.hasStarted_ = false; }); this.textTracks_ = options.textTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!this.featuresProgressEvents) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this.featuresTimeupdateEvents) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); if (options.nativeCaptions === false || options.nativeTextTracks === false) { this.featuresNativeTextTracks = false; } if (!this.featuresNativeTextTracks) { this.emulateTextTracks(); } this.initTextTrackListeners(); // Turn on component tap events this.emitTapEvents(); } /* * List of associated text tracks * * @type {Array} * @private */ /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active * * @method initControlsListeners */ Tech.prototype.initControlsListeners = function initControlsListeners() { // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // Long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function () { if (this.networkState && this.networkState() > 0) { this.trigger('loadstart'); } // Allow the tech ready event to handle synchronisity }, true); }; /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events /** * Turn on progress events * * @method manualProgressOn */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off progress events * * @method manualProgressOff */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * Track progress * * @method trackProgress */ Tech.prototype.trackProgress = function trackProgress() { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update duration * * @method onDurationChange */ Tech.prototype.onDurationChange = function onDurationChange() { this.duration_ = this.duration(); }; /** * Create and get TimeRange object for buffering * * @return {TimeRangeObject} * @method buffered */ Tech.prototype.buffered = function buffered() { return _utilsTimeRangesJs.createTimeRange(0, 0); }; /** * Get buffered percent * * @return {Number} * @method bufferedPercent */ Tech.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration_); }; /** * Stops tracking progress by clearing progress interval * * @method stopTrackingProgress */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ /** * Set event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOn */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Remove event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOff */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Tracks current time * * @method trackCurrentTime */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; /** * Turn off play progress tracking (when paused or dragging) * * @method stopTrackingCurrentTime */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off any manual progress or timeupdate tracking * * @method dispose */ Tech.prototype.dispose = function dispose() { // clear out text tracks because we can't reuse them between techs var textTracks = this.textTracks(); if (textTracks) { var i = textTracks.length; while (i--) { this.removeRemoteTextTrack(textTracks[i]); } } // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * When invoked without an argument, returns a MediaError object * representing the current error state of the player or null if * there is no error. When invoked with an argument, set the current * error state of the player. * @param {MediaError=} err Optional an error object * @return {MediaError} the current error object or null * @method error */ Tech.prototype.error = function error(err) { if (err !== undefined) { if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } this.trigger('error'); } return this.error_; }; /** * Return the time ranges that have been played through for the * current source. This implementation is incomplete. It does not * track the played time ranges, only whether the source has played * at all or not. * @return {TimeRangeObject} a single time range if this video has * played or an empty set of ranges if not. * @method played */ Tech.prototype.played = function played() { if (this.hasStarted_) { return _utilsTimeRangesJs.createTimeRange(0, 0); } return _utilsTimeRangesJs.createTimeRange(); }; /** * Set current time * * @method setCurrentTime */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Initialize texttrack listeners * * @method initTextTrackListeners */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) return; tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { if (!_globalWindow2['default']['WebVTT'] && this.el().parentNode != null) { var script = _globalDocument2['default'].createElement('script'); script.src = this.options_['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js'; this.el().parentNode.appendChild(script); _globalWindow2['default']['WebVTT'] = true; } var tracks = this.textTracks(); if (!tracks) { return; } var textTracksChanges = Fn.bind(this, function () { var _this = this; var updateDisplay = function updateDisplay() { return _this.trigger('texttrackchange'); }; updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }); tracks.addEventListener('change', textTracksChanges); this.on('dispose', function () { tracks.removeEventListener('change', textTracksChanges); }); }; /* * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * Get texttracks * * @returns {TextTrackList} * @method textTracks */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _tracksTextTrackList2['default'](); return this.textTracks_; }; /** * Get remote texttracks * * @returns {TextTrackList} * @method remoteTextTracks */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _tracksTextTrackList2['default'](); return this.remoteTextTracks_; }; /** * Creates and returns a remote text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { var track = createTrackHelper(this, options.kind, options.label, options.language, options); this.remoteTextTracks().addTrack_(track); return { track: track }; }; /** * Remove remote texttrack * * @param {TextTrackObject} track Texttrack to remove * @method removeRemoteTextTrack */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.textTracks().removeTrack_(track); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. * * @method setPoster */ Tech.prototype.setPoster = function setPoster() {}; return Tech; })(_component2['default']); Tech.prototype.textTracks_; var createTrackHelper = function createTrackHelper(self, kind, label, language) { var options = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4]; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _tracksTextTrack2['default'](options); tracks.addTrack_(track); return track; }; Tech.prototype.featuresVolumeControl = true; // Resizing plugins using request fullscreen reloads the plugin Tech.prototype.featuresFullscreenResize = false; Tech.prototype.featuresPlaybackRate = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf Tech.prototype.featuresProgressEvents = false; Tech.prototype.featuresTimeupdateEvents = false; Tech.prototype.featuresNativeTextTracks = false; /* * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * Tech.withSourceHandlers.call(MyTech); * */ Tech.withSourceHandlers = function (_Tech) { /* * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /* * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ _Tech.selectSourceHandler = function (source) { var handlers = _Tech.sourceHandlers || []; var can = undefined; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /* * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj) { var sh = _Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; var originalSeekable = _Tech.prototype.seekable; // when a source handler is registered, prefer its implementation of // seekable when present. _Tech.prototype.seekable = function () { if (this.sourceHandler_ && this.sourceHandler_.seekable) { return this.sourceHandler_.seekable(); } return originalSeekable.call(this); }; /* * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {Tech} self */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _utilsLogJs2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); return this; }; /* * Clean up any existing source handler */ _Tech.prototype.disposeSourceHandler = function () { if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } }; }; _component2['default'].registerComponent('Tech', Tech); // Old name for Tech _component2['default'].registerComponent('MediaTechController', Tech); exports['default'] = Tech; module.exports = exports['default']; },{"../component":48,"../media-error.js":83,"../tracks/text-track":103,"../tracks/text-track-list":101,"../utils/buffer.js":105,"../utils/fn.js":109,"../utils/log.js":112,"../utils/time-ranges.js":115,"global/document":1,"global/window":2}],97:[function(_dereq_,module,exports){ /** * @file text-track-cue-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; */ var TextTrackCueList = function TextTrackCueList(cues) { var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { list[prop] = TextTrackCueList.prototype[prop]; } } TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } }; TextTrackCueList.prototype.setCues_ = function (cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(i) { if (!('' + i in this)) { Object.defineProperty(this, '' + i, { get: function get() { return this.cues_[i]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; TextTrackCueList.prototype.getCueById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; exports['default'] = TextTrackCueList; module.exports = exports['default']; },{"../utils/browser.js":104,"global/document":1}],98:[function(_dereq_,module,exports){ /** * @file text-track-display.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _menuMenuJs = _dereq_('../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _menuMenuItemJs = _dereq_('../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _menuMenuButtonJs = _dereq_('../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * The component for displaying text track cues * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class TextTrackDisplay */ var TextTrackDisplay = (function (_Component) { _inherits(TextTrackDisplay, _Component); function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); _Component.call(this, player, options, ready); player.on('loadstart', Fn.bind(this, this.toggleDisplay)); player.on('texttrackchange', Fn.bind(this, this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(this, function () { if (player.tech && player.tech['featuresNativeTextTracks']) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions['tracks'] || []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } /** * Add cue HTML to display * * @param {Number} color Hex number for color, like #f0e * @param {Number} opacity Value for opacity,0.0 - 1.0 * @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)' * @method constructColor */ /** * Toggle display texttracks * * @method toggleDisplay */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech && this.player_.tech['featuresNativeTextTracks']) { this.hide(); } else { this.show(); } }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * Clear display texttracks * * @method clearDisplay */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _globalWindow2['default']['WebVTT'] === 'function') { _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], [], this.el_); } }; /** * Update display texttracks * * @method updateDisplay */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['mode'] === 'showing') { this.updateForTrack(track); } } }; /** * Add texttrack to texttrack list * * @param {TextTrackObject} track Texttrack object to be added to list * @method updateForTrack */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _globalWindow2['default']['WebVTT'] !== 'function' || !track['activeCues']) { return; } var overrides = this.player_['textTrackSettings'].getValues(); var cues = []; for (var _i = 0; _i < track['activeCues'].length; _i++) { cues.push(track['activeCues'][_i]); } _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], track['activeCues'], this.el_); var i = cues.length; while (i--) { var cueDiv = cues[i].displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _globalWindow2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; })(_component2['default']); function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update style * Some style changes will throw an error, particularly in IE8. Those should be noops. * * @param {Element} el The element to be styles * @param {CSSProperty} style The CSS property to be styled * @param {CSSStyle} rule The actual style to be applied to the property * @method tryUpdateStyle */ function tryUpdateStyle(el, style, rule) { // try { el.style[style] = rule; } catch (e) {} } _component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; module.exports = exports['default']; },{"../component":48,"../menu/menu-button.js":84,"../menu/menu-item.js":85,"../menu/menu.js":86,"../utils/fn.js":109,"global/document":1,"global/window":2}],99:[function(_dereq_,module,exports){ /** * @file text-track-enums.js * * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ 'use strict'; exports.__esModule = true; var TextTrackMode = { 'disabled': 'disabled', 'hidden': 'hidden', 'showing': 'showing' }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" }; */ var TextTrackKind = { 'subtitles': 'subtitles', 'captions': 'captions', 'descriptions': 'descriptions', 'chapters': 'chapters', 'metadata': 'metadata' }; exports.TextTrackMode = TextTrackMode; exports.TextTrackKind = TextTrackKind; },{}],100:[function(_dereq_,module,exports){ /** * Utilities for capturing text track state and re-creating tracks * based on a capture. * * @file text-track-list-converter.js */ /** * Examine a single text track and return a JSON-compatible javascript * object that represents the text track's state. * @param track {TextTrackObject} the text track to query * @return {Object} a serializable javascript representation of the * @private */ 'use strict'; exports.__esModule = true; var trackToJson_ = function trackToJson_(track) { return { kind: track.kind, label: track.label, language: track.language, id: track.id, inBandMetadataTrackDispatchType: track.inBandMetadataTrackDispatchType, mode: track.mode, cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }), src: track.src }; }; /** * Examine a tech and return a JSON-compatible javascript array that * represents the state of all text tracks currently configured. The * return array is compatible with `jsonToTextTracks`. * @param tech {tech} the tech object to query * @return {Array} a serializable javascript representation of the * @function textTracksToJson */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.el().querySelectorAll('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); json.src = trackEl.src; return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Creates a set of remote text tracks on a tech based on an array of * javascript text track representations. * @param json {Array} an array of text track representation objects, * like those that would be produced by `textTracksToJson` * @param tech {tech} the tech to create text tracks on * @function jsonToTextTracks */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; module.exports = exports['default']; },{}],101:[function(_dereq_,module,exports){ /** * @file text-track-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; */ var TextTrackList = function TextTrackList(tracks) { var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackList.prototype) { list[prop] = TextTrackList.prototype[prop]; } } tracks = tracks || []; list.tracks_ = []; Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (browser.IS_IE8) { return list; } }; TextTrackList.prototype = Object.create(_eventTarget2['default'].prototype); TextTrackList.prototype.constructor = TextTrackList; /* * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ TextTrackList.prototype.allowedEvents_ = { 'change': 'change', 'addtrack': 'addtrack', 'removetrack': 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var _event in TextTrackList.prototype.allowedEvents_) { TextTrackList.prototype['on' + _event] = null; } TextTrackList.prototype.addTrack_ = function (track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ type: 'addtrack', track: track }); }; TextTrackList.prototype.removeTrack_ = function (rtrack) { var result = null; var track = undefined; for (var i = 0, l = this.length; i < l; i++) { track = this[i]; if (track === rtrack) { this.tracks_.splice(i, 1); break; } } this.trigger({ type: 'removetrack', track: track }); }; TextTrackList.prototype.getTrackById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; exports['default'] = TextTrackList; module.exports = exports['default']; },{"../event-target":79,"../utils/browser.js":104,"../utils/fn.js":109,"global/document":1}],102:[function(_dereq_,module,exports){ /** * @file text-track-settings.js */ 'use strict'; exports.__esModule = true; 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 }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Manipulate settings of texttracks * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class TextTrackSettings */ var TextTrackSettings = (function (_Component) { _inherits(TextTrackSettings, _Component); function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); _Component.call(this, player, options); this.hide(); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings; } Events.on(this.el().querySelector('.vjs-done-button'), 'click', Fn.bind(this, function () { this.saveSettings(); this.hide(); })); Events.on(this.el().querySelector('.vjs-default-button'), 'click', Fn.bind(this, function () { this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0; this.el().querySelector('.window-color > select').selectedIndex = 0; this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-edge-style select').selectedIndex = 0; this.el().querySelector('.vjs-font-family select').selectedIndex = 0; this.el().querySelector('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); Events.on(this.el().querySelector('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay)); if (this.options_.persistTextTrackSettings) { this.restoreSettings(); } } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackSettings.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; /** * Get texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @return {Object} * @method getValues */ TextTrackSettings.prototype.getValues = function getValues() { var el = this.el(); var textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select')); var fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select')); var fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select')); var textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select')); var bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select')); var bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select')); var windowColor = getSelectedOptionValue(el.querySelector('.window-color > select')); var windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select')); var fontPercent = _globalWindow2['default']['parseFloat'](getSelectedOptionValue(el.querySelector('.vjs-font-percent > select'))); var result = { 'backgroundOpacity': bgOpacity, 'textOpacity': textOpacity, 'windowOpacity': windowOpacity, 'edgeStyle': textEdge, 'fontFamily': fontFamily, 'color': fgColor, 'backgroundColor': bgColor, 'windowColor': windowColor, 'fontPercent': fontPercent }; for (var _name in result) { if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1.00) { delete result[_name]; } } return result; }; /** * Set texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @param {Object} values Object with texttrack setting values * @method setValues */ TextTrackSettings.prototype.setValues = function setValues(values) { var el = this.el(); setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily); setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color); setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(el.querySelector('.window-color > select'), values.windowColor); setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity); var fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent); }; /** * Restore texttrack settings * * @method restoreSettings */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var _safeParseTuple = _safeJsonParseTuple2['default'](_globalWindow2['default'].localStorage.getItem('vjs-text-track-settings')); var err = _safeParseTuple[0]; var values = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } if (values) { this.setValues(values); } }; /** * Save texttrack settings to local storage * * @method saveSettings */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.getOwnPropertyNames(values).length > 0) { _globalWindow2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { _globalWindow2['default'].localStorage.removeItem('vjs-text-track-settings'); } } catch (e) {} }; /** * Update display of texttrack settings * * @method updateDisplay */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; })(_component2['default']); _component2['default'].registerComponent('TextTrackSettings', TextTrackSettings); function getSelectedOptionValue(target) { var selectedOption = undefined; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { if (!value) { return; } var i = undefined; for (i = 0; i < target.options.length; i++) { var option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>'; return template; } exports['default'] = TextTrackSettings; module.exports = exports['default']; },{"../component":48,"../utils/events.js":108,"../utils/fn.js":109,"../utils/log.js":112,"global/window":2,"safe-json-parse/tuple":45}],103:[function(_dereq_,module,exports){ /** * @file text-track.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _textTrackCueList = _dereq_('./text-track-cue-list'); var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('../utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _textTrackEnums = _dereq_('./text-track-enums'); var TextTrackEnum = _interopRequireWildcard(_textTrackEnums); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _xhrJs = _dereq_('../xhr.js'); var _xhrJs2 = _interopRequireDefault(_xhrJs); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; */ var TextTrack = function TextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (!options.tech) { throw new Error('A tech was not provided.'); } var tt = this; if (browser.IS_IE8) { tt = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrack.prototype) { tt[prop] = TextTrack.prototype[prop]; } } tt.tech_ = options.tech; var mode = TextTrackEnum.TextTrackMode[options['mode']] || 'disabled'; var kind = TextTrackEnum.TextTrackKind[options['kind']] || 'subtitles'; var label = options['label'] || ''; var language = options['language'] || options['srclang'] || ''; var id = options['id'] || 'vjs_text_track_' + Guid.newGUID(); if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; var cues = new _textTrackCueList2['default'](tt.cues_); var activeCues = new _textTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { this['activeCues']; if (changed) { this['trigger']('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function get() { return kind; }, set: Function.prototype }); Object.defineProperty(tt, 'label', { get: function get() { return label; }, set: Function.prototype }); Object.defineProperty(tt, 'language', { get: function get() { return language; }, set: Function.prototype }); Object.defineProperty(tt, 'id', { get: function get() { return id; }, set: Function.prototype }); Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { if (!TextTrackEnum.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: Function.prototype }); Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } if (this['cues'].length === 0) { return activeCues; // nothing to do } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this['cues'].length; i < l; i++) { var cue = this['cues'][i]; if (cue['startTime'] <= ct && cue['endTime'] >= ct) { active.push(cue); } else if (cue['startTime'] === cue['endTime'] && cue['startTime'] <= ct && cue['startTime'] + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var i = 0; i < active.length; i++) { if (indexOf.call(this.activeCues_, active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: Function.prototype }); if (options.src) { tt.src = options.src; loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (browser.IS_IE8) { return tt; } }; TextTrack.prototype = Object.create(_eventTarget2['default'].prototype); TextTrack.prototype.constructor = TextTrack; /* * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { 'cuechange': 'cuechange' }; TextTrack.prototype.addCue = function (cue) { var tracks = this.tech_.textTracks(); if (tracks) { for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this['cues'].setCues_(this.cues_); }; TextTrack.prototype.removeCue = function (removeCue) { var removed = false; for (var i = 0, l = this.cues_.length; i < l; i++) { var cue = this.cues_[i]; if (cue === removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; /* * Downloading stuff happens below this point */ var parseCues = function parseCues(srcContent, track) { if (typeof _globalWindow2['default']['WebVTT'] !== 'function') { //try again a bit later return _globalWindow2['default'].setTimeout(function () { parseCues(srcContent, track); }, 25); } var parser = new _globalWindow2['default']['WebVTT']['Parser'](_globalWindow2['default'], _globalWindow2['default']['vttjs'], _globalWindow2['default']['WebVTT']['StringDecoder']()); parser['oncue'] = function (cue) { track.addCue(cue); }; parser['onparsingerror'] = function (error) { _utilsLogJs2['default'].error(error); }; parser['parse'](srcContent); parser['flush'](); }; var loadTrack = function loadTrack(src, track) { _xhrJs2['default'](src, Fn.bind(this, function (err, response, responseBody) { if (err) { return _utilsLogJs2['default'].error(err, response); } track.loaded_ = true; parseCues(responseBody, track); })); }; var indexOf = function indexOf(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; exports['default'] = TextTrack; module.exports = exports['default']; },{"../event-target":79,"../utils/browser.js":104,"../utils/fn.js":109,"../utils/guid.js":111,"../utils/log.js":112,"../xhr.js":119,"./text-track-cue-list":97,"./text-track-enums":99,"global/document":1,"global/window":2}],104:[function(_dereq_,module,exports){ /** * @file browser.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var USER_AGENT = _globalWindow2['default'].navigator.userAgent; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPHONE = /iPhone/i.test(USER_AGENT); exports.IS_IPHONE = IS_IPHONE; var IS_IPAD = /iPad/i.test(USER_AGENT); exports.IS_IPAD = IS_IPAD; var IS_IPOD = /iPod/i.test(USER_AGENT); exports.IS_IPOD = IS_IPOD; var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; exports.IS_IOS = IS_IOS; var IOS_VERSION = (function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); exports.IOS_VERSION = IOS_VERSION; var IS_ANDROID = /Android/i.test(USER_AGENT); exports.IS_ANDROID = IS_ANDROID; var ANDROID_VERSION = (function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); exports.ANDROID_VERSION = ANDROID_VERSION; // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; exports.IS_OLD_ANDROID = IS_OLD_ANDROID; var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; exports.IS_NATIVE_ANDROID = IS_NATIVE_ANDROID; var IS_FIREFOX = /Firefox/i.test(USER_AGENT); exports.IS_FIREFOX = IS_FIREFOX; var IS_CHROME = /Chrome/i.test(USER_AGENT); exports.IS_CHROME = IS_CHROME; var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); exports.IS_IE8 = IS_IE8; var TOUCH_ENABLED = !!('ontouchstart' in _globalWindow2['default'] || _globalWindow2['default'].DocumentTouch && _globalDocument2['default'] instanceof _globalWindow2['default'].DocumentTouch); exports.TOUCH_ENABLED = TOUCH_ENABLED; var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _globalDocument2['default'].createElement('video').style); exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED; },{"global/document":1,"global/window":2}],105:[function(_dereq_,module,exports){ /** * @file buffer.js */ 'use strict'; exports.__esModule = true; exports.bufferedPercent = bufferedPercent; var _timeRangesJs = _dereq_('./time-ranges.js'); /** * Compute how much your video has been buffered * * @param {Object} Buffered object * @param {Number} Total duration * @return {Number} Percent buffered of the total duration * @private * @function bufferedPercent */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0, start, end; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = _timeRangesJs.createTimeRange(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } },{"./time-ranges.js":115}],106:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); /** * Object containing the default behaviors for available handler methods. * * @private * @type {Object} */ var defaultBehaviors = { get: function get(obj, key) { return obj[key]; }, set: function set(obj, key, value) { obj[key] = value; return true; } }; /** * Expose private objects publicly using a Proxy to log deprecation warnings. * * Browsers that do not support Proxy objects will simply return the `target` * object, so it can be directly exposed. * * @param {Object} target The target object. * @param {Object} messages Messages to display from a Proxy. Only operations * with an associated message will be proxied. * @param {String} [messages.get] * @param {String} [messages.set] * @return {Object} A Proxy if supported or the `target` argument. */ exports['default'] = function (target) { var messages = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (typeof Proxy === 'function') { var _ret = (function () { var handler = {}; // Build a handler object based on those keys that have both messages // and default behaviors. Object.keys(messages).forEach(function (key) { if (defaultBehaviors.hasOwnProperty(key)) { handler[key] = function () { _logJs2['default'].warn(messages[key]); return defaultBehaviors[key].apply(this, arguments); }; } }); return { v: new Proxy(target, handler) }; })(); if (typeof _ret === 'object') return _ret.v; } return target; }; module.exports = exports['default']; },{"./log.js":112}],107:[function(_dereq_,module,exports){ /** * @file dom.js */ 'use strict'; exports.__esModule = true; exports.getEl = getEl; exports.createEl = createEl; exports.insertElFirst = insertElFirst; exports.getElData = getElData; exports.hasElData = hasElData; exports.removeElData = removeElData; exports.hasElClass = hasElClass; exports.addElClass = addElClass; exports.removeElClass = removeElClass; exports.setElAttributes = setElAttributes; exports.getElAttributes = getElAttributes; exports.blockTextSelection = blockTextSelection; exports.unblockTextSelection = unblockTextSelection; exports.findElPosition = findElPosition; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {String} id Element ID * @return {Element} Element with supplied ID * @function getEl */ function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _globalDocument2['default'].getElementById(id); } /** * Creates an element and applies properties. * * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @function createEl */ function createEl() { var tagName = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0]; var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var el = _globalDocument2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria- * attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria- * attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; } /** * Insert an element as the first child node of another * * @param {Element} child Element to insert * @param {Element} parent Element to insert child into * @private * @function insertElFirst */ function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {String} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); /** * Returns the cache object where data for an element is stored * * @param {Element} el Element to store data for. * @return {Object} * @function getElData */ function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } /** * Returns whether or not an element has cached data * * @param {Element} el A dom element * @return {Boolean} * @private * @function hasElData */ function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el Remove data for an element * @private * @function removeElData */ function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } /** * Check if an element has a CSS class * * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @function hasElClass */ function hasElClass(element, classToCheck) { return (' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1; } /** * Add a CSS class name to an element * * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @function addElClass */ function addElClass(element, classToAdd) { if (!hasElClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } } /** * Remove a CSS class name from an element * * @param {Element} element Element to remove from class name * @param {String} classToRemove Classname to remove * @function removeElClass */ function removeElClass(element, classToRemove) { if (!hasElClass(element, classToRemove)) { return; } var classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (var i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i, 1); } } element.className = classNames.join(' '); } /** * Apply attributes to an HTML element. * * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private * @function setElAttributes */ function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private * @function getElAttributes */ function getElAttributes(tag) { var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Attempt to block the ability to select text while dragging controls * * @return {Boolean} * @method blockTextSelection */ function blockTextSelection() { _globalDocument2['default'].body.focus(); _globalDocument2['default'].onselectstart = function () { return false; }; } /** * Turn off text selection blocking * * @return {Boolean} * @method unblockTextSelection */ function unblockTextSelection() { _globalDocument2['default'].onselectstart = function () { return true; }; } /** * Offset Left * getBoundingClientRect technique from * John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el Element from which to get offset * @return {Object=} * @method findElPosition */ function findElPosition(el) { var box = undefined; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _globalDocument2['default'].documentElement; var body = _globalDocument2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _globalWindow2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _globalWindow2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } },{"./guid.js":111,"global/document":1,"global/window":2}],108:[function(_dereq_,module,exports){ /** * @file events.js * * Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ 'use strict'; exports.__esModule = true; exports.on = on; exports.off = off; exports.trigger = trigger; exports.one = one; exports.fixEvent = fixEvent; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _domJs = _dereq_('./dom.js'); var Dom = _interopRequireWildcard(_domJs); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = Guid.newGUID(); data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) return; event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event, hash); } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) return; var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); }return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } /** * Fix a native event to have standard property values * * @param {Object} event Event object to fix * @return {Object} * @private * @method fixEvent */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _globalWindow2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation // and webkitMovementX/Y if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _globalDocument2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = _globalDocument2['default'].documentElement, body = _globalDocument2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; } } // Returns fixed-up instance return event; } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private * @method _cleanUpEvents */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private * @function _handleMultipleEvents */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { //Call the event method for each one of the types fn(elem, type, callback); }); } },{"./dom.js":107,"./guid.js":111,"global/document":1,"global/window":2}],109:[function(_dereq_,module,exports){ /** * @file fn.js */ 'use strict'; exports.__esModule = true; var _guidJs = _dereq_('./guid.js'); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private * @method bind */ var bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = _guidJs.newGUID(); } // Create the new function that changes the context var ret = function ret() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = uid ? uid + '_' + fn.guid : fn.guid; return ret; }; exports.bind = bind; },{"./guid.js":111}],110:[function(_dereq_,module,exports){ /** * @file format-time.js * * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private * @function formatTime */ 'use strict'; exports.__esModule = true; function formatTime(seconds) { var guide = arguments.length <= 1 || arguments[1] === undefined ? seconds : arguments[1]; return (function () { var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; })(); } exports['default'] = formatTime; module.exports = exports['default']; },{}],111:[function(_dereq_,module,exports){ /** * @file guid.js * * Unique ID for an element or function * @type {Number} * @private */ "use strict"; exports.__esModule = true; exports.newGUID = newGUID; var _guid = 1; /** * Get the next unique ID * * @return {String} * @function newGUID */ function newGUID() { return _guid++; } },{}],112:[function(_dereq_,module,exports){ /** * @file log.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Log plain debug messages */ var log = function log() { _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ log.history = []; /** * Log error messages */ log.error = function () { _logType('error', arguments); }; /** * Log warning messages */ log.warn = function () { _logType('warn', arguments); }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {Object} args The args to be passed to the log * @private * @method _logType */ function _logType(type, args) { // convert args to an array to get array functions var argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist var noop = function noop() {}; var console = _globalWindow2['default']['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase() + ':'); } else { // default to log with no prefix type = 'log'; } // add to history log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } exports['default'] = log; module.exports = exports['default']; },{"global/window":2}],113:[function(_dereq_,module,exports){ /** * @file merge-options.js */ 'use strict'; exports.__esModule = true; exports['default'] = mergeOptions; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); function isPlain(obj) { return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; } /** * Merge customizer. video.js simply overwrites non-simple objects * (like arrays) instead of attempting to overlay them. * @see https://lodash.com/docs#merge */ var customizer = function customizer(destination, source) { // If we're not working with a plain object, copy the value as is // If source is an array, for instance, it will replace destination if (!isPlain(source)) { return source; } // If the new value is a plain object but the first object value is not // we need to create a new object for the first object to merge with. // This makes it consistent with how merge() works by default // and also protects from later changes the to first object affecting // the second object's values. if (!isPlain(destination)) { return mergeOptions(source); } }; /** * Merge one or more options objects, recursively merging **only** * plain object properties. Previously `deepMerge`. * * @param {...Object} source One or more objects to merge * @returns {Object} a new object that is the union of all * provided objects * @function mergeOptions */ function mergeOptions() { // contruct the call dynamically to handle the variable number of // objects to merge var args = Array.prototype.slice.call(arguments); // unshift an empty object into the front of the call as the target // of the merge args.unshift({}); // customize conflict resolution to match our historical merge behavior args.push(customizer); _lodashCompatObjectMerge2['default'].apply(null, args); // return the mutated result object return args[0]; } module.exports = exports['default']; },{"lodash-compat/object/merge":37}],114:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var createStyleElement = function createStyleElement(className) { var style = _globalDocument2['default'].createElement('style'); style.className = className; return style; }; exports.createStyleElement = createStyleElement; var setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; exports.setTextContent = setTextContent; },{"global/document":1}],115:[function(_dereq_,module,exports){ /** * @file time-ranges.js * * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private * @method createTimeRange */ 'use strict'; exports.__esModule = true; exports.createTimeRange = createTimeRange; function createTimeRange(_start, _end) { if (_start === undefined && _end === undefined) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: 1, start: function start() { return _start; }, end: function end() { return _end; } }; } },{}],116:[function(_dereq_,module,exports){ /** * @file to-title-case.js * * Uppercase the first letter of a string * * @param {String} string String to be uppercased * @return {String} * @private * @method toTitleCase */ "use strict"; exports.__esModule = true; function toTitleCase(string) { return string.charAt(0).toUpperCase() + string.slice(1); } exports["default"] = toTitleCase; module.exports = exports["default"]; },{}],117:[function(_dereq_,module,exports){ /** * @file url.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ var parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _globalDocument2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = undefined; if (addToBody) { div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _globalDocument2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _globalDocument2['default'].body.removeChild(div); } return details; }; exports.parseUrl = parseUrl; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * * @param {String} url URL to make absolute * @return {String} Absolute URL * @private * @method getAbsoluteURL */ var getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; exports.getAbsoluteURL = getAbsoluteURL; /** * Returns the extension of the passed file name. It will return an empty string if you pass an invalid path * * @param {String} path The fileName path like '/path/to/file.mp4' * @returns {String} The extension in lower case or an empty string if no extension could be found. * @method getFileExtension */ var getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; exports.getFileExtension = getFileExtension; },{"global/document":1}],118:[function(_dereq_,module,exports){ /** * @file video.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _setup = _dereq_('./setup'); var setup = _interopRequireWildcard(_setup); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _eventTarget = _dereq_('./event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _player = _dereq_('./player'); var _player2 = _interopRequireDefault(_player); var _pluginsJs = _dereq_('./plugins.js'); var _pluginsJs2 = _interopRequireDefault(_pluginsJs); var _srcJsUtilsMergeOptionsJs = _dereq_('../../src/js/utils/merge-options.js'); var _srcJsUtilsMergeOptionsJs2 = _interopRequireDefault(_srcJsUtilsMergeOptionsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsFormatTimeJs = _dereq_('./utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _xhrJs = _dereq_('./xhr.js'); var _xhrJs2 = _interopRequireDefault(_xhrJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsUrlJs = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _extendsJs = _dereq_('./extends.js'); var _extendsJs2 = _interopRequireDefault(_extendsJs); var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); var _utilsCreateDeprecationProxyJs = _dereq_('./utils/create-deprecation-proxy.js'); var _utilsCreateDeprecationProxyJs2 = _interopRequireDefault(_utilsCreateDeprecationProxyJs); // Include the built-in techs var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); var _techFlashJs = _dereq_('./tech/flash.js'); var _techFlashJs2 = _interopRequireDefault(_techFlashJs); // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined') { _globalDocument2['default'].createElement('video'); _globalDocument2['default'].createElement('audio'); _globalDocument2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * ```js * var myPlayer = videojs('my_video_id'); * ``` * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {Player} A player instance * @mixes videojs * @method videojs */ var videojs = function videojs(id, options, ready) { var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (videojs.getPlayers()[id]) { // If options or ready funtion are passed, warn if (options) { _utilsLogJs2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { videojs.getPlayers()[id].ready(ready); } return videojs.getPlayers()[id]; // Otherwise get element for ID } else { tag = Dom.getEl(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || new _player2['default'](tag, options, ready); }; // Add default styles var style = stylesheet.createStyleElement('vjs-styles-defaults'); var head = _globalDocument2['default'].querySelector('head'); head.insertBefore(style, head.firstChild); stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n'); // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /* * Current software version (semver) * * @type {String} */ videojs.VERSION = '5.0.0-rc.83'; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * ```js * videojs.options.autoplay = true * // -> all players will autoplay by default * ``` * * @type {Object} */ videojs.options = _player2['default'].prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} The created players * @mixes videojs * @method getPlayers */ videojs.getPlayers = function () { return _player2['default'].players; }; /** * For backward compatibility, expose players object. * * @deprecated * @memberOf videojs * @property {Object|Proxy} players */ videojs.players = _utilsCreateDeprecationProxyJs2['default'](_player2['default'].players, { get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead', set: 'Modification of videojs.players is deprecated' }); /** * Get a component class object by name * ```js * var VjsButton = videojs.getComponent('Button'); * // Create a new instance of the component * var myButton = new VjsButton(myPlayer); * ``` * * @return {Component} Component identified by name * @mixes videojs * @method getComponent */ videojs.getComponent = _component2['default'].getComponent; /** * Register a component so it can referred to by name * Used when adding to other * components, either through addChild * `component.addChild('myComponent')` * or through default children options * `{ children: ['myComponent'] }`. * ```js * // Get a component to subclass * var VjsButton = videojs.getComponent('Button'); * // Subclass the component (see 'extends' doc for more info) * var MySpecialButton = videojs.extends(VjsButton, {}); * // Register the new component * VjsButton.registerComponent('MySepcialButton', MySepcialButton); * // (optionally) add the new component as a default player child * myPlayer.addChild('MySepcialButton'); * ``` * NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {String} The class name of the component * @param {Component} The component class * @return {Component} The newly registered component * @mixes videojs * @method registerComponent */ videojs.registerComponent = _component2['default'].registerComponent; /** * A suite of browser and device tests * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated * @type {Boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extends` keyword * ```js * // Create a basic javascript 'class' * function MyClass(name){ * // Set a property at initialization * this.myName = name; * } * // Create an instance method * MyClass.prototype.sayMyName = function(){ * alert(this.myName); * }; * // Subclass the exisitng class and change the name * // when initializing * var MySubClass = videojs.extends(MyClass, { * constructor: function(name) { * // Call the super class constructor for the subclass * MyClass.call(this, name) * } * }); * // Create an instance of the new sub class * var myInstance = new MySubClass('John'); * myInstance.sayMyName(); // -> should alert "John" * ``` * * @param {Function} The Class to subclass * @param {Object} An object including instace methods for the new class * Optionally including a `constructor` function * @return {Function} The newly created subclass * @mixes videojs * @method extends */ videojs['extends'] = _extendsJs2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * ```js * var defaultOptions = { * foo: true, * bar: { * a: true, * b: [1,2,3] * } * }; * var newOptions = { * foo: false, * bar: { * b: [4,5,6] * } * }; * var result = videojs.mergeOptions(defaultOptions, newOptions); * // result.foo = false; * // result.bar.a = true; * // result.bar.b = [4,5,6]; * ``` * * @param {Object} The options object whose values will be overriden * @param {Object} The options object with values to override the first * @param {Object} Any number of additional options objects * * @return {Object} a new object with the merged values * @mixes videojs * @method mergeOptions */ videojs.mergeOptions = _srcJsUtilsMergeOptionsJs2['default']; /** * Change the context (this) of a function * * videojs.bind(newContext, function(){ * this === newContext * }); * * NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function(){}.bind(newContext);` instead of this. * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * **See the plugin guide in the docs for a more detailed example** * ```js * // Make a plugin that alerts when the player plays * videojs.plugin('myPlugin', function(myPluginOptions) { * myPluginOptions = myPluginOptions || {}; * * var player = this; * var alertText = myPluginOptions.text || 'Player is playing!' * * player.on('play', function(){ * alert(alertText); * }); * }); * // USAGE EXAMPLES * // EXAMPLE 1: New player with plugin options, call plugin immediately * var player1 = videojs('idOne', { * myPlugin: { * text: 'Custom text!' * } * }); * // Click play * // --> Should alert 'Custom text!' * // EXAMPLE 3: New player, initialize plugin later * var player3 = videojs('idThree'); * // Click play * // --> NO ALERT * // Click pause * // Initialize plugin using the plugin function on the player instance * player3.myPlugin({ * text: 'Plugin added later!' * }); * // Click play * // --> Should alert 'Plugin added later!' * ``` * * @param {String} The plugin name * @param {Function} The plugin function that will be called with options * @mixes videojs * @method plugin */ videojs.plugin = _pluginsJs2['default']; /** * Adding languages so that they're available to all players. * ```js * videojs.addLanguage('es', { 'Hello': 'Hola' }); * ``` * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting language dictionary object * @mixes videojs * @method addLanguage */ videojs.addLanguage = function (code, data) { var _merge; code = ('' + code).toLowerCase(); return _lodashCompatObjectMerge2['default'](videojs.options.languages, (_merge = {}, _merge[code] = data, _merge))[code]; }; /** * Log debug messages. * * @param {...Object} messages One or more messages to log */ videojs.log = _utilsLogJs2['default']; /** * Creates an emulated TimeRange object. * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @method createTimeRange */ videojs.createTimeRange = _utilsTimeRangesJs.createTimeRange; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @method formatTime */ videojs.formatTime = _utilsFormatTimeJs2['default']; /** * Simple http request for retrieving external files (e.g. text tracks) * * ##### Example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * API is modeled after the Raynos/xhr. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @returns {Object} The request */ videojs.xhr = _xhrJs2['default']; /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Event target class. * * @type {Function} */ videojs.EventTarget = _eventTarget2['default']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ videojs.on = Events.on; /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ videojs.one = Events.one; /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ videojs.off = Events.off; /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ videojs.trigger = Events.trigger; // REMOVING: We probably should add this to the migration plugin // // Expose but deprecate the window[componentName] method for accessing components // Object.getOwnPropertyNames(Component.components).forEach(function(name){ // let component = Component.components[name]; // // // A deprecation warning as the constuctor // module.exports[name] = function(player, options, ready){ // log.warn('Using videojs.'+name+' to access the '+name+' component has been deprecated. Please use videojs.getComponent("componentName")'); // // return new Component(player, options, ready); // }; // // // Allow the prototype and class methods to be accessible still this way // // Though anything that attempts to override class methods will no longer work // assign(module.exports[name], component); // }); /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define('videojs', [], function () { return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } exports['default'] = videojs; module.exports = exports['default']; },{"../../src/js/utils/merge-options.js":113,"./component":48,"./event-target":79,"./extends.js":80,"./player":87,"./plugins.js":88,"./setup":90,"./tech/flash.js":93,"./tech/html5.js":94,"./utils/browser.js":104,"./utils/create-deprecation-proxy.js":106,"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"./utils/format-time.js":110,"./utils/log.js":112,"./utils/stylesheet.js":114,"./utils/time-ranges.js":115,"./utils/url.js":117,"./xhr.js":119,"global/document":1,"lodash-compat/object/merge":37,"object.assign":40}],119:[function(_dereq_,module,exports){ /** * @file xhr.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsUrlJs = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /* * Simple http request for retrieving external files (e.g. text tracks) * ##### Example * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * ///////////// * API is modeled after the Raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @return {Object} The request * @method xhr */ var xhr = function xhr(options, callback) { var abortTimeout = undefined; // If options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // Merge with default options options = _utilsMergeOptionsJs2['default']({ method: 'GET', timeout: 45 * 1000 }, options); callback = callback || function () {}; var XHR = _globalWindow2['default'].XMLHttpRequest; if (typeof XHR === 'undefined') { // Shim XMLHttpRequest for older IEs XHR = function () { try { return new _globalWindow2['default'].ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new _globalWindow2['default'].ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new _globalWindow2['default'].ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } var request = new XHR(); // Store a reference to the url on the request instance request.uri = options.uri; var urlInfo = Url.parseUrl(options.uri); var winLoc = _globalWindow2['default'].location; var successHandler = function successHandler() { _globalWindow2['default'].clearTimeout(abortTimeout); callback(null, request, request.response || request.responseText); }; var errorHandler = function errorHandler(err) { _globalWindow2['default'].clearTimeout(abortTimeout); if (!err || typeof err === 'string') { err = new Error(err || 'XHR Failed with a response of: ' + (request && (request.response || request.responseText))); } callback(err, request); }; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = urlInfo.protocol + urlInfo.host !== winLoc.protocol + winLoc.host; // XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available // 'withCredentials' is only available in XMLHTTPRequest2 // Also XDomainRequest has a lot of gotchas, so only use if cross domain if (crossOrigin && _globalWindow2['default'].XDomainRequest && !('withCredentials' in request)) { request = new _globalWindow2['default'].XDomainRequest(); request.onload = successHandler; request.onerror = errorHandler; // These blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function () {}; request.ontimeout = function () {}; // XMLHTTPRequest } else { (function () { var fileUrl = urlInfo.protocol === 'file:' || winLoc.protocol === 'file:'; request.onreadystatechange = function () { if (request.readyState === 4) { if (request.timedout) { return errorHandler('timeout'); } if (request.status === 200 || fileUrl && request.status === 0) { successHandler(); } else { errorHandler(); } } }; if (options.timeout) { abortTimeout = _globalWindow2['default'].setTimeout(function () { if (request.readyState !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } })(); } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open(options.method || 'GET', options.uri, true); } catch (err) { return errorHandler(err); } // withCredentials only supported by XMLHttpRequest2 if (options.withCredentials) { request.withCredentials = true; } if (options.responseType) { request.responseType = options.responseType; } // send the request try { request.send(); } catch (err) { return errorHandler(err); } return request; }; exports['default'] = xhr; module.exports = exports['default']; },{"./utils/log.js":112,"./utils/merge-options.js":113,"./utils/url.js":117,"global/window":2}]},{},[118])(118) }); //# sourceMappingURL=video.js.map
packages/react-dom/server.js
DJCordhose/react
'use strict'; module.exports = require('react/lib/ReactDOMServer');
src/components/macros.js
DarklyLabs/LaserWeb4
import React from 'react'; import { connect } from 'react-redux'; import ReactDOM from 'react-dom'; import { PanelGroup, Panel, Tooltip } from 'react-bootstrap'; import Icon from './font-awesome' import { addMacro, removeMacro, setMacro, fireMacroById } from '../actions/macros' import { runCommand } from './com.js'; import { Button, FormControl, ButtonGroup, ButtonToolbar } from 'react-bootstrap' import Validator from 'validatorjs'; import { MACRO_VALIDATION_RULES } from '../reducers/macros' import uuid from 'node-uuid'; export class Macros extends React.Component { constructor(props) { super(props) this.state = { selected: [], label: "", keybinding: "", gcode: "", meta: [], _locked: false } this.handleSelection.bind(this) this.handleAppend.bind(this) this.handleRemove.bind(this) this.handleFormChange.bind(this) this.handleMeta.bind(this) this.metakeys = ['ctrl', 'shift', 'command', 'alt'] } handleSelection(e) { let opts = [].slice.call(e.target.selectedOptions).map(o => { return o.value; }); this.setState({ selected: opts }) if (e.target.value) { this.setState(Object.assign({ _locked: this.props.macros[e.target.value]._locked || false }, this.props.macros[e.target.value])) } else { this.setState({ keybinding: "", label: "", gcode: "", _locked: false }) } } handleAppend(e) { let macro = this.getForm(); let errors = this.getErrors(macro); if (!errors && this.state.selected.length < 2) { let id = (this.state.selected.length) ? this.state.selected[0] : uuid.v4(); this.props.handleSet({ [id]: macro }) } else { console.error(JSON.stringify(errors)) } this.setState({ ...macro, selected: [] }) } handleRemove(e) { this.props.handleRemove(this.state.selected) this.setState({ selected: [], keybinding: "", label: "", gcode: "", _locked: false }) } handleFormChange(e, fieldid) { this.setState({ [fieldid]: e.target.value }); } handleMeta(e, item) { let tokens = new Set(this.state.keybinding.trim().split("+")) if (tokens.has(item)) { tokens.delete(item); } else { tokens.add(item); } this.setState({ keybinding: Array.from(tokens).sort().join('+') }) } getForm() { let label = ReactDOM.findDOMNode(this.refs.label).value let keybinding = ReactDOM.findDOMNode(this.refs.keybinding).value let gcode = ReactDOM.findDOMNode(this.refs.gcode).value return { keybinding: [...this.state.meta, keybinding].join('+'), label, gcode } } getErrors(macro) { let validator = new Validator(macro, MACRO_VALIDATION_RULES); return (validator.passes()) ? undefined : validator.errors.errors; } render() { let errors = this.getErrors(this.state); return ( <div className="macros"> <small className="help-block">Append new key binding to Gcode. App must be reloaded to take effect</small> <FormControl componentClass="select" size="10" multiple onChange={(e) => this.handleSelection(e)} value={this.state.selected}> {Object.entries(this.props.macros).map((opt, i) => { let [key, value] = opt; return <option key={i} value={key}>{(value.keybinding) ? `[${value.keybinding}] ` : ''}{value.label}</option> })} </FormControl> <FormControl type="text" ref="label" placeholder="Label" value={this.state.label} onChange={(e) => this.handleFormChange(e, 'label')} /> <FormControl type="text" ref="keybinding" placeholder="Keybinding" value={this.state.keybinding} onChange={(e) => this.handleFormChange(e, 'keybinding')} /> <ButtonGroup> {this.metakeys.map((meta, i) => { return <Button key={i} bsSize="xsmall" bsStyle={(this.state.keybinding.indexOf(meta) !== -1) ? 'primary' : 'default'} onClick={(e) => this.handleMeta(e, meta)}>{meta}</Button> })} </ButtonGroup> <FormControl componentClass="textarea" ref="gcode" placeholder="Gcode" value={this.state.gcode} onChange={(e) => this.handleFormChange(e, 'gcode')} /> <Button bsStyle="primary" disabled={(errors !== undefined) || this.state._locked} onClick={(e) => this.handleAppend(e)} style={{ float: "left" }} title={JSON.stringify(errors)}><Icon name="share" /> Set</Button> <Button bsStyle="danger" disabled={this.state._locked} title={this.state._locked ? 'This is a locked macro' : undefined} onClick={(e) => this.handleRemove(e)} style={{ float: "right" }}><Icon name="trash" /> Remove</Button> </div> ) } } export class MacrosBar extends React.Component { handleRunMacro(id, macros) { let { label, gcode, keybinding } = macros[id]; console.log('runMacro(' + keybinding + ')'); runCommand(gcode); } render() { return ( <ButtonToolbar> {Object.entries(this.props.macros).map((macro, i) => { let [id, data] = macro; return <Button key={i} bsSize="small" onClick={(e) => this.handleRunMacro(id, this.props.macros)} title={"[" + data.keybinding + "]"}>{data.label}</Button> }) } </ButtonToolbar> ) } } const mapStateToProps = (state) => { return { macros: state.settings.macros } }; const mapDispatchToProps = (dispatch) => { return { handleRemove: (keybinding) => { dispatch(removeMacro(keybinding)) }, handleSet: (macro) => { dispatch(setMacro(macro)) }, handleMacro: (keybinding, macros) => { dispatch(fireMacroById(keybinding, macros)) } } } Macros = connect(mapStateToProps, mapDispatchToProps)(Macros); MacrosBar = connect(mapStateToProps, mapDispatchToProps)(MacrosBar);
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/AllGood.js
ylu1317/flow
// @flow import React from 'react'; class MyComponent extends React.Component<DefaultProps, Props, State> { static defaultProps: BadDefaultProps = {}; props: BadProps; state: BadState = {}; } const expression = () => class extends React.Component<DefaultProps, Props, State> { static defaultProps: BadDefaultProps = {}; props: BadProps; state: BadState = {}; }
node_modules/react-bootstrap/es/Fade.js
WatkinsSoftwareDevelopment/HowardsBarberShop
import _extends from 'babel-runtime/helpers/extends'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import Transition from 'react-overlays/lib/Transition'; var propTypes = { /** * Show the component; triggers the fade in or fade out animation */ 'in': React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: React.PropTypes.bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: React.PropTypes.number, /** * Callback fired before the component fades in */ onEnter: React.PropTypes.func, /** * Callback fired after the component starts to fade in */ onEntering: React.PropTypes.func, /** * Callback fired after the has component faded in */ onEntered: React.PropTypes.func, /** * Callback fired before the component fades out */ onExit: React.PropTypes.func, /** * Callback fired after the component starts to fade out */ onExiting: React.PropTypes.func, /** * Callback fired after the component has faded out */ onExited: React.PropTypes.func }; var defaultProps = { 'in': false, timeout: 300, unmountOnExit: false, transitionAppear: false }; var Fade = function (_React$Component) { _inherits(Fade, _React$Component); function Fade() { _classCallCheck(this, Fade); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Fade.prototype.render = function render() { return React.createElement(Transition, _extends({}, this.props, { className: classNames(this.props.className, 'fade'), enteredClassName: 'in', enteringClassName: 'in' })); }; return Fade; }(React.Component); Fade.propTypes = propTypes; Fade.defaultProps = defaultProps; export default Fade;
example/index.android.js
Liroo/react-native-markdown-syntax
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class example extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('example', () => example);
quickviz/2020-07-25-gutenberg-colors/viz/src/App.js
ebemunk/blog
import React from 'react' import './App.css' import Viz from './Viz' import Colors from './Colors' import HowToRead from './HowToRead' const P = ({ children, style, ...rest }) => ( <p style={{ color: 'white', maxWidth: '1000px', fontSize: '20px', fontFamily: '"Roboto Condensed"', ...style, }} {...rest} > {children} </p> ) function App() { return ( <div className="App" style={{ background: '#2f2f2f', minWidth: `${(400 + 60) * 5}px`, padding: '20px', // position: 'relative', }} > <div style={{ display: 'flex' }}> <HowToRead /> <div style={{ // position: 'absolute', // left: '550px', // top: '30px', textAlign: 'left', color: 'white', fontFamily: '"Caramond Georgia"', fontWeight: 'bold', fontSize: '72px', flexGrow: 1, }} > <div style={{ display: 'flex', fontFamily: '"Goudy Bookletter 1911"', letterSpacing: '4px', }} > <div className="title-color" style={{ marginRight: '1rem', marginBottom: '1rem', }} > Color </div>{' '} in Books </div> <P> This is an exploration of colors seen in Project Gutenberg's Top 25 "Best Books Ever" list. Specifically, these are the CSS Named Colors which all modern browsers support, like 'Green' or 'Red' to 'Blanched Almond' and 'Light Golden Rod Yellow'. There are 147 such colors. We read the book, from start to end (visualized clockwise) and note every occurrence of one of these 147 colors. </P> <P> At the end, we are faced with a color profile for each individual book, almost a unique "retinal scan". Does it tell us anything? Who knows. Maybe it will inspire you to read one of these classics, or compare those you have read to go "Ah, that's right!". </P> <P>Let me know what you think by tweeting me @ebemunk.</P> </div> <div style={{ maxWidth: '390px' }}> <div style={{ textAlign: 'left', color: 'white', fontSize: '16px', fontFamily: '"Roboto Condensed"', fontWeight: 600, }} > All present CSS Named Colors (53 out of 147): </div> <Colors /> </div> </div> <Viz /> </div> ) } export default App
App/index.ios.js
Tyler-Losinski/Rater-Mc-Ratey-Face
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class AwesomeNativeBase extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.ios.js </Text> <Text style={styles.instructions}> Press Cmd+R to reload,{'\n'} Cmd+D or shake for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('AwesomeNativeBase', () => AwesomeNativeBase);
react-fundamentals-es6/lessons/09-lifecycle-mounting-usage/main.js
3mundi/React-Bible
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('app'));
src/components/Search/Search.js
nambawan/g-old
// heavily inspired by https://github.com/grommet/grommet/blob/master/src/js/components/Search.js import React from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; import cn from 'classnames'; import withStyles from 'isomorphic-style-loader/withStyles'; import s from './Search.css'; import Drop from '../Drop'; const onSink = event => { event.stopPropagation(); event.nativeEvent.stopImmediatePropagation(); }; const renderLabel = suggestion => { if (typeof suggestion === 'object') { return suggestion.label || suggestion.value; } return suggestion; }; class Search extends React.Component { static contextTypes = { intl: PropTypes.object, insertCss: PropTypes.func, }; static propTypes = { dropAlign: PropTypes.shape(), id: PropTypes.string, onFocus: PropTypes.func, onDOMChange: PropTypes.func.isRequired, onSelect: PropTypes.func.isRequired, placeHolder: PropTypes.string, suggestions: PropTypes.arrayOf( PropTypes.oneOfType([ PropTypes.shape({ label: PropTypes.node, value: PropTypes.any, }), PropTypes.string, ]), ), value: PropTypes.string, }; static defaultProps = { placeHolder: null, suggestions: null, value: null, dropAlign: null, id: null, onFocus: null, }; constructor(props, context) { super(props, context); this.onAddDrop = this.onAddDrop.bind(this); this.onRemoveDrop = this.onRemoveDrop.bind(this); this.onChangeInput = this.onChangeInput.bind(this); this.onClickBody = this.onClickBody.bind(this); this.onClickSuggestion = this.onClickSuggestion.bind(this); this.fireDOMChange = this.fireDOMChange.bind(this); this.onFocusInput = this.onFocusInput.bind(this); this.state = { activeSuggestionIndex: -1, align: 'left', dropActive: false, }; } componentWillReceiveProps(nextProps) { const { dropActive } = this.state; if ( nextProps.suggestions && nextProps.suggestions.length > 0 && !dropActive && this.inputRef === document.activeElement ) { this.setState({ dropActive: true }); } } componentDidUpdate(prevProps, prevState) { const { dropAlign } = this.props; const { dropActive } = this.state; if (!dropActive && prevState.dropActive) { document.removeEventListener('click', this.onClickBody); if (this.drop) { this.drop.remove(); this.drop = undefined; } } if (dropActive && !prevState.dropActive) { document.addEventListener('click', this.onClickBody); let baseElement; if (this.controlRef) { baseElement = findDOMNode(this.controlRef); } else { baseElement = this.inputRef; } const align = dropAlign || { top: 'bottom', left: 'left', }; this.drop = new Drop(baseElement, this.renderDropContent(), { align, className: s.drop, responsive: false, // so suggestion changes don't re-align context: this.context, }); this.inputRef.focus(); } else if (this.drop) { this.drop.render(this.renderDropContent()); } } componentWillUnmount() { document.removeEventListener('click', this.onClickBody); if (this.drop) { this.drop.remove(); } } onClickBody(event) { // don't close drop when clicking on input if (event.target !== this.inputRef) { this.onRemoveDrop(); } } // eslint-disable-next-line no-unused-vars onChangeInput(event) { const { onDOMChange } = this.props; this.setState({ activeSuggestionIndex: -1, announceChange: true }); if (onDOMChange) { this.fireDOMChange(); } } onClickSuggestion(suggestion) { const { onSelect } = this.props; this.onRemoveDrop(); if (onSelect) { onSelect( { target: this.inputRef || this.controlRef, suggestion, }, true, ); } } onAddDrop() { this.setState({ dropActive: true, activeSuggestionIndex: -1 }); } onRemoveDrop() { this.setState({ dropActive: false }); } onFocusInput(event) { const { onFocus, suggestions } = this.props; if (onFocus) { onFocus(event); } if (suggestions && suggestions.length > 0) { this.onAddDrop(); } } fireDOMChange() { const { onDOMChange } = this.props; let event; try { event = new Event('change', { bubbles: true, cancelable: true, }); } catch (e) { // IE11 workaround. event = document.createEvent('Event'); event.initEvent('change', true, true); } const target = this.inputRef; target.dispatchEvent(event); onDOMChange(event); } renderDropContent() { const { suggestions } = this.props; const { activeSuggestionIndex } = this.state; let suggestionsNode; if (suggestions) { /* eslint-disable react/no-array-index-key */ suggestionsNode = suggestions.map( (suggestion, index) => ( <div key={index} className={cn( s.searchSuggestion, index === activeSuggestionIndex ? s.active : null, )} tabIndex="-1" role="button" onClick={this.onClickSuggestion.bind(this, suggestion)} // eslint-disable-line > {renderLabel(suggestion)} </div> ), this, ); /* eslint-enable react/no-array-index-key */ suggestionsNode = <div key="suggestions">{suggestionsNode}</div>; } const contents = [ // eslint-disable-next-line jsx-a11y/no-static-element-interactions <div key="contents" onClick={onSink}> {suggestionsNode} </div>, ]; return <div className={s.searchDrop}>{contents}</div>; } render() { const { id, placeHolder, value } = this.props; return ( <div className={s.search}> <input ref={ref => (this.inputRef = ref)} type="search" id={id} placeholder={placeHolder} autoComplete="off" value={renderLabel(value)} className={s.searchInput} onChange={this.onChangeInput} onFocus={this.onFocusInput} /> <svg className={s.searchIcon} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" aria-label="search" > <path fill="none" stroke="#000" strokeWidth="2" d="M15,15 L22,22 L15,15 Z M9.5,17 C13.6421356,17 17,13.6421356 17,9.5 C17,5.35786438 13.6421356,2 9.5,2 C5.35786438,2 2,5.35786438 2,9.5 C2,13.6421356 5.35786438,17 9.5,17 Z" /> </svg> </div> ); } } export default withStyles(s)(Search);
modules/History.js
angus-c/react-router
var invariant = require('react/lib/invariant'); var canUseDOM = require('react/lib/ExecutionEnvironment').canUseDOM; var History = { /** * The current number of entries in the history. * * Note: This property is read-only. */ length: 1, /** * Sends the browser back one entry in the history. */ back: function () { invariant( canUseDOM, 'Cannot use History.back without a DOM' ); // Do this first so that History.length will // be accurate in location change listeners. History.length -= 1; window.history.back(); } }; module.exports = History;
jenkins-design-language/src/js/components/material-ui/svg-icons/action/opacity.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionOpacity = (props) => ( <SvgIcon {...props}> <path d="M17.66 8L12 2.35 6.34 8C4.78 9.56 4 11.64 4 13.64s.78 4.11 2.34 5.67 3.61 2.35 5.66 2.35 4.1-.79 5.66-2.35S20 15.64 20 13.64 19.22 9.56 17.66 8zM6 14c.01-2 .62-3.27 1.76-4.4L12 5.27l4.24 4.38C17.38 10.77 17.99 12 18 14H6z"/> </SvgIcon> ); ActionOpacity.displayName = 'ActionOpacity'; ActionOpacity.muiName = 'SvgIcon'; export default ActionOpacity;
ajax/libs/bla/1.6.1/bla.js
maruilian11/cdnjs
/** * @module vow * @author Filatov Dmitry <dfilatov@yandex-team.ru> * @version 0.4.9 * @license * Dual licensed under the MIT and GPL licenses: * * http://www.opensource.org/licenses/mit-license.php * * http://www.gnu.org/licenses/gpl.html */ (function(global) { var undef, nextTick = (function() { var fns = [], enqueueFn = function(fn) { return fns.push(fn) === 1; }, callFns = function() { var fnsToCall = fns, i = 0, len = fns.length; fns = []; while(i < len) { fnsToCall[i++](); } }; if(typeof setImmediate === 'function') { // ie10, nodejs >= 0.10 return function(fn) { enqueueFn(fn) && setImmediate(callFns); }; } if(typeof process === 'object' && process.nextTick) { // nodejs < 0.10 return function(fn) { enqueueFn(fn) && process.nextTick(callFns); }; } if(global.postMessage) { // modern browsers var isPostMessageAsync = true; if(global.attachEvent) { var checkAsync = function() { isPostMessageAsync = false; }; global.attachEvent('onmessage', checkAsync); global.postMessage('__checkAsync', '*'); global.detachEvent('onmessage', checkAsync); } if(isPostMessageAsync) { var msg = '__promise' + +new Date, onMessage = function(e) { if(e.data === msg) { e.stopPropagation && e.stopPropagation(); callFns(); } }; global.addEventListener? global.addEventListener('message', onMessage, true) : global.attachEvent('onmessage', onMessage); return function(fn) { enqueueFn(fn) && global.postMessage(msg, '*'); }; } } var doc = global.document; if('onreadystatechange' in doc.createElement('script')) { // ie6-ie8 var createScript = function() { var script = doc.createElement('script'); script.onreadystatechange = function() { script.parentNode.removeChild(script); script = script.onreadystatechange = null; callFns(); }; (doc.documentElement || doc.body).appendChild(script); }; return function(fn) { enqueueFn(fn) && createScript(); }; } return function(fn) { // old browsers enqueueFn(fn) && setTimeout(callFns, 0); }; })(), throwException = function(e) { nextTick(function() { throw e; }); }, isFunction = function(obj) { return typeof obj === 'function'; }, isObject = function(obj) { return obj !== null && typeof obj === 'object'; }, toStr = Object.prototype.toString, isArray = Array.isArray || function(obj) { return toStr.call(obj) === '[object Array]'; }, getArrayKeys = function(arr) { var res = [], i = 0, len = arr.length; while(i < len) { res.push(i++); } return res; }, getObjectKeys = Object.keys || function(obj) { var res = []; for(var i in obj) { obj.hasOwnProperty(i) && res.push(i); } return res; }, defineCustomErrorType = function(name) { var res = function(message) { this.name = name; this.message = message; }; res.prototype = new Error(); return res; }, wrapOnFulfilled = function(onFulfilled, idx) { return function(val) { onFulfilled.call(this, val, idx); }; }; /** * @class Deferred * @exports vow:Deferred * @description * The `Deferred` class is used to encapsulate newly-created promise object along with functions that resolve, reject or notify it. */ /** * @constructor * @description * You can use `vow.defer()` instead of using this constructor. * * `new vow.Deferred()` gives the same result as `vow.defer()`. */ var Deferred = function() { this._promise = new Promise(); }; Deferred.prototype = /** @lends Deferred.prototype */{ /** * Returns corresponding promise. * * @returns {vow:Promise} */ promise : function() { return this._promise; }, /** * Resolves corresponding promise with given `value`. * * @param {*} value * * @example * ```js * var defer = vow.defer(), * promise = defer.promise(); * * promise.then(function(value) { * // value is "'success'" here * }); * * defer.resolve('success'); * ``` */ resolve : function(value) { this._promise.isResolved() || this._promise._resolve(value); }, /** * Rejects corresponding promise with given `reason`. * * @param {*} reason * * @example * ```js * var defer = vow.defer(), * promise = defer.promise(); * * promise.fail(function(reason) { * // reason is "'something is wrong'" here * }); * * defer.reject('something is wrong'); * ``` */ reject : function(reason) { if(this._promise.isResolved()) { return; } if(vow.isPromise(reason)) { reason = reason.then(function(val) { var defer = vow.defer(); defer.reject(val); return defer.promise(); }); this._promise._resolve(reason); } else { this._promise._reject(reason); } }, /** * Notifies corresponding promise with given `value`. * * @param {*} value * * @example * ```js * var defer = vow.defer(), * promise = defer.promise(); * * promise.progress(function(value) { * // value is "'20%'", "'40%'" here * }); * * defer.notify('20%'); * defer.notify('40%'); * ``` */ notify : function(value) { this._promise.isResolved() || this._promise._notify(value); } }; var PROMISE_STATUS = { PENDING : 0, RESOLVED : 1, FULFILLED : 2, REJECTED : 3 }; /** * @class Promise * @exports vow:Promise * @description * The `Promise` class is used when you want to give to the caller something to subscribe to, * but not the ability to resolve or reject the deferred. */ /** * @constructor * @param {Function} resolver See https://github.com/domenic/promises-unwrapping/blob/master/README.md#the-promise-constructor for details. * @description * You should use this constructor directly only if you are going to use `vow` as DOM Promises implementation. * In other case you should use `vow.defer()` and `defer.promise()` methods. * @example * ```js * function fetchJSON(url) { * return new vow.Promise(function(resolve, reject, notify) { * var xhr = new XMLHttpRequest(); * xhr.open('GET', url); * xhr.responseType = 'json'; * xhr.send(); * xhr.onload = function() { * if(xhr.response) { * resolve(xhr.response); * } * else { * reject(new TypeError()); * } * }; * }); * } * ``` */ var Promise = function(resolver) { this._value = undef; this._status = PROMISE_STATUS.PENDING; this._fulfilledCallbacks = []; this._rejectedCallbacks = []; this._progressCallbacks = []; if(resolver) { // NOTE: see https://github.com/domenic/promises-unwrapping/blob/master/README.md var _this = this, resolverFnLen = resolver.length; resolver( function(val) { _this.isResolved() || _this._resolve(val); }, resolverFnLen > 1? function(reason) { _this.isResolved() || _this._reject(reason); } : undef, resolverFnLen > 2? function(val) { _this.isResolved() || _this._notify(val); } : undef); } }; Promise.prototype = /** @lends Promise.prototype */ { /** * Returns value of fulfilled promise or reason in case of rejection. * * @returns {*} */ valueOf : function() { return this._value; }, /** * Returns `true` if promise is resolved. * * @returns {Boolean} */ isResolved : function() { return this._status !== PROMISE_STATUS.PENDING; }, /** * Returns `true` if promise is fulfilled. * * @returns {Boolean} */ isFulfilled : function() { return this._status === PROMISE_STATUS.FULFILLED; }, /** * Returns `true` if promise is rejected. * * @returns {Boolean} */ isRejected : function() { return this._status === PROMISE_STATUS.REJECTED; }, /** * Adds reactions to promise. * * @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled * @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected * @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified * @param {Object} [ctx] Context of callbacks execution * @returns {vow:Promise} A new promise, see https://github.com/promises-aplus/promises-spec for details */ then : function(onFulfilled, onRejected, onProgress, ctx) { var defer = new Deferred(); this._addCallbacks(defer, onFulfilled, onRejected, onProgress, ctx); return defer.promise(); }, /** * Adds rejection reaction only. It is shortcut for `promise.then(undefined, onRejected)`. * * @param {Function} onRejected Callback to be called with the value after promise has been rejected * @param {Object} [ctx] Context of callback execution * @returns {vow:Promise} */ 'catch' : function(onRejected, ctx) { return this.then(undef, onRejected, ctx); }, /** * Adds rejection reaction only. It is shortcut for `promise.then(null, onRejected)`. It's alias for `catch`. * * @param {Function} onRejected Callback to be called with the value after promise has been rejected * @param {Object} [ctx] Context of callback execution * @returns {vow:Promise} */ fail : function(onRejected, ctx) { return this.then(undef, onRejected, ctx); }, /** * Adds resolving reaction (to fulfillment and rejection both). * * @param {Function} onResolved Callback that to be called with the value after promise has been resolved * @param {Object} [ctx] Context of callback execution * @returns {vow:Promise} */ always : function(onResolved, ctx) { var _this = this, cb = function() { return onResolved.call(this, _this); }; return this.then(cb, cb, ctx); }, /** * Adds progress reaction. * * @param {Function} onProgress Callback to be called with the value when promise has been notified * @param {Object} [ctx] Context of callback execution * @returns {vow:Promise} */ progress : function(onProgress, ctx) { return this.then(undef, undef, onProgress, ctx); }, /** * Like `promise.then`, but "spreads" the array into a variadic value handler. * It is useful with `vow.all` and `vow.allResolved` methods. * * @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled * @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected * @param {Object} [ctx] Context of callbacks execution * @returns {vow:Promise} * * @example * ```js * var defer1 = vow.defer(), * defer2 = vow.defer(); * * vow.all([defer1.promise(), defer2.promise()]).spread(function(arg1, arg2) { * // arg1 is "1", arg2 is "'two'" here * }); * * defer1.resolve(1); * defer2.resolve('two'); * ``` */ spread : function(onFulfilled, onRejected, ctx) { return this.then( function(val) { return onFulfilled.apply(this, val); }, onRejected, ctx); }, /** * Like `then`, but terminates a chain of promises. * If the promise has been rejected, throws it as an exception in a future turn of the event loop. * * @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled * @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected * @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified * @param {Object} [ctx] Context of callbacks execution * * @example * ```js * var defer = vow.defer(); * defer.reject(Error('Internal error')); * defer.promise().done(); // exception to be thrown * ``` */ done : function(onFulfilled, onRejected, onProgress, ctx) { this .then(onFulfilled, onRejected, onProgress, ctx) .fail(throwException); }, /** * Returns a new promise that will be fulfilled in `delay` milliseconds if the promise is fulfilled, * or immediately rejected if promise is rejected. * * @param {Number} delay * @returns {vow:Promise} */ delay : function(delay) { var timer, promise = this.then(function(val) { var defer = new Deferred(); timer = setTimeout( function() { defer.resolve(val); }, delay); return defer.promise(); }); promise.always(function() { clearTimeout(timer); }); return promise; }, /** * Returns a new promise that will be rejected in `timeout` milliseconds * if the promise is not resolved beforehand. * * @param {Number} timeout * @returns {vow:Promise} * * @example * ```js * var defer = vow.defer(), * promiseWithTimeout1 = defer.promise().timeout(50), * promiseWithTimeout2 = defer.promise().timeout(200); * * setTimeout( * function() { * defer.resolve('ok'); * }, * 100); * * promiseWithTimeout1.fail(function(reason) { * // promiseWithTimeout to be rejected in 50ms * }); * * promiseWithTimeout2.then(function(value) { * // promiseWithTimeout to be fulfilled with "'ok'" value * }); * ``` */ timeout : function(timeout) { var defer = new Deferred(), timer = setTimeout( function() { defer.reject(new vow.TimedOutError('timed out')); }, timeout); this.then( function(val) { defer.resolve(val); }, function(reason) { defer.reject(reason); }); defer.promise().always(function() { clearTimeout(timer); }); return defer.promise(); }, _vow : true, _resolve : function(val) { if(this._status > PROMISE_STATUS.RESOLVED) { return; } if(val === this) { this._reject(TypeError('Can\'t resolve promise with itself')); return; } this._status = PROMISE_STATUS.RESOLVED; if(val && !!val._vow) { // shortpath for vow.Promise val.isFulfilled()? this._fulfill(val.valueOf()) : val.isRejected()? this._reject(val.valueOf()) : val.then( this._fulfill, this._reject, this._notify, this); return; } if(isObject(val) || isFunction(val)) { var then; try { then = val.then; } catch(e) { this._reject(e); return; } if(isFunction(then)) { var _this = this, isResolved = false; try { then.call( val, function(val) { if(isResolved) { return; } isResolved = true; _this._resolve(val); }, function(err) { if(isResolved) { return; } isResolved = true; _this._reject(err); }, function(val) { _this._notify(val); }); } catch(e) { isResolved || this._reject(e); } return; } } this._fulfill(val); }, _fulfill : function(val) { if(this._status > PROMISE_STATUS.RESOLVED) { return; } this._status = PROMISE_STATUS.FULFILLED; this._value = val; this._callCallbacks(this._fulfilledCallbacks, val); this._fulfilledCallbacks = this._rejectedCallbacks = this._progressCallbacks = undef; }, _reject : function(reason) { if(this._status > PROMISE_STATUS.RESOLVED) { return; } this._status = PROMISE_STATUS.REJECTED; this._value = reason; this._callCallbacks(this._rejectedCallbacks, reason); this._fulfilledCallbacks = this._rejectedCallbacks = this._progressCallbacks = undef; }, _notify : function(val) { this._callCallbacks(this._progressCallbacks, val); }, _addCallbacks : function(defer, onFulfilled, onRejected, onProgress, ctx) { if(onRejected && !isFunction(onRejected)) { ctx = onRejected; onRejected = undef; } else if(onProgress && !isFunction(onProgress)) { ctx = onProgress; onProgress = undef; } var cb; if(!this.isRejected()) { cb = { defer : defer, fn : isFunction(onFulfilled)? onFulfilled : undef, ctx : ctx }; this.isFulfilled()? this._callCallbacks([cb], this._value) : this._fulfilledCallbacks.push(cb); } if(!this.isFulfilled()) { cb = { defer : defer, fn : onRejected, ctx : ctx }; this.isRejected()? this._callCallbacks([cb], this._value) : this._rejectedCallbacks.push(cb); } if(this._status <= PROMISE_STATUS.RESOLVED) { this._progressCallbacks.push({ defer : defer, fn : onProgress, ctx : ctx }); } }, _callCallbacks : function(callbacks, arg) { var len = callbacks.length; if(!len) { return; } var isResolved = this.isResolved(), isFulfilled = this.isFulfilled(); nextTick(function() { var i = 0, cb, defer, fn; while(i < len) { cb = callbacks[i++]; defer = cb.defer; fn = cb.fn; if(fn) { var ctx = cb.ctx, res; try { res = ctx? fn.call(ctx, arg) : fn(arg); } catch(e) { defer.reject(e); continue; } isResolved? defer.resolve(res) : defer.notify(res); } else { isResolved? isFulfilled? defer.resolve(arg) : defer.reject(arg) : defer.notify(arg); } } }); } }; /** @lends Promise */ var staticMethods = { /** * Coerces given `value` to a promise, or returns the `value` if it's already a promise. * * @param {*} value * @returns {vow:Promise} */ cast : function(value) { return vow.cast(value); }, /** * Returns a promise to be fulfilled only after all the items in `iterable` are fulfilled, * or to be rejected when any of the `iterable` is rejected. * * @param {Array|Object} iterable * @returns {vow:Promise} */ all : function(iterable) { return vow.all(iterable); }, /** * Returns a promise to be fulfilled only when any of the items in `iterable` are fulfilled, * or to be rejected when the first item is rejected. * * @param {Array} iterable * @returns {vow:Promise} */ race : function(iterable) { return vow.anyResolved(iterable); }, /** * Returns a promise that has already been resolved with the given `value`. * If `value` is a promise, returned promise will be adopted with the state of given promise. * * @param {*} value * @returns {vow:Promise} */ resolve : function(value) { return vow.resolve(value); }, /** * Returns a promise that has already been rejected with the given `reason`. * * @param {*} reason * @returns {vow:Promise} */ reject : function(reason) { return vow.reject(reason); } }; for(var prop in staticMethods) { staticMethods.hasOwnProperty(prop) && (Promise[prop] = staticMethods[prop]); } var vow = /** @exports vow */ { Deferred : Deferred, Promise : Promise, /** * Creates a new deferred. This method is a factory method for `vow:Deferred` class. * It's equivalent to `new vow.Deferred()`. * * @returns {vow:Deferred} */ defer : function() { return new Deferred(); }, /** * Static equivalent to `promise.then`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled * @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected * @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified * @param {Object} [ctx] Context of callbacks execution * @returns {vow:Promise} */ when : function(value, onFulfilled, onRejected, onProgress, ctx) { return vow.cast(value).then(onFulfilled, onRejected, onProgress, ctx); }, /** * Static equivalent to `promise.fail`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Function} onRejected Callback that will to be invoked with the reason after promise has been rejected * @param {Object} [ctx] Context of callback execution * @returns {vow:Promise} */ fail : function(value, onRejected, ctx) { return vow.when(value, undef, onRejected, ctx); }, /** * Static equivalent to `promise.always`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Function} onResolved Callback that will to be invoked with the reason after promise has been resolved * @param {Object} [ctx] Context of callback execution * @returns {vow:Promise} */ always : function(value, onResolved, ctx) { return vow.when(value).always(onResolved, ctx); }, /** * Static equivalent to `promise.progress`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Function} onProgress Callback that will to be invoked with the reason after promise has been notified * @param {Object} [ctx] Context of callback execution * @returns {vow:Promise} */ progress : function(value, onProgress, ctx) { return vow.when(value).progress(onProgress, ctx); }, /** * Static equivalent to `promise.spread`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled * @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected * @param {Object} [ctx] Context of callbacks execution * @returns {vow:Promise} */ spread : function(value, onFulfilled, onRejected, ctx) { return vow.when(value).spread(onFulfilled, onRejected, ctx); }, /** * Static equivalent to `promise.done`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled * @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected * @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified * @param {Object} [ctx] Context of callbacks execution */ done : function(value, onFulfilled, onRejected, onProgress, ctx) { vow.when(value).done(onFulfilled, onRejected, onProgress, ctx); }, /** * Checks whether the given `value` is a promise-like object * * @param {*} value * @returns {Boolean} * * @example * ```js * vow.isPromise('something'); // returns false * vow.isPromise(vow.defer().promise()); // returns true * vow.isPromise({ then : function() { }); // returns true * ``` */ isPromise : function(value) { return isObject(value) && isFunction(value.then); }, /** * Coerces given `value` to a promise, or returns the `value` if it's already a promise. * * @param {*} value * @returns {vow:Promise} */ cast : function(value) { return value && !!value._vow? value : vow.resolve(value); }, /** * Static equivalent to `promise.valueOf`. * If given `value` is not an instance of `vow.Promise`, then `value` is equivalent to fulfilled promise. * * @param {*} value * @returns {*} */ valueOf : function(value) { return value && isFunction(value.valueOf)? value.valueOf() : value; }, /** * Static equivalent to `promise.isFulfilled`. * If given `value` is not an instance of `vow.Promise`, then `value` is equivalent to fulfilled promise. * * @param {*} value * @returns {Boolean} */ isFulfilled : function(value) { return value && isFunction(value.isFulfilled)? value.isFulfilled() : true; }, /** * Static equivalent to `promise.isRejected`. * If given `value` is not an instance of `vow.Promise`, then `value` is equivalent to fulfilled promise. * * @param {*} value * @returns {Boolean} */ isRejected : function(value) { return value && isFunction(value.isRejected)? value.isRejected() : false; }, /** * Static equivalent to `promise.isResolved`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @returns {Boolean} */ isResolved : function(value) { return value && isFunction(value.isResolved)? value.isResolved() : true; }, /** * Returns a promise that has already been resolved with the given `value`. * If `value` is a promise, returned promise will be adopted with the state of given promise. * * @param {*} value * @returns {vow:Promise} */ resolve : function(value) { var res = vow.defer(); res.resolve(value); return res.promise(); }, /** * Returns a promise that has already been fulfilled with the given `value`. * If `value` is a promise, returned promise will be fulfilled with fulfill/rejection value of given promise. * * @param {*} value * @returns {vow:Promise} */ fulfill : function(value) { var defer = vow.defer(), promise = defer.promise(); defer.resolve(value); return promise.isFulfilled()? promise : promise.then(null, function(reason) { return reason; }); }, /** * Returns a promise that has already been rejected with the given `reason`. * If `reason` is a promise, returned promise will be rejected with fulfill/rejection value of given promise. * * @param {*} reason * @returns {vow:Promise} */ reject : function(reason) { var defer = vow.defer(); defer.reject(reason); return defer.promise(); }, /** * Invokes a given function `fn` with arguments `args` * * @param {Function} fn * @param {...*} [args] * @returns {vow:Promise} * * @example * ```js * var promise1 = vow.invoke(function(value) { * return value; * }, 'ok'), * promise2 = vow.invoke(function() { * throw Error(); * }); * * promise1.isFulfilled(); // true * promise1.valueOf(); // 'ok' * promise2.isRejected(); // true * promise2.valueOf(); // instance of Error * ``` */ invoke : function(fn, args) { var len = Math.max(arguments.length - 1, 0), callArgs; if(len) { // optimization for V8 callArgs = Array(len); var i = 0; while(i < len) { callArgs[i++] = arguments[i]; } } try { return vow.resolve(callArgs? fn.apply(global, callArgs) : fn.call(global)); } catch(e) { return vow.reject(e); } }, /** * Returns a promise to be fulfilled only after all the items in `iterable` are fulfilled, * or to be rejected when any of the `iterable` is rejected. * * @param {Array|Object} iterable * @returns {vow:Promise} * * @example * with array: * ```js * var defer1 = vow.defer(), * defer2 = vow.defer(); * * vow.all([defer1.promise(), defer2.promise(), 3]) * .then(function(value) { * // value is "[1, 2, 3]" here * }); * * defer1.resolve(1); * defer2.resolve(2); * ``` * * @example * with object: * ```js * var defer1 = vow.defer(), * defer2 = vow.defer(); * * vow.all({ p1 : defer1.promise(), p2 : defer2.promise(), p3 : 3 }) * .then(function(value) { * // value is "{ p1 : 1, p2 : 2, p3 : 3 }" here * }); * * defer1.resolve(1); * defer2.resolve(2); * ``` */ all : function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), len = keys.length, res = isPromisesArray? [] : {}; if(!len) { defer.resolve(res); return defer.promise(); } var i = len; vow._forEach( iterable, function(value, idx) { res[keys[idx]] = value; if(!--i) { defer.resolve(res); } }, defer.reject, defer.notify, defer, keys); return defer.promise(); }, /** * Returns a promise to be fulfilled only after all the items in `iterable` are resolved. * * @param {Array|Object} iterable * @returns {vow:Promise} * * @example * ```js * var defer1 = vow.defer(), * defer2 = vow.defer(); * * vow.allResolved([defer1.promise(), defer2.promise()]).spread(function(promise1, promise2) { * promise1.isRejected(); // returns true * promise1.valueOf(); // returns "'error'" * promise2.isFulfilled(); // returns true * promise2.valueOf(); // returns "'ok'" * }); * * defer1.reject('error'); * defer2.resolve('ok'); * ``` */ allResolved : function(iterable) { var defer = new Deferred(), isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), i = keys.length, res = isPromisesArray? [] : {}; if(!i) { defer.resolve(res); return defer.promise(); } var onResolved = function() { --i || defer.resolve(iterable); }; vow._forEach( iterable, onResolved, onResolved, defer.notify, defer, keys); return defer.promise(); }, allPatiently : function(iterable) { return vow.allResolved(iterable).then(function() { var isPromisesArray = isArray(iterable), keys = isPromisesArray? getArrayKeys(iterable) : getObjectKeys(iterable), rejectedPromises, fulfilledPromises, len = keys.length, i = 0, key, promise; if(!len) { return isPromisesArray? [] : {}; } while(i < len) { key = keys[i++]; promise = iterable[key]; if(vow.isRejected(promise)) { rejectedPromises || (rejectedPromises = isPromisesArray? [] : {}); isPromisesArray? rejectedPromises.push(promise.valueOf()) : rejectedPromises[key] = promise.valueOf(); } else if(!rejectedPromises) { (fulfilledPromises || (fulfilledPromises = isPromisesArray? [] : {}))[key] = vow.valueOf(promise); } } if(rejectedPromises) { throw rejectedPromises; } return fulfilledPromises; }); }, /** * Returns a promise to be fulfilled only when any of the items in `iterable` is fulfilled, * or to be rejected when all the items are rejected (with the reason of the first rejected item). * * @param {Array} iterable * @returns {vow:Promise} */ any : function(iterable) { var defer = new Deferred(), len = iterable.length; if(!len) { defer.reject(Error()); return defer.promise(); } var i = 0, reason; vow._forEach( iterable, defer.resolve, function(e) { i || (reason = e); ++i === len && defer.reject(reason); }, defer.notify, defer); return defer.promise(); }, /** * Returns a promise to be fulfilled only when any of the items in `iterable` is fulfilled, * or to be rejected when the first item is rejected. * * @param {Array} iterable * @returns {vow:Promise} */ anyResolved : function(iterable) { var defer = new Deferred(), len = iterable.length; if(!len) { defer.reject(Error()); return defer.promise(); } vow._forEach( iterable, defer.resolve, defer.reject, defer.notify, defer); return defer.promise(); }, /** * Static equivalent to `promise.delay`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Number} delay * @returns {vow:Promise} */ delay : function(value, delay) { return vow.resolve(value).delay(delay); }, /** * Static equivalent to `promise.timeout`. * If given `value` is not a promise, then `value` is equivalent to fulfilled promise. * * @param {*} value * @param {Number} timeout * @returns {vow:Promise} */ timeout : function(value, timeout) { return vow.resolve(value).timeout(timeout); }, _forEach : function(promises, onFulfilled, onRejected, onProgress, ctx, keys) { var len = keys? keys.length : promises.length, i = 0; while(i < len) { vow.when( promises[keys? keys[i] : i], wrapOnFulfilled(onFulfilled, i), onRejected, onProgress, ctx); ++i; } }, TimedOutError : defineCustomErrorType('TimedOut') }; var defineAsGlobal = true; if(typeof module === 'object' && typeof module.exports === 'object') { module.exports = vow; defineAsGlobal = false; } if(typeof modules === 'object' && isFunction(modules.define)) { modules.define('vow', function(provide) { provide(vow); }); defineAsGlobal = false; } if(typeof define === 'function') { define(function(require, exports, module) { module.exports = vow; }); defineAsGlobal = false; } defineAsGlobal && (global.vow = vow); })(this); (function (global) { /** * API error. * * @param {String} type Error type. * @param {String} message Human-readable description of the error. */ function ApiError(type, message) { this.name = 'ApiError'; this.type = type; this.message = message; if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } } ApiError.prototype = Object.create(Error.prototype, { constructor: { value: ApiError } }); /** * Invalid or missed parameter. */ ApiError.BAD_REQUEST = 'BAD_REQUEST'; /** * Unspecified error or server logic error. */ ApiError.INTERNAL_ERROR = 'INTERNAL_ERROR'; /** * API middleware wasn't found. */ ApiError.NOT_FOUND = 'NOT_FOUND'; var defineAsGlobal = true; /** * @see https://github.com/ymaps/modules */ if (typeof global.modules === 'object') { global.modules.define('bla-error', function (provide) { provide(ApiError); }); defineAsGlobal = false; } /** * @see requirejs.org */ if (typeof global.define === 'function') { global.define('bla-error', function () { return ApiError; }); defineAsGlobal = false; } /** * Common JS. * @see http://wiki.commonjs.org/wiki/Modules/1.1.1 */ if (typeof require === 'function' && typeof module === 'object' && typeof module.exports === 'object') { module.exports = ApiError; defineAsGlobal = false; } if (defineAsGlobal) { global.bla = global.bla || {}; global.bla.ApiError = ApiError; } }(window)); (function (global) { /** * Returns API class based on dependencies. * * @param {Object} vow * @param {Object} ApiError * @returns {Function} */ function createApiClass(vow, ApiError) { /** * Makes an ajax request. * * @param {String} url A string containing the URL to which the request is sent. * @param {String} data Data to be sent to the server. * @returns {vow.Promise} */ function sendAjaxRequest(url, data) { var xhr = new XMLHttpRequest(); var d = vow.defer(); xhr.onreadystatechange = function () { if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { d.resolve(JSON.parse(xhr.responseText)); } else { d.reject(xhr); } } }; xhr.open('POST', url, true); xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01'); xhr.setRequestHeader('Content-type', 'application/json'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(data); return d.promise(); } /** * Api provider. * * @param {String} basePath Url path to the middleware root. * @param {Object} [options] Extra options. * @param {Boolean} [options.enableBatching=true] Enables batching. */ function Api(basePath, options) { this._basePath = basePath; options = options || {}; this._options = { enableBatching: options.hasOwnProperty('enableBatching') ? options.enableBatching : true }; this._batch = []; this._deferreds = {}; } Api.prototype = { constructor: Api, /** * Executes api by path with specified parameters. * * @param {String} methodName Method name. * @param {Object} params Data should be sent to the method. * @param {Object} [execOptions] Exec-specific options. * @param {Boolean} [execOptions.enableBatching=true] Should the current call of the method be batched. * method be batched. * @returns {vow.Promise} */ exec: function (methodName, params, execOptions) { execOptions = execOptions || {}; var enableBatching = execOptions.hasOwnProperty('enableBatching') ? execOptions.enableBatching : this._options.enableBatching; return enableBatching ? this._execWithBatching(methodName, params) : this._execWithoutBatching(methodName, params); }, /** * Executes method immediately. * * @param {String} methodName Method name. * @param {Object} params Data should be sent to the method. * @returns {vow.Promise} */ _execWithoutBatching: function (methodName, params) { var defer = vow.defer(); var url = this._basePath + methodName; var data = JSON.stringify(params); sendAjaxRequest(url, data).then( this._resolvePromise.bind(this, defer), this._rejectPromise.bind(this, defer) ); return defer.promise(); }, /** * Executes method with a little delay, adding it to batch. * * @param {String} methodName Method name. * @param {Object} params Data should be sent to the method. * @returns {vow.Promise} */ _execWithBatching: function (methodName, params) { var requestId = this._getRequestId(methodName, params); var promise = this._getRequestPromise(requestId); if (!promise) { this._addToBatch(methodName, params); promise = this._createPromise(requestId); this._run(); } return promise; }, /** * Generates an ID for a method request. * * @param {String} methodName * @param {Object} params * @returns {String} */ _getRequestId: function (methodName, params) { var stringifiedParams = JSON.stringify(params) || ''; return methodName + stringifiedParams; }, /** * Gets the promise object for given request ID. * * @param {String} requestId Request ID for which promise is retrieved. * @returns {vow.Promise|undefined} */ _getRequestPromise: function (requestId) { var defer = this._deferreds[requestId]; return defer && defer.promise(); }, /** * Appends data to the batch array. * * @param {String} methodName * @param {Object} params */ _addToBatch: function (methodName, params) { this._batch.push({ method: methodName, params: params }); }, /** * Creates new deferred promise. * * @param {String} requestId Request ID for which promise is generated. * @returns {vow.Promise} */ _createPromise: function (requestId) { var defer = vow.defer(); this._deferreds[requestId] = defer; return defer.promise(); }, /** * Initializes async batch request. */ _run: function () { // The collecting requests for the batch will start when a first request is received. // That's why the batch length is checked there. if (this._batch.length === 1) { vow.resolve().then(this._sendBatchRequest, this); } }, /** * Performs batch request. */ _sendBatchRequest: function () { var url = this._basePath + 'batch'; var data = JSON.stringify({methods: this._batch}); sendAjaxRequest(url, data).then( this._resolvePromises.bind(this, this._batch), this._rejectPromises.bind(this, this._batch) ); this._batch = []; }, /** * Resolve deferred promise. * * @param {vow.Deferred} defer * @param {Object} response Server response. */ _resolvePromise: function (defer, response) { var error = response.error; if (error) { defer.reject(new ApiError(error.type, error.message)); } else { defer.resolve(response.data); } }, /** * Resolves deferred promises. * * @param {Object[]} batch Batch request data. * @param {Object} response Server response. */ _resolvePromises: function (batch, response) { var data = response.data; for (var i = 0, requestId; i < batch.length; i++) { requestId = this._getRequestId(batch[i].method, batch[i].params); this._resolvePromise(this._deferreds[requestId], data[i]); delete this._deferreds[requestId]; } }, /** * Rejects deferred promise. * * @param {vow.Deferred} defer * @param {XMLHttpRequest} xhr */ _rejectPromise: function (defer, xhr) { var errorMessage = xhr.responseText || xhr.message || xhr.statusText; defer.reject(new ApiError(xhr.status, errorMessage)); }, /** * Rejects deferred promises. * * @param {Object[]} batch Batch request data. * @param {XMLHttpRequest} xhr */ _rejectPromises: function (batch, xhr) { for (var i = 0, requestId; i < batch.length; i++) { requestId = this._getRequestId(batch[i].method, batch[i].params); this._rejectPromise(this._deferreds[requestId], xhr); delete this._deferreds[requestId]; } } }; return Api; } var defineAsGlobal = true; /** * @see https://github.com/ymaps/modules */ if (typeof global.modules === 'object') { global.modules.define('bla', ['vow', 'bla-error'], function (provide, vow, ApiError) { var Api = createApiClass(vow, ApiError); provide(Api); }); defineAsGlobal = false; } /** * @see requirejs.org */ if (typeof global.define === 'function') { global.define('bla', ['bla-error', 'vow'], function (ApiError, vow) { return createApiClass(vow, ApiError); }); defineAsGlobal = false; } /** * Common JS. * @see http://wiki.commonjs.org/wiki/Modules/1.1.1 */ if (typeof require === 'function' && typeof module === 'object' && typeof module.exports === 'object') { var vow = require('vow'); var ApiError = require('../bla-error/bla-error.js'); module.exports = createApiClass(vow, ApiError); defineAsGlobal = false; } if (defineAsGlobal) { global.bla = global.bla || {}; global.bla.Api = createApiClass(global.vow, global.bla.ApiError); } }(window));
src/svg-icons/hardware/router.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareRouter = (props) => ( <SvgIcon {...props}> <path d="M20.2 5.9l.8-.8C19.6 3.7 17.8 3 16 3s-3.6.7-5 2.1l.8.8C13 4.8 14.5 4.2 16 4.2s3 .6 4.2 1.7zm-.9.8c-.9-.9-2.1-1.4-3.3-1.4s-2.4.5-3.3 1.4l.8.8c.7-.7 1.6-1 2.5-1 .9 0 1.8.3 2.5 1l.8-.8zM19 13h-2V9h-2v4H5c-1.1 0-2 .9-2 2v4c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-4c0-1.1-.9-2-2-2zM8 18H6v-2h2v2zm3.5 0h-2v-2h2v2zm3.5 0h-2v-2h2v2z"/> </SvgIcon> ); HardwareRouter = pure(HardwareRouter); HardwareRouter.displayName = 'HardwareRouter'; export default HardwareRouter;
ajax/libs/react-instantsearch/5.0.3/Core.js
joeyparrish/cdnjs
/*! ReactInstantSearch 5.0.3 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.ReactInstantSearch = global.ReactInstantSearch || {}, global.ReactInstantSearch.Core = {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {} if (typeof global$1.setTimeout === 'function') { } if (typeof global$1.clearTimeout === 'function') { } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function(){ return (new Date()).getTime() }; /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } var _listCacheClear = listCacheClear; /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } var eq_1 = eq; /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq_1(array[length][0], key)) { return length; } } return -1; } var _assocIndexOf = assocIndexOf; /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } var _listCacheDelete = listCacheDelete; /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = _assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } var _listCacheGet = listCacheGet; /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return _assocIndexOf(this.__data__, key) > -1; } var _listCacheHas = listCacheHas; /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = _assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } var _listCacheSet = listCacheSet; /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = _listCacheClear; ListCache.prototype['delete'] = _listCacheDelete; ListCache.prototype.get = _listCacheGet; ListCache.prototype.has = _listCacheHas; ListCache.prototype.set = _listCacheSet; var _ListCache = ListCache; /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new _ListCache; this.size = 0; } var _stackClear = stackClear; /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } var _stackDelete = stackDelete; /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } var _stackGet = stackGet; /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } var _stackHas = stackHas; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; var _freeGlobal = freeGlobal; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = _freeGlobal || freeSelf || Function('return this')(); var _root = root; /** Built-in value references. */ var Symbol$1 = _root.Symbol; var _Symbol = Symbol$1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } var _getRawTag = getRawTag; /** Used for built-in method references. */ var objectProto$1 = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString$1.call(value); } var _objectToString = objectToString; /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag$1 && symToStringTag$1 in Object(value)) ? _getRawTag(value) : _objectToString(value); } var _baseGetTag = baseGetTag; /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } var isObject_1 = isObject; /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject_1(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = _baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } var isFunction_1 = isFunction; /** Used to detect overreaching core-js shims. */ var coreJsData = _root['__core-js_shared__']; var _coreJsData = coreJsData; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } var _isMasked = isMasked; /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } var _toSource = toSource; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto$1 = Function.prototype, objectProto$2 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$1 = funcProto$1.toString; /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$2.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject_1(value) || _isMasked(value)) { return false; } var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; return pattern.test(_toSource(value)); } var _baseIsNative = baseIsNative; /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } var _getValue = getValue; /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = _getValue(object, key); return _baseIsNative(value) ? value : undefined; } var _getNative = getNative; /* Built-in method references that are verified to be native. */ var Map = _getNative(_root, 'Map'); var _Map = Map; /* Built-in method references that are verified to be native. */ var nativeCreate = _getNative(Object, 'create'); var _nativeCreate = nativeCreate; /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; this.size = 0; } var _hashClear = hashClear; /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } var _hashDelete = hashDelete; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto$3 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$3.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (_nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty$2.call(data, key) ? data[key] : undefined; } var _hashGet = hashGet; /** Used for built-in method references. */ var objectProto$4 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$3.call(data, key); } var _hashHas = hashHas; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; return this; } var _hashSet = hashSet; /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = _hashClear; Hash.prototype['delete'] = _hashDelete; Hash.prototype.get = _hashGet; Hash.prototype.has = _hashHas; Hash.prototype.set = _hashSet; var _Hash = Hash; /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new _Hash, 'map': new (_Map || _ListCache), 'string': new _Hash }; } var _mapCacheClear = mapCacheClear; /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } var _isKeyable = isKeyable; /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } var _getMapData = getMapData; /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = _getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } var _mapCacheDelete = mapCacheDelete; /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return _getMapData(this, key).get(key); } var _mapCacheGet = mapCacheGet; /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return _getMapData(this, key).has(key); } var _mapCacheHas = mapCacheHas; /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = _getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } var _mapCacheSet = mapCacheSet; /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = _mapCacheClear; MapCache.prototype['delete'] = _mapCacheDelete; MapCache.prototype.get = _mapCacheGet; MapCache.prototype.has = _mapCacheHas; MapCache.prototype.set = _mapCacheSet; var _MapCache = MapCache; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof _ListCache) { var pairs = data.__data__; if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new _MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } var _stackSet = stackSet; /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new _ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = _stackClear; Stack.prototype['delete'] = _stackDelete; Stack.prototype.get = _stackGet; Stack.prototype.has = _stackHas; Stack.prototype.set = _stackSet; var _Stack = Stack; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED$2); return this; } var _setCacheAdd = setCacheAdd; /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } var _setCacheHas = setCacheHas; /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new _MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; SetCache.prototype.has = _setCacheHas; var _SetCache = SetCache; /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } var _arraySome = arraySome; /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } var _cacheHas = cacheHas; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!_arraySome(other, function(othValue, othIndex) { if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } var _equalArrays = equalArrays; /** Built-in value references. */ var Uint8Array = _root.Uint8Array; var _Uint8Array = Uint8Array; /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } var _mapToArray = mapToArray; /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } var _setToArray = setToArray; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = _Symbol ? _Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq_1(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = _mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; convert || (convert = _setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } var _equalByTag = equalByTag; /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } var _arrayPush = arrayPush; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; var isArray_1 = isArray; /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); } var _baseGetAllKeys = baseGetAllKeys; /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } var _arrayFilter = arrayFilter; /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } var stubArray_1 = stubArray; /** Used for built-in method references. */ var objectProto$5 = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { if (object == null) { return []; } object = Object(object); return _arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; var _getSymbols = getSymbols; /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } var _baseTimes = baseTimes; /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } var isObjectLike_1 = isObjectLike; /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike_1(value) && _baseGetTag(value) == argsTag; } var _baseIsArguments = baseIsArguments; /** Used for built-in method references. */ var objectProto$6 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$4 = objectProto$6.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { return isObjectLike_1(value) && hasOwnProperty$4.call(value, 'callee') && !propertyIsEnumerable$1.call(value, 'callee'); }; var isArguments_1 = isArguments; /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } var stubFalse_1 = stubFalse; var isBuffer_1 = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? _root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse_1; module.exports = isBuffer; }); /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } var _isIndex = isIndex; /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; } var isLength_1 = isLength; /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]', arrayTag = '[object Array]', boolTag$1 = '[object Boolean]', dateTag$1 = '[object Date]', errorTag$1 = '[object Error]', funcTag$1 = '[object Function]', mapTag$1 = '[object Map]', numberTag$1 = '[object Number]', objectTag = '[object Object]', regexpTag$1 = '[object RegExp]', setTag$1 = '[object Set]', stringTag$1 = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag$1 = '[object ArrayBuffer]', dataViewTag$1 = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; } var _baseIsTypedArray = baseIsTypedArray; /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } var _baseUnary = baseUnary; var _nodeUtil = createCommonjsModule(function (module, exports) { /** Detect free variable `exports`. */ var freeExports = 'object' == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && _freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; }); /* Node.js helper references. */ var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; var isTypedArray_1 = isTypedArray; /** Used for built-in method references. */ var objectProto$7 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$5 = objectProto$7.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray_1(value), isArg = !isArr && isArguments_1(value), isBuff = !isArr && !isArg && isBuffer_1(value), isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? _baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty$5.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. _isIndex(key, length) ))) { result.push(key); } } return result; } var _arrayLikeKeys = arrayLikeKeys; /** Used for built-in method references. */ var objectProto$8 = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$8; return value === proto; } var _isPrototype = isPrototype; /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } var _overArg = overArg; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = _overArg(Object.keys, Object); var _nativeKeys = nativeKeys; /** Used for built-in method references. */ var objectProto$9 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$6 = objectProto$9.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!_isPrototype(object)) { return _nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty$6.call(object, key) && key != 'constructor') { result.push(key); } } return result; } var _baseKeys = baseKeys; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength_1(value.length) && !isFunction_1(value); } var isArrayLike_1 = isArrayLike; /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); } var keys_1 = keys; /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return _baseGetAllKeys(object, keys_1, _getSymbols); } var _getAllKeys = getAllKeys; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$2 = 1; /** Used for built-in method references. */ var objectProto$10 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$7 = objectProto$10.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, objProps = _getAllKeys(object), objLength = objProps.length, othProps = _getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty$7.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } var _equalObjects = equalObjects; /* Built-in method references that are verified to be native. */ var DataView = _getNative(_root, 'DataView'); var _DataView = DataView; /* Built-in method references that are verified to be native. */ var Promise$1 = _getNative(_root, 'Promise'); var _Promise = Promise$1; /* Built-in method references that are verified to be native. */ var Set = _getNative(_root, 'Set'); var _Set = Set; /* Built-in method references that are verified to be native. */ var WeakMap = _getNative(_root, 'WeakMap'); var _WeakMap = WeakMap; /** `Object#toString` result references. */ var mapTag$2 = '[object Map]', objectTag$1 = '[object Object]', promiseTag = '[object Promise]', setTag$2 = '[object Set]', weakMapTag$1 = '[object WeakMap]'; var dataViewTag$2 = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = _toSource(_DataView), mapCtorString = _toSource(_Map), promiseCtorString = _toSource(_Promise), setCtorString = _toSource(_Set), weakMapCtorString = _toSource(_WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2) || (_Map && getTag(new _Map) != mapTag$2) || (_Promise && getTag(_Promise.resolve()) != promiseTag) || (_Set && getTag(new _Set) != setTag$2) || (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { getTag = function(value) { var result = _baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : undefined, ctorString = Ctor ? _toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag$2; case mapCtorString: return mapTag$2; case promiseCtorString: return promiseTag; case setCtorString: return setTag$2; case weakMapCtorString: return weakMapTag$1; } } return result; }; } var _getTag = getTag; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG$3 = 1; /** `Object#toString` result references. */ var argsTag$2 = '[object Arguments]', arrayTag$1 = '[object Array]', objectTag$2 = '[object Object]'; /** Used for built-in method references. */ var objectProto$11 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$8 = objectProto$11.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray_1(object), othIsArr = isArray_1(other), objTag = objIsArr ? arrayTag$1 : _getTag(object), othTag = othIsArr ? arrayTag$1 : _getTag(other); objTag = objTag == argsTag$2 ? objectTag$2 : objTag; othTag = othTag == argsTag$2 ? objectTag$2 : othTag; var objIsObj = objTag == objectTag$2, othIsObj = othTag == objectTag$2, isSameTag = objTag == othTag; if (isSameTag && isBuffer_1(object)) { if (!isBuffer_1(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new _Stack); return (objIsArr || isTypedArray_1(object)) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { var objIsWrapped = objIsObj && hasOwnProperty$8.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty$8.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new _Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new _Stack); return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); } var _baseIsEqualDeep = baseIsEqualDeep; /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { return value !== value && other !== other; } return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } var _baseIsEqual = baseIsEqual; /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ /** `Object#toString` result references. */ var symbolTag$1 = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1); } var isSymbol_1 = isSymbol; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray_1(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } var _isKey = isKey; /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || _MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = _MapCache; var memoize_1 = memoize; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize_1(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } var _memoizeCapped = memoizeCapped; /** Used to match property names within property paths. */ var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = _memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); var _stringToPath = stringToPath; /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } var _arrayMap = arrayMap; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray_1(value)) { // Recursively convert values (susceptible to call stack limits). return _arrayMap(value, baseToString) + ''; } if (isSymbol_1(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } var _baseToString = baseToString; /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : _baseToString(value); } var toString_1 = toString; /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray_1(value)) { return value; } return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); } var _castPath = castPath; /** Used as references for various `Number` constants. */ var INFINITY$1 = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol_1(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; } var _toKey = toKey; /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = _castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = _toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); } var _hasPath = hasPath; /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return _baseIsEqual(value, other); } var isEqual_1 = isEqual; /** Used for built-in method references. */ var objectProto$12 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$9 = objectProto$12.hasOwnProperty; /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty$9.call(object, key); } var _baseHas = baseHas; /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && _hasPath(object, path, _baseHas); } var has_1 = has; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; var emptyFunction_1 = emptyFunction; function invariant(condition, format, a, b, c, d, e, f) { if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } var invariant_1 = invariant; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty$10 = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty$10.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED'; var ReactPropTypesSecret_1 = ReactPropTypesSecret; var factoryWithThrowingShims = function() { function shim(props, propName, componentName, location, propFullName, secret) { if (secret === ReactPropTypesSecret_1) { // It is still safe when called from React. return; } invariant_1( false, 'Calling PropTypes validators directly is not supported by the `prop-types` package. ' + 'Use PropTypes.checkPropTypes() to call them. ' + 'Read more at http://fb.me/use-check-prop-types' ); } shim.isRequired = shim; function getShim() { return shim; } // Important! // Keep this list in sync with production version in `./factoryWithTypeCheckers.js`. var ReactPropTypes = { array: shim, bool: shim, func: shim, number: shim, object: shim, string: shim, symbol: shim, any: shim, arrayOf: getShim, element: shim, instanceOf: getShim, node: shim, objectOf: getShim, oneOf: getShim, oneOfType: getShim, shape: getShim, exact: getShim }; ReactPropTypes.checkPropTypes = emptyFunction_1; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; var propTypes = createCommonjsModule(function (module) { /** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ { // By explicitly using `prop-types` you are opting into new production behavior. // http://fb.me/prop-types-in-prod module.exports = factoryWithThrowingShims(); } }); /** Built-in value references. */ var getPrototype = _overArg(Object.getPrototypeOf, Object); var _getPrototype = getPrototype; /** `Object#toString` result references. */ var objectTag$3 = '[object Object]'; /** Used for built-in method references. */ var funcProto$2 = Function.prototype, objectProto$13 = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString$2 = funcProto$2.toString; /** Used to check objects for own properties. */ var hasOwnProperty$11 = objectProto$13.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString$2.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { return false; } var proto = _getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty$11.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString$2.call(Ctor) == objectCtorString; } var isPlainObject_1 = isPlainObject; /** `Object#toString` result references. */ var mapTag$3 = '[object Map]', setTag$3 = '[object Set]'; /** Used for built-in method references. */ var objectProto$14 = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty$12 = objectProto$14.hasOwnProperty; /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike_1(value) && (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { return !value.length; } var tag = _getTag(value); if (tag == mapTag$3 || tag == setTag$3) { return !value.size; } if (_isPrototype(value)) { return !_baseKeys(value).length; } for (var key in value) { if (hasOwnProperty$12.call(value, key)) { return false; } } return true; } var isEmpty_1 = isEmpty; // From https://github.com/reactjs/react-redux/blob/master/src/utils/shallowEqual.js function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } function getDisplayName(Component) { return Component.displayName || Component.name || 'UnknownComponent'; } function removeEmptyKey(obj) { Object.keys(obj).forEach(function (key) { var value = obj[key]; if (isEmpty_1(value) && isPlainObject_1(value)) { delete obj[key]; } else if (isPlainObject_1(value)) { removeEmptyKey(value); } }); return obj; } var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; /** * @typedef {object} ConnectorDescription * @property {string} displayName - the displayName used by the wrapper * @property {function} refine - a function to filter the local state * @property {function} getSearchParameters - function transforming the local state to a SearchParameters * @property {function} getMetadata - metadata of the widget * @property {function} transitionState - hook after the state has changed * @property {function} getProvidedProps - transform the state into props passed to the wrapped component. * Receives (props, widgetStates, searchState, metadata) and returns the local state. * @property {function} getId - Receives props and return the id that will be used to identify the widget * @property {function} cleanUp - hook when the widget will unmount. Receives (props, searchState) and return a cleaned state. * @property {object} propTypes - PropTypes forwarded to the wrapped component. * @property {object} defaultProps - default values for the props */ /** * Connectors are the HOC used to transform React components * into InstantSearch widgets. * In order to simplify the construction of such connectors * `createConnector` takes a description and transform it into * a connector. * @param {ConnectorDescription} connectorDesc the description of the connector * @return {Connector} a function that wraps a component into * an instantsearch connected one. */ function createConnector(connectorDesc) { if (!connectorDesc.displayName) { throw new Error('`createConnector` requires you to provide a `displayName` property.'); } var hasRefine = has_1(connectorDesc, 'refine'); var hasSearchForFacetValues = has_1(connectorDesc, 'searchForFacetValues'); var hasSearchParameters = has_1(connectorDesc, 'getSearchParameters'); var hasMetadata = has_1(connectorDesc, 'getMetadata'); var hasTransitionState = has_1(connectorDesc, 'transitionState'); var hasCleanUp = has_1(connectorDesc, 'cleanUp'); var isWidget = hasSearchParameters || hasMetadata || hasTransitionState; return function (Composed) { var _class, _temp, _initialiseProps; return _temp = _class = function (_Component) { inherits(Connector, _Component); function Connector(props, context) { classCallCheck(this, Connector); var _this = possibleConstructorReturn(this, (Connector.__proto__ || Object.getPrototypeOf(Connector)).call(this, props, context)); _initialiseProps.call(_this); var _context$ais = context.ais, store = _context$ais.store, widgetsManager = _context$ais.widgetsManager; var canRender = false; _this.state = { props: _this.getProvidedProps(_extends({}, props, { canRender: canRender })), canRender: canRender // use to know if a component is rendered (browser), or not (server). }; _this.unsubscribe = store.subscribe(function () { if (_this.state.canRender) { _this.setState({ props: _this.getProvidedProps(_extends({}, _this.props, { canRender: _this.state.canRender })) }); } }); if (isWidget) { _this.unregisterWidget = widgetsManager.registerWidget(_this); } return _this; } createClass(Connector, [{ key: 'getMetadata', value: function getMetadata(nextWidgetsState) { if (hasMetadata) { return connectorDesc.getMetadata.call(this, this.props, nextWidgetsState); } return {}; } }, { key: 'getSearchParameters', value: function getSearchParameters(searchParameters) { if (hasSearchParameters) { return connectorDesc.getSearchParameters.call(this, searchParameters, this.props, this.context.ais.store.getState().widgets); } return null; } }, { key: 'transitionState', value: function transitionState(prevWidgetsState, nextWidgetsState) { if (hasTransitionState) { return connectorDesc.transitionState.call(this, this.props, prevWidgetsState, nextWidgetsState); } return nextWidgetsState; } }, { key: 'componentDidMount', value: function componentDidMount() { this.setState({ canRender: true }); } }, { key: 'componentWillMount', value: function componentWillMount() { if (connectorDesc.getSearchParameters) { this.context.ais.onSearchParameters(connectorDesc.getSearchParameters, this.context, this.props); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (!isEqual_1(this.props, nextProps)) { this.setState({ props: this.getProvidedProps(nextProps) }); if (isWidget) { // Since props might have changed, we need to re-run getSearchParameters // and getMetadata with the new props. this.context.ais.widgetsManager.update(); if (connectorDesc.transitionState) { this.context.ais.onSearchStateChange(connectorDesc.transitionState.call(this, nextProps, this.context.ais.store.getState().widgets, this.context.ais.store.getState().widgets)); } } } } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unsubscribe(); if (isWidget) { this.unregisterWidget(); // will schedule an update if (hasCleanUp) { var newState = connectorDesc.cleanUp.call(this, this.props, this.context.ais.store.getState().widgets); this.context.ais.store.setState(_extends({}, this.context.ais.store.getState(), { widgets: newState })); this.context.ais.onSearchStateChange(removeEmptyKey(newState)); } } } }, { key: 'shouldComponentUpdate', value: function shouldComponentUpdate(nextProps, nextState) { var propsEqual = shallowEqual(this.props, nextProps); if (this.state.props === null || nextState.props === null) { if (this.state.props === nextState.props) { return !propsEqual; } return true; } return !propsEqual || !shallowEqual(this.state.props, nextState.props); } }, { key: 'render', value: function render() { if (this.state.props === null) { return null; } var refineProps = hasRefine ? { refine: this.refine, createURL: this.createURL } : {}; var searchForFacetValuesProps = hasSearchForFacetValues ? { searchForItems: this.searchForFacetValues } : {}; return React__default.createElement(Composed, _extends({}, this.props, this.state.props, refineProps, searchForFacetValuesProps)); } }]); return Connector; }(React.Component), _class.displayName = connectorDesc.displayName + '(' + getDisplayName(Composed) + ')', _class.defaultClassNames = Composed.defaultClassNames, _class.propTypes = connectorDesc.propTypes, _class.defaultProps = connectorDesc.defaultProps, _class.contextTypes = { // @TODO: more precise state manager propType ais: propTypes.object.isRequired, multiIndexContext: propTypes.object }, _initialiseProps = function _initialiseProps() { var _this2 = this; this.getProvidedProps = function (props) { var store = _this2.context.ais.store; var _store$getState = store.getState(), results = _store$getState.results, searching = _store$getState.searching, error = _store$getState.error, widgets = _store$getState.widgets, metadata = _store$getState.metadata, resultsFacetValues = _store$getState.resultsFacetValues, searchingForFacetValues = _store$getState.searchingForFacetValues, isSearchStalled = _store$getState.isSearchStalled; var searchResults = { results: results, searching: searching, error: error, searchingForFacetValues: searchingForFacetValues, isSearchStalled: isSearchStalled }; return connectorDesc.getProvidedProps.call(_this2, props, widgets, searchResults, metadata, resultsFacetValues); }; this.refine = function () { var _connectorDesc$refine; for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this2.context.ais.onInternalStateUpdate((_connectorDesc$refine = connectorDesc.refine).call.apply(_connectorDesc$refine, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.searchForFacetValues = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2.context.ais.onSearchForFacetValues(connectorDesc.searchForFacetValues.apply(connectorDesc, [_this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.createURL = function () { var _connectorDesc$refine2; for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return _this2.context.ais.createHrefForState((_connectorDesc$refine2 = connectorDesc.refine).call.apply(_connectorDesc$refine2, [_this2, _this2.props, _this2.context.ais.store.getState().widgets].concat(args))); }; this.cleanUp = function () { var _connectorDesc$cleanU; for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return (_connectorDesc$cleanU = connectorDesc.cleanUp).call.apply(_connectorDesc$cleanU, [_this2].concat(args)); }; }, _temp; }; } exports.createConnector = createConnector; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=Core.js.map
flow-typed/npm/eslint-plugin-react_vx.x.x.js
pionl/react-resizable-box
// flow-typed signature: fc559df9ab8c05cd9fa66b7d7ee8c5a4 // flow-typed version: <<STUB>>/eslint-plugin-react_v^7.1.0/flow_v0.54.0 /** * This is an autogenerated libdef stub for: * * 'eslint-plugin-react' * * 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 'eslint-plugin-react' { 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 'eslint-plugin-react/lib/rules/boolean-prop-naming' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/default-props-match-prop-types' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/display-name' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/forbid-component-props' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/forbid-elements' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/forbid-foreign-prop-types' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/forbid-prop-types' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-boolean-value' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-closing-bracket-location' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-closing-tag-location' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-curly-spacing' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-equals-spacing' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-filename-extension' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-first-prop-new-line' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-handler-names' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-indent-props' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-indent' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-key' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-max-props-per-line' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-no-bind' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-no-comment-textnodes' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-no-duplicate-props' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-no-literals' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-no-target-blank' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-no-undef' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-pascal-case' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-sort-props' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-space-before-closing' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-tag-spacing' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-uses-react' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-uses-vars' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/jsx-wrap-multilines' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-array-index-key' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-children-prop' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-danger-with-children' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-danger' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-deprecated' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-did-mount-set-state' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-did-update-set-state' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-direct-mutation-state' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-find-dom-node' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-is-mounted' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-multi-comp' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-redundant-should-component-update' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-render-return-value' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-set-state' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-string-refs' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-typos' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-unescaped-entities' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-unknown-property' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-unused-prop-types' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-unused-state' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/no-will-update-set-state' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/prefer-es6-class' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/prefer-stateless-function' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/prop-types' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/react-in-jsx-scope' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/require-default-props' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/require-optimization' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/require-render-return' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/self-closing-comp' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/sort-comp' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/sort-prop-types' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/style-prop-object' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/rules/void-dom-elements-no-children' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/util/annotations' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/util/Components' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/util/getTokenBeforeClosingBracket' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/util/makeNoMethodSetStateRule' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/util/pragma' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/util/variable' { declare module.exports: any; } declare module 'eslint-plugin-react/lib/util/version' { declare module.exports: any; } // Filename aliases declare module 'eslint-plugin-react/index' { declare module.exports: $Exports<'eslint-plugin-react'>; } declare module 'eslint-plugin-react/index.js' { declare module.exports: $Exports<'eslint-plugin-react'>; } declare module 'eslint-plugin-react/lib/rules/boolean-prop-naming.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/boolean-prop-naming'>; } declare module 'eslint-plugin-react/lib/rules/default-props-match-prop-types.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/default-props-match-prop-types'>; } declare module 'eslint-plugin-react/lib/rules/display-name.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/display-name'>; } declare module 'eslint-plugin-react/lib/rules/forbid-component-props.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/forbid-component-props'>; } declare module 'eslint-plugin-react/lib/rules/forbid-elements.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/forbid-elements'>; } declare module 'eslint-plugin-react/lib/rules/forbid-foreign-prop-types.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/forbid-foreign-prop-types'>; } declare module 'eslint-plugin-react/lib/rules/forbid-prop-types.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/forbid-prop-types'>; } declare module 'eslint-plugin-react/lib/rules/jsx-boolean-value.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-boolean-value'>; } declare module 'eslint-plugin-react/lib/rules/jsx-closing-bracket-location.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-closing-bracket-location'>; } declare module 'eslint-plugin-react/lib/rules/jsx-closing-tag-location.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-closing-tag-location'>; } declare module 'eslint-plugin-react/lib/rules/jsx-curly-spacing.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-curly-spacing'>; } declare module 'eslint-plugin-react/lib/rules/jsx-equals-spacing.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-equals-spacing'>; } declare module 'eslint-plugin-react/lib/rules/jsx-filename-extension.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-filename-extension'>; } declare module 'eslint-plugin-react/lib/rules/jsx-first-prop-new-line.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-first-prop-new-line'>; } declare module 'eslint-plugin-react/lib/rules/jsx-handler-names.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-handler-names'>; } declare module 'eslint-plugin-react/lib/rules/jsx-indent-props.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-indent-props'>; } declare module 'eslint-plugin-react/lib/rules/jsx-indent.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-indent'>; } declare module 'eslint-plugin-react/lib/rules/jsx-key.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-key'>; } declare module 'eslint-plugin-react/lib/rules/jsx-max-props-per-line.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-max-props-per-line'>; } declare module 'eslint-plugin-react/lib/rules/jsx-no-bind.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-no-bind'>; } declare module 'eslint-plugin-react/lib/rules/jsx-no-comment-textnodes.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-no-comment-textnodes'>; } declare module 'eslint-plugin-react/lib/rules/jsx-no-duplicate-props.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-no-duplicate-props'>; } declare module 'eslint-plugin-react/lib/rules/jsx-no-literals.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-no-literals'>; } declare module 'eslint-plugin-react/lib/rules/jsx-no-target-blank.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-no-target-blank'>; } declare module 'eslint-plugin-react/lib/rules/jsx-no-undef.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-no-undef'>; } declare module 'eslint-plugin-react/lib/rules/jsx-pascal-case.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-pascal-case'>; } declare module 'eslint-plugin-react/lib/rules/jsx-sort-props.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-sort-props'>; } declare module 'eslint-plugin-react/lib/rules/jsx-space-before-closing.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-space-before-closing'>; } declare module 'eslint-plugin-react/lib/rules/jsx-tag-spacing.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-tag-spacing'>; } declare module 'eslint-plugin-react/lib/rules/jsx-uses-react.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-uses-react'>; } declare module 'eslint-plugin-react/lib/rules/jsx-uses-vars.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-uses-vars'>; } declare module 'eslint-plugin-react/lib/rules/jsx-wrap-multilines.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/jsx-wrap-multilines'>; } declare module 'eslint-plugin-react/lib/rules/no-array-index-key.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-array-index-key'>; } declare module 'eslint-plugin-react/lib/rules/no-children-prop.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-children-prop'>; } declare module 'eslint-plugin-react/lib/rules/no-danger-with-children.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-danger-with-children'>; } declare module 'eslint-plugin-react/lib/rules/no-danger.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-danger'>; } declare module 'eslint-plugin-react/lib/rules/no-deprecated.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-deprecated'>; } declare module 'eslint-plugin-react/lib/rules/no-did-mount-set-state.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-did-mount-set-state'>; } declare module 'eslint-plugin-react/lib/rules/no-did-update-set-state.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-did-update-set-state'>; } declare module 'eslint-plugin-react/lib/rules/no-direct-mutation-state.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-direct-mutation-state'>; } declare module 'eslint-plugin-react/lib/rules/no-find-dom-node.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-find-dom-node'>; } declare module 'eslint-plugin-react/lib/rules/no-is-mounted.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-is-mounted'>; } declare module 'eslint-plugin-react/lib/rules/no-multi-comp.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-multi-comp'>; } declare module 'eslint-plugin-react/lib/rules/no-redundant-should-component-update.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-redundant-should-component-update'>; } declare module 'eslint-plugin-react/lib/rules/no-render-return-value.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-render-return-value'>; } declare module 'eslint-plugin-react/lib/rules/no-set-state.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-set-state'>; } declare module 'eslint-plugin-react/lib/rules/no-string-refs.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-string-refs'>; } declare module 'eslint-plugin-react/lib/rules/no-typos.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-typos'>; } declare module 'eslint-plugin-react/lib/rules/no-unescaped-entities.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-unescaped-entities'>; } declare module 'eslint-plugin-react/lib/rules/no-unknown-property.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-unknown-property'>; } declare module 'eslint-plugin-react/lib/rules/no-unused-prop-types.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-unused-prop-types'>; } declare module 'eslint-plugin-react/lib/rules/no-unused-state.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-unused-state'>; } declare module 'eslint-plugin-react/lib/rules/no-will-update-set-state.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/no-will-update-set-state'>; } declare module 'eslint-plugin-react/lib/rules/prefer-es6-class.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/prefer-es6-class'>; } declare module 'eslint-plugin-react/lib/rules/prefer-stateless-function.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/prefer-stateless-function'>; } declare module 'eslint-plugin-react/lib/rules/prop-types.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/prop-types'>; } declare module 'eslint-plugin-react/lib/rules/react-in-jsx-scope.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/react-in-jsx-scope'>; } declare module 'eslint-plugin-react/lib/rules/require-default-props.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/require-default-props'>; } declare module 'eslint-plugin-react/lib/rules/require-optimization.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/require-optimization'>; } declare module 'eslint-plugin-react/lib/rules/require-render-return.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/require-render-return'>; } declare module 'eslint-plugin-react/lib/rules/self-closing-comp.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/self-closing-comp'>; } declare module 'eslint-plugin-react/lib/rules/sort-comp.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/sort-comp'>; } declare module 'eslint-plugin-react/lib/rules/sort-prop-types.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/sort-prop-types'>; } declare module 'eslint-plugin-react/lib/rules/style-prop-object.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/style-prop-object'>; } declare module 'eslint-plugin-react/lib/rules/void-dom-elements-no-children.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/rules/void-dom-elements-no-children'>; } declare module 'eslint-plugin-react/lib/util/annotations.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/util/annotations'>; } declare module 'eslint-plugin-react/lib/util/Components.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/util/Components'>; } declare module 'eslint-plugin-react/lib/util/getTokenBeforeClosingBracket.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/util/getTokenBeforeClosingBracket'>; } declare module 'eslint-plugin-react/lib/util/makeNoMethodSetStateRule.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/util/makeNoMethodSetStateRule'>; } declare module 'eslint-plugin-react/lib/util/pragma.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/util/pragma'>; } declare module 'eslint-plugin-react/lib/util/variable.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/util/variable'>; } declare module 'eslint-plugin-react/lib/util/version.js' { declare module.exports: $Exports<'eslint-plugin-react/lib/util/version'>; }
dev/react-subjects/subjects/ServerRendering/solution/server.js
AlanWarren/dotfiles
/* eslint-disable no-console */ import http from 'http' import React from 'react' import ReactDOMServer from 'react-dom/server' import fetchContacts from './fetchContacts' import App from './App' const webpackServer = 'http://localhost:8080' const port = 8090 const createPage = (markup, data) => ` <!doctype html> <html> <head> <meta charset="utf-8"/> <title>My Universal App</title> </head> <body> <div id="app">${markup}</div> <script>window.__DATA__ = ${JSON.stringify(data)}</script> <script src="${webpackServer}/__build__/shared.js"></script> <script src="${webpackServer}/__build__/ServerRendering-solution.js"></script> </body> </html> ` const app = http.createServer((req, res) => { fetchContacts((error, contacts) => { const markup = ReactDOMServer.renderToString(<App contacts={contacts}/>) const html = createPage(markup, { contacts }) res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': html.length }) res.end(html) }) }) app.listen(port, () => { console.log('\nOpen http://localhost:%s', port) })
pages/guides/typescript.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from 'docs/src/pages/guides/typescript/typescript.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
web/src/js/__tests__/components/ContentView/DownloadContentButtonSpec.js
zlorb/mitmproxy
import React from 'react' import renderer from 'react-test-renderer' import DownloadContentButton from '../../../components/ContentView/DownloadContentButton' import { TFlow } from '../../ducks/tutils' let tflow = new TFlow() describe('DownloadContentButton Component', () => { it('should render correctly', () => { let downloadContentButton = renderer.create( <DownloadContentButton flow={tflow} message={tflow.response}/> ), tree = downloadContentButton.toJSON() expect(tree).toMatchSnapshot() }) })
docs/src/index.js
InsidersByte/react-markdown-editor
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
packages/material-ui-icons/legacy/BatteryCharging30Rounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fillOpacity=".3" d="M15.67 4H14V3c0-.55-.45-1-1-1h-2c-.55 0-1 .45-1 1v1H8.33C7.6 4 7 4.6 7 5.33v9.17h2.83c-.38 0-.62-.4-.44-.74l2.67-5c.24-.45.94-.28.94.24v3.5h1.17c.38 0 .62.4.44.74l-.67 1.26H17V5.33C17 4.6 16.4 4 15.67 4z" /><path d="M11.94 18.24c-.24.45-.94.28-.94-.24v-3.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07l-1.99 3.74z" /></React.Fragment> , 'BatteryCharging30Rounded');
app/components/Login/Social.js
Jberivera/pandoras-wall
import React from 'react'; import style from './Login.scss'; import classNames from 'classnames/bind'; const css = classNames.bind(style); const Social = ({ onFacebookLogin }) => { return ( <div> <div className={ css('fb-btn') } onClick={onFacebookLogin}>Facebook</div> </div> ); }; export default Social;
src/svg-icons/action/trending-down.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionTrendingDown = (props) => ( <SvgIcon {...props}> <path d="M16 18l2.29-2.29-4.88-4.88-4 4L2 7.41 3.41 6l6 6 4-4 6.3 6.29L22 12v6z"/> </SvgIcon> ); ActionTrendingDown = pure(ActionTrendingDown); ActionTrendingDown.displayName = 'ActionTrendingDown'; ActionTrendingDown.muiName = 'SvgIcon'; export default ActionTrendingDown;
src/routes/home/index.js
hmeinertrita/MyPlanetGirlGuides
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Home from './Home'; import Layout from '../../components/Layout'; function action() { return { chunks: ['home'], title: 'Girl Scout', component: ( <Layout> <Home /> </Layout> ), }; } export default action;
node_modules/rebass/test/PanelHeader.spec.js
HasanSa/hackathon
import React from 'react' import TestUtils from 'react-addons-test-utils' import expect from 'expect' import { PanelHeader, Base } from '../src' const renderer = TestUtils.createRenderer() describe('PanelHeader', () => { let tree beforeEach(() => { renderer.render(<PanelHeader />) tree = renderer.getRenderOutput() }) it('should render', () => { expect(tree.type).toEqual(Base) }) it('should have a className', () => { expect(tree.props.className).toEqual('PanelHeader') }) it('should have default theme', () => { expect(tree.props.theme).toEqual('default') }) context('when custom styles are set', () => { beforeEach(() => { renderer.render(<PanelHeader style={{ color: 'tomato' }} />) tree = renderer.getRenderOutput() }) it('should have a custom color', () => { expect(tree.props.style.color).toEqual('tomato') }) }) })
src/containers/ResetPasswordContainer.js
codefordenver/encorelink
import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import PropTypes from 'prop-types'; import React from 'react'; import ResetPassword from '../components/ResetPassword'; import { resetPasswordFromToken } from '../actions/userActions'; const ResetPasswordContainer = (props) => { function onResetPassword(formData) { props.resetPasswordFromToken(formData.password, props.location.query.id, props.location.query.token); } return ( <ResetPassword onSubmit={onResetPassword} /> ); }; ResetPasswordContainer.propTypes = { resetPasswordFromToken: PropTypes.func.isRequired, location: PropTypes.shape({ query: PropTypes.shape({ id: PropTypes.string, token: PropTypes.string }) }).isRequired }; const mapDispatchToProps = { resetPasswordFromToken }; export default withRouter(connect(null, mapDispatchToProps)(ResetPasswordContainer));
packages/@vega/review-tool/src/components/withNavigateIntent.js
VegaPublish/vega-studio
import React from 'react' import {withRouterHOC} from 'part:@vega/core/router' export default function withNavigateIntent(Component) { return withRouterHOC(props => { const {router, ...rest} = props return <Component navigateIntent={router.navigateIntent} {...rest} /> }) }
examples/huge-apps/components/GlobalNav.js
emmenko/react-router
import React from 'react'; import { Link } from 'react-router'; const styles = {}; class GlobalNav extends React.Component { static defaultProps = { user: { id: 1, name: 'Ryan Florence' } }; constructor (props, context) { super(props, context); this.logOut = this.logOut.bind(this); } logOut () { alert('log out'); } render () { var { user } = this.props; return ( <div style={styles.wrapper}> <div style={{float: 'left'}}> <Link to="/" style={styles.link}>Home</Link>{' '} <Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '} <Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '} <Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '} </div> <div style={{float: 'right'}}> <Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button> </div> </div> ); } } var dark = 'hsl(200, 20%, 20%)'; var light = '#fff'; styles.wrapper = { padding: '10px 20px', overflow: 'hidden', background: dark, color: light }; styles.link = { padding: 11, color: light, fontWeight: 200 } styles.activeLink = Object.assign({}, styles.link, { background: light, color: dark }); console.log(styles.link); export default GlobalNav;
node_modules/material-ui/svg-icons/action/view-list.js
firdiansyah/crud-req
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var ActionViewList = function ActionViewList(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M4 14h4v-4H4v4zm0 5h4v-4H4v4zM4 9h4V5H4v4zm5 5h12v-4H9v4zm0 5h12v-4H9v4zM9 5v4h12V5H9z' }) ); }; ActionViewList = (0, _pure2.default)(ActionViewList); ActionViewList.displayName = 'ActionViewList'; ActionViewList.muiName = 'SvgIcon'; exports.default = ActionViewList;
rojak-ui-web/src/app/result/ResultWrapper.js
bobbypriambodo/rojak
import React from 'react' import { connect } from 'react-redux' import styles from './result.css' class ResultWrapper extends React.Component { static propTypes = { children: React.PropTypes.any.isRequired, expanded: React.PropTypes.bool.isRequired } get managedChildren () { const { children, expanded } = this.props if (!expanded) return null return children } render () { const { expanded } = this.props return ( <div className={expanded ? styles.resultWrapper : ''}> {this.managedChildren} </div> ) } } const mapStateToProps = (state) => ({ expanded: state.root.expanded }) export default connect(mapStateToProps)(ResultWrapper)
src/components/ui/Alerts.js
shojil/bifapp
/** * Alerts - Status/Success/Error Messages * <Alerts error={'Error hey'} success={'Hello Success'} status={'Something\'s happening...'} /> * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React from 'react'; import PropTypes from 'prop-types'; import { View, StyleSheet, } from 'react-native'; // Components import { Spacer, Text } from '@ui/'; /* Styles ==================================================================== */ const styles = StyleSheet.create({ alerts: { left: 0, right: 0, }, // Success msg: { right: 0, left: 0, paddingVertical: 10, paddingHorizontal: 10, borderLeftWidth: 3, borderColor: '#1C854C', backgroundColor: '#59DC9A', }, msg_text: { textAlign: 'center', color: '#16693c', fontWeight: '500', }, // Error msgError: { borderColor: '#C02827', backgroundColor: '#FB6567', }, msgError_text: { color: '#7f1a1a', }, // Status msgStatus: { borderColor: '#408491', backgroundColor: '#8EDBE5', }, msgStatus_text: { color: '#2f606a', }, }); /* Component ==================================================================== */ const Alerts = ({ status, success, error }) => ( <View style={styles.alerts}> {!!success && <View> <View style={[styles.msg]}> <Text style={[styles.msg_text]}>{success}</Text> </View> <Spacer size={20} /> </View> } {!!status && <View> <View style={[styles.msg, styles.msgStatus]}> <Text style={[styles.msg_text, styles.msgStatus_text]}> {status} </Text> </View> <Spacer size={20} /> </View> } {!!error && <View> <View style={[styles.msg, styles.msgError]}> <Text style={[ styles.msg_text, styles.msgError_text, ]} > {error} </Text> </View> <Spacer size={20} /> </View> } </View> ); Alerts.propTypes = { status: PropTypes.string, success: PropTypes.string, error: PropTypes.string, }; Alerts.defaultProps = { status: '', success: '', error: '', }; Alerts.componentName = 'Alerts'; /* Export Component ==================================================================== */ export default Alerts;
node_modules/react-bootstrap/es/ButtonToolbar.js
superKaigon/TheCave
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var ButtonToolbar = function (_React$Component) { _inherits(ButtonToolbar, _React$Component); function ButtonToolbar() { _classCallCheck(this, ButtonToolbar); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ButtonToolbar.prototype.render = function render() { var _props = this.props, className = _props.className, props = _objectWithoutProperties(_props, ['className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement('div', _extends({}, elementProps, { role: 'toolbar', className: classNames(className, classes) })); }; return ButtonToolbar; }(React.Component); export default bsClass('btn-toolbar', ButtonToolbar);
src/www/js/components/view-row.js
training4developers/bootcamp_04112016
import React from 'react'; export default props => <tr> <td>{props.widget.name}</td> <td>{props.widget.description}</td> <td className='capitalize'>{props.widget.color}</td> <td className='capitalize'>{props.widget.size}</td> <td className='number'>{props.widget.quantity}</td> <td>{props.widget.owner.name}</td> <td> <button className='btn btn-primary btn-sm' type='button' onClick={() => props.onEdit(props.widget.id)}>Edit</button> <button className='btn btn-danger btn-sm' type='button' onClick={() => props.onDelete(props.widget)}>Delete</button> </td> </tr>;
unbuilt/admin/assets/js/hooks/extensions/periods/views/simple-period.js
WordPoints/wordpoints
/** * wp.wordpoints.hooks.view.SimplePeriod * * @class * @augments Backbone.View * @augments wp.wordpoints.hooks.view.Base */ var Base = wp.wordpoints.hooks.view.Base, template = wp.wordpoints.hooks.template, Fields = wp.wordpoints.hooks.Fields, SimplePeriod; SimplePeriod = Base.extend({ namespace: 'period', className: 'wordpoints-hook-period', template: template( 'hook-reaction-simple-period' ), events: { 'change .wordpoints-hook-period-sync': 'sync', 'input .wordpoints-hook-period-sync': 'sync' }, initialize: function ( options ) { this.extension = options.extension; this.reaction = options.reaction; this.actionType = options.actionType; }, // Display the period settings form. render: function () { var name = [ this.extension.get( 'slug' ), this.actionType, 0, 'length' ]; var periodLength = this.reaction.model.get( name ); // Which units should this period be displayed in (second, minutes, &c.)? var unit, units; units = _.keys( this.extension.data.period_units ).sort( function ( a, b ) { return b - a; // We don't have to worry about NaN, etc. }); for ( var i = 0; i < units.length; i++ ) { unit = units[ i ]; if ( 0 === periodLength % unit ) { break; } } var template = this.template( { name: Fields.getFieldName( name ), length: periodLength, length_in_units: periodLength / unit, length_in_units_label: this.getPeriodLabel() } ); template = Fields.createSelect( { value: unit, options: this.extension.data.period_units } , template ); this.$el.html( template ); this.$length = this.$( '.wordpoints-hook-period-length' ); this.$lengthInUnits = this.$( '.wordpoints-hook-period-length-in-units' ); this.$units = this.$( '.wordpoints-hook-period-units' ); this.trigger( 'render', this ); return this; }, getPeriodLabel: function () { var label = this.reaction.Reactor.get( 'periods_label' ); if ( !label ) { label = this.extension.data.l10n.label; } return label; }, sync: function () { this.$length.val( this.$lengthInUnits.val() * this.$units.val() ); } }); module.exports = SimplePeriod;
src/index.js
oliviertassinari/react-event-listener
import React from 'react'; import PropTypes from 'prop-types'; import warning from 'warning'; import { passiveOption } from './supports'; const defaultEventOptions = { capture: false, passive: false, }; function mergeDefaultEventOptions(options) { return { ...defaultEventOptions, ...options }; } function getEventListenerArgs(eventName, callback, options) { const args = [eventName, callback]; args.push(passiveOption ? options : options.capture); return args; } function on(target, eventName, callback, options) { // eslint-disable-next-line prefer-spread target.addEventListener.apply(target, getEventListenerArgs(eventName, callback, options)); } function off(target, eventName, callback, options) { // eslint-disable-next-line prefer-spread target.removeEventListener.apply(target, getEventListenerArgs(eventName, callback, options)); } function forEachListener(props, iteratee) { const { children, // eslint-disable-line no-unused-vars target, // eslint-disable-line no-unused-vars ...eventProps } = props; Object.keys(eventProps).forEach(name => { if (name.substring(0, 2) !== 'on') { return; } const prop = eventProps[name]; const type = typeof prop; const isObject = type === 'object'; const isFunction = type === 'function'; if (!isObject && !isFunction) { return; } const capture = name.substr(-7).toLowerCase() === 'capture'; let eventName = name.substring(2).toLowerCase(); eventName = capture ? eventName.substring(0, eventName.length - 7) : eventName; if (isObject) { iteratee(eventName, prop.handler, prop.options); } else { iteratee(eventName, prop, mergeDefaultEventOptions({ capture })); } }); } export function withOptions(handler, options) { warning(options, 'react-event-listener: should be specified options in withOptions.'); return { handler, options: mergeDefaultEventOptions(options), }; } class EventListener extends React.PureComponent { componentDidMount() { this.applyListeners(on); } componentDidUpdate(prevProps) { this.applyListeners(off, prevProps); this.applyListeners(on); } componentWillUnmount() { this.applyListeners(off); } applyListeners(onOrOff, props = this.props) { const { target } = props; if (target) { let element = target; if (typeof target === 'string') { element = window[target]; } forEachListener(props, onOrOff.bind(null, element)); } } render() { return this.props.children || null; } } EventListener.propTypes = { /** * You can provide a single child too. */ children: PropTypes.node, /** * The DOM target to listen to. */ target: PropTypes.oneOfType([PropTypes.object, PropTypes.string]).isRequired, }; export default EventListener;
ajax/libs/remoteStorage/0.12.1/remotestorage-nocache.amd.js
emmy41124/cdnjs
/** remotestorage.js 0.12.1, http://remotestorage.io, MIT-licensed **/ define(['bluebird'], function(Promise) { /** FILE: src/remotestorage.js **/ (function (global) { // wrapper to implement defer() functionality Promise.defer = function () { var resolve, reject; var promise = new Promise(function() { resolve = arguments[0]; reject = arguments[1]; }); return { resolve: resolve, reject: reject, promise: promise }; }; function logError(error) { if (typeof(error) === 'string') { console.error(error); } else { console.error(error.message, error.stack); } } function emitUnauthorized(r) { if (r.statusCode === 403 || r.statusCode === 401) { this._emit('error', new RemoteStorage.Unauthorized()); } return Promise.resolve(r); } function shareFirst(path) { return ( this.backend === 'dropbox' && path.match(/^\/public\/.*[^\/]$/) ); } var SyncedGetPutDelete = { get: function (path, maxAge) { var self = this; if (this.local) { if (maxAge === undefined) { if ((typeof this.remote === 'object') && this.remote.connected && this.remote.online) { maxAge = 2*this.getSyncInterval(); } else { RemoteStorage.log('Not setting default maxAge, because remote is offline or not connected'); maxAge = false; } } var maxAgeInvalid = function (maxAge) { return maxAge !== false && typeof(maxAge) !== 'number'; }; if (maxAgeInvalid(maxAge)) { return Promise.reject('Argument \'maxAge\' must be false or a number'); } return this.local.get(path, maxAge, this.sync.queueGetRequest.bind(this.sync)); } else { return this.remote.get(path); } }, put: function (path, body, contentType) { if (shareFirst.bind(this)(path)) { return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType)); } else if (this.local) { return this.local.put(path, body, contentType); } else { return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.put(path, body, contentType)); } }, 'delete': function (path) { if (this.local) { return this.local.delete(path); } else { return SyncedGetPutDelete._wrapBusyDone.call(this, this.remote.delete(path)); } }, _wrapBusyDone: function (result) { var self = this; this._emit('wire-busy'); return result.then(function (r) { self._emit('wire-done', { success: true }); return Promise.resolve(r); }, function (err) { self._emit('wire-done', { success: false }); return Promise.reject(err); }); } }; /** * Class: RemoteStorage * * TODO needs proper introduction and links to relevant classes etc * * Constructor for global remoteStorage object. * * This class primarily contains feature detection code and a global convenience API. * * Depending on which features are built in, it contains different attributes and * functions. See the individual features for more information. * * (start code) * var remoteStorage = new RemoteStorage({ * logging: true, // defaults to false * cordovaRedirectUri: 'https://app.mygreatapp.com' // defaults to undefined * }); * (end code) */ var RemoteStorage = function (cfg) { /** * Event: ready * * Fired when ready **/ /** * Event: not-connected * * Fired when ready, but no storage connected ("anonymous mode") **/ /** * Event: connected * * Fired when a remote storage has been connected **/ /** * Event: disconnected * * Fired after disconnect **/ /** * Event: error * * Fired when an error occurs * * Arguments: * the error **/ /** * Event: features-loaded * * Fired when all features are loaded **/ /** * Event: connecting * * Fired before webfinger lookup **/ /** * Event: authing * * Fired before redirecting to the authing server **/ /** * Event: wire-busy * * Fired when a wire request starts **/ /** * Event: wire-done * * Fired when a wire request completes **/ // Initial configuration property settings. if (typeof cfg === 'object') { RemoteStorage.config.logging = !!cfg.logging; RemoteStorage.config.cordovaRedirectUri = cfg.cordovaRedirectUri; } RemoteStorage.eventHandling( this, 'ready', 'connected', 'disconnected', 'not-connected', 'conflict', 'error', 'features-loaded', 'connecting', 'authing', 'wire-busy', 'wire-done', 'sync-interval-change' ); // pending get/put/delete calls. this._pending = []; this._setGPD({ get: this._pendingGPD('get'), put: this._pendingGPD('put'), delete: this._pendingGPD('delete') }); this._cleanups = []; this._pathHandlers = { change: {} }; this.apiKeys = {}; if (this.localStorageAvailable()) { try { this.apiKeys = JSON.parse(localStorage['remotestorage:api-keys']); } catch(exc) { // ignored } this.setBackend(localStorage['remotestorage:backend'] || 'remotestorage'); } var origOn = this.on; this.on = function (eventName, handler) { if (eventName === 'ready' && this.remote.connected && this._allLoaded) { setTimeout(handler, 0); } else if (eventName === 'features-loaded' && this._allLoaded) { setTimeout(handler, 0); } return origOn.call(this, eventName, handler); }; this._init(); this.fireInitial = function () { if (this.local) { setTimeout(this.local.fireInitial.bind(this.local), 0); } }.bind(this); this.on('ready', this.fireInitial.bind(this)); }; RemoteStorage.SyncedGetPutDelete = SyncedGetPutDelete; RemoteStorage.DiscoveryError = function (message) { Error.apply(this, arguments); this.message = message; }; RemoteStorage.DiscoveryError.prototype = Object.create(Error.prototype); RemoteStorage.Unauthorized = function () { Error.apply(this, arguments); }; RemoteStorage.Unauthorized.prototype = Object.create(Error.prototype); /** * Method: RemoteStorage.log * * Log using console.log, when remoteStorage logging is enabled. * * You can enable logging with <enableLog>. * * (In node.js you can also enable logging during remoteStorage object * creation. See: <RemoteStorage>). */ RemoteStorage.log = function () { if (RemoteStorage.config.logging) { console.log.apply(console, arguments); } }; RemoteStorage.config = { logging: false, changeEvents: { local: true, window: false, remote: true, conflict: true }, discoveryTimeout: 10000, cordovaRedirectUri: undefined }; RemoteStorage.prototype = { /** * Method: displayWidget * * Displays the widget at the top right of the page. Make sure to call this function * once on every pageload (after the html 'body' tag), unless you use a custom widget. * * Parameters: * * domID: identifier of the DOM element which should embody the widget (optional) */ // (see src/widget.js for implementation) /** * Property: remote * * Properties: * * connected - Boolean, whether or not a remote store is connected * online - Boolean, whether last sync action was successful or not * userAddress - String, the user address of the connected user * properties - String, the properties of the WebFinger link */ /** * Method: scope * * Returns a BaseClient with a certain scope (base path). Please use this method * only for debugging, and always use defineModule instead, to get access to a * BaseClient from a module in an app. * * Parameters: * * scope - A string, with a leading and a trailing slash, specifying the * base path of the BaseClient that will be returned. * * Code example: * * (start code) * remoteStorage.scope('/pictures/').getListing(''); * remoteStorage.scope('/public/pictures/').getListing(''); */ /** * Method: connect * * Connect to a remoteStorage server. * * Parameters: * userAddress - The user address (user@host) to connect to. * token - (optional) A bearer token acquired beforehand * * Discovers the WebFinger profile of the given user address and initiates * the OAuth dance. * * This method must be called *after* all required access has been claimed. * When using the connect widget, it will call this method itself. * * Special cases: * * 1. If a bearer token is supplied as second argument, the OAuth dance * will be skipped and the supplied token be used instead. This is * useful outside of browser environments, where the token has been * acquired in a different way. * * 2. If the Webfinger profile for the given user address doesn't contain * an auth URL, the library will assume that client and server have * established authorization among themselves, which will omit bearer * tokens in all requests later on. This is useful for example when using * Kerberos and similar protocols. */ connect: function (userAddress, token) { this.setBackend('remotestorage'); if (userAddress.indexOf('@') < 0) { this._emit('error', new RemoteStorage.DiscoveryError("User address doesn't contain an @.")); return; } if (global.cordova) { if (typeof RemoteStorage.config.cordovaRedirectUri !== 'string') { this._emit('error', new RemoteStorage.DiscoveryError("Please supply a custom HTTPS redirect URI for your Cordova app")); return; } if (!global.cordova.InAppBrowser) { this._emit('error', new RemoteStorage.DiscoveryError("Please include the InAppBrowser Cordova plugin to enable OAuth")); return; } } this.remote.configure({ userAddress: userAddress }); this._emit('connecting'); var discoveryTimeout = setTimeout(function () { this._emit('error', new RemoteStorage.DiscoveryError("No storage information found at that user address.")); }.bind(this), RemoteStorage.config.discoveryTimeout); RemoteStorage.Discover(userAddress).then(function (info) { // Info contains fields: href, storageApi, authURL (optional), properties clearTimeout(discoveryTimeout); this._emit('authing'); info.userAddress = userAddress; this.remote.configure(info); if (! this.remote.connected) { if (info.authURL) { if (typeof token === 'undefined') { // Normal authorization step; the default way to connect this.authorize(info.authURL, RemoteStorage.config.cordovaRedirectUri); } else if (typeof token === 'string') { // Token supplied directly by app/developer/user RemoteStorage.log('Skipping authorization sequence and connecting with known token'); this.remote.configure({ token: token }); } else { throw new Error("Supplied bearer token must be a string"); } } else { // In lieu of an excplicit authURL, assume that the browser and // server handle any authorization needs; for instance, TLS may // trigger the browser to use a client certificate, or a 401 Not // Authorized response may make the browser send a Kerberos ticket // using the SPNEGO method. this.impliedauth(); } } }.bind(this), function(err) { this._emit('error', new RemoteStorage.DiscoveryError("Failed to contact storage server.")); }.bind(this)); }, /** * Method: disconnect * * "Disconnect" from remotestorage server to terminate current session. * This method clears all stored settings and deletes the entire local * cache. */ disconnect: function () { if (this.remote) { this.remote.configure({ userAddress: null, href: null, storageApi: null, token: null, properties: null }); } this._setGPD({ get: this._pendingGPD('get'), put: this._pendingGPD('put'), delete: this._pendingGPD('delete') }); var n = this._cleanups.length, i = 0; var oneDone = function () { i++; if (i >= n) { this._init(); RemoteStorage.log('Done cleaning up, emitting disconnected and disconnect events'); this._emit('disconnected'); } }.bind(this); if (n > 0) { this._cleanups.forEach(function (cleanup) { var cleanupResult = cleanup(this); if (typeof(cleanup) === 'object' && typeof(cleanup.then) === 'function') { cleanupResult.then(oneDone); } else { oneDone(); } }.bind(this)); } else { oneDone(); } }, setBackend: function (what) { this.backend = what; if (this.localStorageAvailable()) { if (what) { localStorage['remotestorage:backend'] = what; } else { delete localStorage['remotestorage:backend']; } } }, /** * Method: onChange * * Add a "change" event handler to the given path. Whenever a "change" * happens (as determined by the backend, such as e.g. * <RemoteStorage.IndexedDB>) and the affected path is equal to or below * the given 'path', the given handler is called. * * You should usually not use this method directly, but instead use the * "change" events provided by <RemoteStorage.BaseClient>. * * Parameters: * path - Absolute path to attach handler to. * handler - Handler function. */ onChange: function (path, handler) { if (! this._pathHandlers.change[path]) { this._pathHandlers.change[path] = []; } this._pathHandlers.change[path].push(handler); }, /** * Method: enableLog * * Enable remoteStorage logging. */ enableLog: function () { RemoteStorage.config.logging = true; }, /** * Method: disableLog * * Disable remoteStorage logging */ disableLog: function () { RemoteStorage.config.logging = false; }, /** * Method: log * * The same as <RemoteStorage.log>. */ log: function () { RemoteStorage.log.apply(RemoteStorage, arguments); }, /** * Method: setApiKeys (experimental) * * Set API keys for (currently) GoogleDrive and/or Dropbox backend support. * See also the 'backends' example in the starter-kit. Note that support for * both these backends is still experimental. * * Parameters: * type - string, either 'googledrive' or 'dropbox' * keys - object, with one string field; 'clientId' for GoogleDrive, or * 'appKey' for Dropbox. * */ setApiKeys: function (type, keys) { if (keys) { this.apiKeys[type] = keys; } else { delete this.apiKeys[type]; } if (this.localStorageAvailable()) { localStorage['remotestorage:api-keys'] = JSON.stringify(this.apiKeys); } }, /** * Method: setCordovaRedirectUri * * Set redirect URI to be used for the OAuth redirect within the * in-app-browser window in Cordova apps. * * Parameters: * uri - string, valid HTTP(S) URI */ setCordovaRedirectUri: function (uri) { if (typeof uri !== 'string' || !uri.match(/http(s)?\:\/\//)) { throw new Error("Cordova redirect URI must be a URI string"); } RemoteStorage.config.cordovaRedirectUri = uri; }, /** ** INITIALIZATION **/ _init: function () { var self = this, readyFired = false; function fireReady() { try { if (!readyFired) { self._emit('ready'); readyFired = true; } } catch(e) { console.error("'ready' failed: ", e, e.stack); self._emit('error', e); } } this._loadFeatures(function (features) { this.log('[RemoteStorage] All features loaded'); this.local = features.local && new features.local(); // this.remote set by WireClient._rs_init as lazy property on // RS.prototype if (this.local && this.remote) { this._setGPD(SyncedGetPutDelete, this); this._bindChange(this.local); } else if (this.remote) { this._setGPD(this.remote, this.remote); } if (this.remote) { this.remote.on('connected', function (){ fireReady(); self._emit('connected'); }); this.remote.on('not-connected', function (){ fireReady(); self._emit('not-connected'); }); if (this.remote.connected) { fireReady(); self._emit('connected'); } if (!this.hasFeature('Authorize')) { this.remote.stopWaitingForToken(); } } this._collectCleanupFunctions(); try { this._allLoaded = true; this._emit('features-loaded'); } catch(exc) { logError(exc); this._emit('error', exc); } this._processPending(); }.bind(this)); }, _collectCleanupFunctions: function () { for (var i=0; i < this.features.length; i++) { var cleanup = this.features[i].cleanup; if (typeof(cleanup) === 'function') { this._cleanups.push(cleanup); } } }, /** ** FEATURE DETECTION **/ _loadFeatures: function (callback) { var featureList = [ 'WireClient', 'I18n', 'Dropbox', 'GoogleDrive', 'Access', 'Caching', 'Discover', 'Authorize', 'Widget', 'IndexedDB', 'LocalStorage', 'InMemoryStorage', 'Sync', 'BaseClient', 'Env' ]; var features = []; var featuresDone = 0; var self = this; function featureDone() { featuresDone++; if (featuresDone === featureList.length) { setTimeout(function () { features.caching = !!RemoteStorage.Caching; features.sync = !!RemoteStorage.Sync; [ 'IndexedDB', 'LocalStorage', 'InMemoryStorage' ].some(function (cachingLayer) { if (features.some(function (feature) { return feature.name === cachingLayer; })) { features.local = RemoteStorage[cachingLayer]; return true; } }); self.features = features; callback(features); }, 0); } } function featureInitialized(name) { self.log("[RemoteStorage] [FEATURE "+name+"] initialized."); features.push({ name : name, init : RemoteStorage[name]._rs_init, supported : true, cleanup : RemoteStorage[name]._rs_cleanup }); featureDone(); } function featureFailed(name, err) { self.log("[RemoteStorage] [FEATURE "+name+"] initialization failed ( "+err+")"); featureDone(); } function featureSupported(name, success) { self.log("[RemoteStorage] [FEATURE "+name+"]" + success ? "":" not"+" supported"); if (!success) { featureDone(); } } function initFeature(name) { var initResult; try { initResult = RemoteStorage[name]._rs_init(self); } catch(e) { featureFailed(name, e); return; } if (typeof(initResult) === 'object' && typeof(initResult.then) === 'function') { initResult.then( function (){ featureInitialized(name); }, function (err){ featureFailed(name, err); } ); } else { featureInitialized(name); } } featureList.forEach(function (featureName) { self.log("[RemoteStorage] [FEATURE " + featureName + "] initializing..."); var impl = RemoteStorage[featureName]; var supported; if (impl) { supported = !impl._rs_supported || impl._rs_supported(); if (typeof supported === 'object') { supported.then( function (){ featureSupported(featureName, true); initFeature(featureName); }, function (){ featureSupported(featureName, false); } ); } else if (typeof supported === 'boolean') { featureSupported(featureName, supported); if (supported) { initFeature(featureName); } } } else { featureSupported(featureName, false); } }); }, /** * Method: hasFeature * * Checks whether a feature is enabled or not within remoteStorage. * Returns a boolean. * * Parameters: * name - Capitalized name of the feature. e.g. Authorize, or IndexedDB * * Example: * (start code) * if (remoteStorage.hasFeature('LocalStorage')) { * console.log('LocalStorage is enabled!'); * } * (end code) * */ hasFeature: function (feature) { for (var i = this.features.length - 1; i >= 0; i--) { if (this.features[i].name === feature) { return this.features[i].supported; } } return false; }, localStorageAvailable: function () { try { return !!global.localStorage; } catch(error) { return false; } }, /** ** GET/PUT/DELETE INTERFACE HELPERS **/ _setGPD: function (impl, context) { function wrap(func) { return function () { return func.apply(context, arguments) .then(emitUnauthorized.bind(this)); }; } this.get = wrap(impl.get); this.put = wrap(impl.put); this.delete = wrap(impl.delete); }, _pendingGPD: function (methodName) { return function () { var pending = Promise.defer(); this._pending.push({ method: methodName, args: Array.prototype.slice.call(arguments), promise: pending }); return pending.promise; }.bind(this); }, _processPending: function () { this._pending.forEach(function (pending) { try { this[pending.method].apply(this, pending.args).then(pending.promise.resolve, pending.promise.reject); } catch(e) { pending.promise.reject(e); } }.bind(this)); this._pending = []; }, /** ** CHANGE EVENT HANDLING **/ _bindChange: function (object) { object.on('change', this._dispatchEvent.bind(this, 'change')); }, _dispatchEvent: function (eventName, event) { var self = this; Object.keys(this._pathHandlers[eventName]).forEach(function (path) { var pl = path.length; if (event.path.substr(0, pl) === path) { self._pathHandlers[eventName][path].forEach(function (handler) { var ev = {}; for (var key in event) { ev[key] = event[key]; } ev.relativePath = event.path.replace(new RegExp('^' + path), ''); try { handler(ev); } catch(e) { console.error("'change' handler failed: ", e, e.stack); self._emit('error', e); } }); } }); } }; /** * Property: connected * * Boolean property indicating if remoteStorage is currently connected. */ Object.defineProperty(RemoteStorage.prototype, 'connected', { get: function () { return this.remote.connected; } }); /** * Property: access * * Tracking claimed access scopes. A <RemoteStorage.Access> instance. * * * Property: caching * * Caching settings. A <RemoteStorage.Caching> instance. * * Not available in no-cache builds. * * * Property: remote * * Access to the remote backend used. Usually a <RemoteStorage.WireClient>. * * * Property: local * * Access to the local caching backend used. Usually either a * <RemoteStorage.IndexedDB> or <RemoteStorage.LocalStorage> instance. * * Not available in no-cache builds. */ if ((typeof module === 'object') && (typeof module.exports !== undefined)){ module.exports = RemoteStorage; } else { global.RemoteStorage = RemoteStorage; } })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/util.js **/ /** * Class: RemoteStorage.Util * * Provides reusable utility functions at RemoteStorage.util * */ (function () { /** * Function: fixArrayBuffers * * Takes an object and its copy as produced by the _deepClone function * below, and finds and fixes any ArrayBuffers that were cast to `{}` instead * of being cloned to new ArrayBuffers with the same content. * * It recurses into sub-objects, but skips arrays if they occur. */ function fixArrayBuffers(srcObj, dstObj) { var field, srcArr, dstArr; if (typeof(srcObj) !== 'object' || Array.isArray(srcObj) || srcObj === null) { return; } for (field in srcObj) { if (typeof(srcObj[field]) === 'object' && srcObj[field] !== null) { if (srcObj[field].toString() === '[object ArrayBuffer]') { dstObj[field] = new ArrayBuffer(srcObj[field].byteLength); srcArr = new Int8Array(srcObj[field]); dstArr = new Int8Array(dstObj[field]); dstArr.set(srcArr); } else { fixArrayBuffers(srcObj[field], dstObj[field]); } } } } RemoteStorage.util = { getEventEmitter: function () { var object = {}; var args = Array.prototype.slice.call(arguments); args.unshift(object); RemoteStorage.eventHandling.apply(RemoteStorage, args); object.emit = object._emit; return object; }, extend: function (target) { var sources = Array.prototype.slice.call(arguments, 1); sources.forEach(function (source) { for (var key in source) { target[key] = source[key]; } }); return target; }, asyncEach: function (array, callback) { return this.asyncMap(array, callback). then(function () { return array; }); }, asyncMap: function (array, callback) { var pending = Promise.defer(); var n = array.length, i = 0; var results = [], errors = []; function oneDone() { i++; if (i === n) { pending.resolve(results, errors); } } array.forEach(function (item, index) { var result; try { result = callback(item); } catch(exc) { oneDone(); errors[index] = exc; } if (typeof(result) === 'object' && typeof(result.then) === 'function') { result.then(function (res) { results[index] = res; oneDone(); }, function (error) { errors[index] = error; oneDone(); }); } else { oneDone(); results[index] = result; } }); return pending.promise; }, containingFolder: function (path) { if (path === '') { return '/'; } if (! path) { throw "Path not given!"; } return path.replace(/\/+/g, '/').replace(/[^\/]+\/?$/, ''); }, isFolder: function (path) { return path.substr(-1) === '/'; }, isDocument: function (path) { return path.substr(-1) !== '/'; }, baseName: function (path) { var parts = path.split('/'); if (this.isFolder(path)) { return parts[parts.length-2]+'/'; } else { return parts[parts.length-1]; } }, cleanPath: function (path) { return path.replace(/\/+/g, '/') .split('/').map(encodeURIComponent).join('/') .replace(/'/g, '%27'); }, bindAll: function (object) { for (var key in this) { if (typeof(object[key]) === 'function') { object[key] = object[key].bind(object); } } }, equal: function (a, b, seen) { var key; seen = seen || []; if (typeof(a) !== typeof(b)) { return false; } if (typeof(a) === 'number' || typeof(a) === 'boolean' || typeof(a) === 'string') { return a === b; } if (typeof(a) === 'function') { return a.toString() === b.toString(); } if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) { // Without the following conversion the browsers wouldn't be able to // tell the ArrayBuffer instances apart. a = new Uint8Array(a); b = new Uint8Array(b); } // If this point has been reached, a and b are either arrays or objects. if (a instanceof Array) { if (a.length !== b.length) { return false; } for (var i = 0, c = a.length; i < c; i++) { if (!RemoteStorage.util.equal(a[i], b[i], seen)) { return false; } } } else { // Check that keys from a exist in b for (key in a) { if (a.hasOwnProperty(key) && !(key in b)) { return false; } } // Check that keys from b exist in a, and compare the values for (key in b) { if (!b.hasOwnProperty(key)) { continue; } if (!(key in a)) { return false; } var seenArg; if (typeof(b[key]) === 'object') { if (seen.indexOf(b[key]) >= 0) { // Circular reference, don't attempt to compare this object. // If nothing else returns false, the objects match. continue; } seenArg = seen.slice(); seenArg.push(b[key]); } if (!RemoteStorage.util.equal(a[key], b[key], seenArg)) { return false; } } } return true; }, equalObj: function (obj1, obj2) { console.warn('DEPRECATION WARNING: RemoteStorage.util.equalObj has been replaced by RemoteStorage.util.equal.'); return RemoteStorage.util.equal(obj1, obj2); }, deepClone: function (obj) { var clone; if (obj === undefined) { return undefined; } else { clone = JSON.parse(JSON.stringify(obj)); fixArrayBuffers(obj, clone); return clone; } }, pathsFromRoot: function (path) { var paths = [path]; var parts = path.replace(/\/$/, '').split('/'); while (parts.length > 1) { parts.pop(); paths.push(parts.join('/')+'/'); } return paths; }, /* jshint ignore:start */ md5sum: function(str) { // // http://www.myersdaily.org/joseph/javascript/md5.js // function md5cycle(x, k) { var a = x[0], b = x[1], c = x[2], d = x[3]; a = ff(a, b, c, d, k[0], 7, -680876936); d = ff(d, a, b, c, k[1], 12, -389564586); c = ff(c, d, a, b, k[2], 17, 606105819); b = ff(b, c, d, a, k[3], 22, -1044525330); a = ff(a, b, c, d, k[4], 7, -176418897); d = ff(d, a, b, c, k[5], 12, 1200080426); c = ff(c, d, a, b, k[6], 17, -1473231341); b = ff(b, c, d, a, k[7], 22, -45705983); a = ff(a, b, c, d, k[8], 7, 1770035416); d = ff(d, a, b, c, k[9], 12, -1958414417); c = ff(c, d, a, b, k[10], 17, -42063); b = ff(b, c, d, a, k[11], 22, -1990404162); a = ff(a, b, c, d, k[12], 7, 1804603682); d = ff(d, a, b, c, k[13], 12, -40341101); c = ff(c, d, a, b, k[14], 17, -1502002290); b = ff(b, c, d, a, k[15], 22, 1236535329); a = gg(a, b, c, d, k[1], 5, -165796510); d = gg(d, a, b, c, k[6], 9, -1069501632); c = gg(c, d, a, b, k[11], 14, 643717713); b = gg(b, c, d, a, k[0], 20, -373897302); a = gg(a, b, c, d, k[5], 5, -701558691); d = gg(d, a, b, c, k[10], 9, 38016083); c = gg(c, d, a, b, k[15], 14, -660478335); b = gg(b, c, d, a, k[4], 20, -405537848); a = gg(a, b, c, d, k[9], 5, 568446438); d = gg(d, a, b, c, k[14], 9, -1019803690); c = gg(c, d, a, b, k[3], 14, -187363961); b = gg(b, c, d, a, k[8], 20, 1163531501); a = gg(a, b, c, d, k[13], 5, -1444681467); d = gg(d, a, b, c, k[2], 9, -51403784); c = gg(c, d, a, b, k[7], 14, 1735328473); b = gg(b, c, d, a, k[12], 20, -1926607734); a = hh(a, b, c, d, k[5], 4, -378558); d = hh(d, a, b, c, k[8], 11, -2022574463); c = hh(c, d, a, b, k[11], 16, 1839030562); b = hh(b, c, d, a, k[14], 23, -35309556); a = hh(a, b, c, d, k[1], 4, -1530992060); d = hh(d, a, b, c, k[4], 11, 1272893353); c = hh(c, d, a, b, k[7], 16, -155497632); b = hh(b, c, d, a, k[10], 23, -1094730640); a = hh(a, b, c, d, k[13], 4, 681279174); d = hh(d, a, b, c, k[0], 11, -358537222); c = hh(c, d, a, b, k[3], 16, -722521979); b = hh(b, c, d, a, k[6], 23, 76029189); a = hh(a, b, c, d, k[9], 4, -640364487); d = hh(d, a, b, c, k[12], 11, -421815835); c = hh(c, d, a, b, k[15], 16, 530742520); b = hh(b, c, d, a, k[2], 23, -995338651); a = ii(a, b, c, d, k[0], 6, -198630844); d = ii(d, a, b, c, k[7], 10, 1126891415); c = ii(c, d, a, b, k[14], 15, -1416354905); b = ii(b, c, d, a, k[5], 21, -57434055); a = ii(a, b, c, d, k[12], 6, 1700485571); d = ii(d, a, b, c, k[3], 10, -1894986606); c = ii(c, d, a, b, k[10], 15, -1051523); b = ii(b, c, d, a, k[1], 21, -2054922799); a = ii(a, b, c, d, k[8], 6, 1873313359); d = ii(d, a, b, c, k[15], 10, -30611744); c = ii(c, d, a, b, k[6], 15, -1560198380); b = ii(b, c, d, a, k[13], 21, 1309151649); a = ii(a, b, c, d, k[4], 6, -145523070); d = ii(d, a, b, c, k[11], 10, -1120210379); c = ii(c, d, a, b, k[2], 15, 718787259); b = ii(b, c, d, a, k[9], 21, -343485551); x[0] = add32(a, x[0]); x[1] = add32(b, x[1]); x[2] = add32(c, x[2]); x[3] = add32(d, x[3]); } function cmn(q, a, b, x, s, t) { a = add32(add32(a, q), add32(x, t)); return add32((a << s) | (a >>> (32 - s)), b); } function ff(a, b, c, d, x, s, t) { return cmn((b & c) | ((~b) & d), a, b, x, s, t); } function gg(a, b, c, d, x, s, t) { return cmn((b & d) | (c & (~d)), a, b, x, s, t); } function hh(a, b, c, d, x, s, t) { return cmn(b ^ c ^ d, a, b, x, s, t); } function ii(a, b, c, d, x, s, t) { return cmn(c ^ (b | (~d)), a, b, x, s, t); } function md51(s) { txt = ''; var n = s.length, state = [1732584193, -271733879, -1732584194, 271733878], i; for (i=64; i<=s.length; i+=64) { md5cycle(state, md5blk(s.substring(i-64, i))); } s = s.substring(i-64); var tail = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0]; for (i=0; i<s.length; i++) tail[i>>2] |= s.charCodeAt(i) << ((i%4) << 3); tail[i>>2] |= 0x80 << ((i%4) << 3); if (i > 55) { md5cycle(state, tail); for (i=0; i<16; i++) tail[i] = 0; } tail[14] = n*8; md5cycle(state, tail); return state; } function md5blk(s) { var md5blks = [], i; for (i=0; i<64; i+=4) { md5blks[i>>2] = s.charCodeAt(i) + (s.charCodeAt(i+1) << 8) + (s.charCodeAt(i+2) << 16) + (s.charCodeAt(i+3) << 24); } return md5blks; } var hex_chr = '0123456789abcdef'.split(''); function rhex(n) { var s='', j=0; for(; j<4; j++) s += hex_chr[(n >> (j * 8 + 4)) & 0x0F] + hex_chr[(n >> (j * 8)) & 0x0F]; return s; } function hex(x) { for (var i=0; i<x.length; i++) x[i] = rhex(x[i]); return x.join(''); } function md5(s) { return hex(md51(s)); } var add32 = function (a, b) { return (a + b) & 0xFFFFFFFF; }; if (md5('hello') !== '5d41402abc4b2a76b9719d911017c592') { add32 = function (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; } return md5(str); } /* jshint ignore:end */ }; if (!RemoteStorage.prototype.util) { Object.defineProperty(RemoteStorage.prototype, 'util', { get: function () { console.log('DEPRECATION WARNING: remoteStorage.util was moved to RemoteStorage.util'); return RemoteStorage.util; } }); } })(); /** FILE: src/eventhandling.js **/ (function (global) { /** * Interface: eventhandling */ var methods = { /** * Method: addEventListener * * Install an event handler for the given event name */ addEventListener: function (eventName, handler) { if (typeof(eventName) !== 'string') { throw new Error('Argument eventName should be a string'); } if (typeof(handler) !== 'function') { throw new Error('Argument handler should be a function'); } RemoteStorage.log('[Eventhandling] Adding event listener', eventName, handler); this._validateEvent(eventName); this._handlers[eventName].push(handler); }, /** * Method: removeEventListener * * Remove a previously installed event handler */ removeEventListener: function (eventName, handler) { this._validateEvent(eventName); var hl = this._handlers[eventName].length; for (var i=0;i<hl;i++) { if (this._handlers[eventName][i] === handler) { this._handlers[eventName].splice(i, 1); return; } } }, _emit: function (eventName) { this._validateEvent(eventName); var args = Array.prototype.slice.call(arguments, 1); this._handlers[eventName].forEach(function (handler) { handler.apply(this, args); }); }, _validateEvent: function (eventName) { if (! (eventName in this._handlers)) { throw new Error("Unknown event: " + eventName); } }, _delegateEvent: function (eventName, target) { target.on(eventName, function (event) { this._emit(eventName, event); }.bind(this)); }, _addEvent: function (eventName) { this._handlers[eventName] = []; } }; /** * Method: eventhandling.on * * Alias for <addEventListener> **/ methods.on = methods.addEventListener; /** * Function: eventHandling * * Mixes event handling functionality into an object. * * The first parameter is always the object to be extended. * All remaining parameter are expected to be strings, interpreted as valid event * names. * * Example: * (start code) * var MyConstructor = function () { * eventHandling(this, 'connected', 'disconnected'); * * this._emit('connected'); * this._emit('disconnected'); * // This would throw an exception: * // this._emit('something-else'); * }; * * var myObject = new MyConstructor(); * myObject.on('connected', function () { console.log('connected'); }); * myObject.on('disconnected', function () { console.log('disconnected'); }); * // This would throw an exception as well: * // myObject.on('something-else', function () {}); * (end code) */ RemoteStorage.eventHandling = function (object) { var eventNames = Array.prototype.slice.call(arguments, 1); for (var key in methods) { object[key] = methods[key]; } object._handlers = {}; eventNames.forEach(function (eventName) { object._addEvent(eventName); }); }; })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/wireclient.js **/ (function (global) { var RS = RemoteStorage; /** * Class: RemoteStorage.WireClient * * WireClient Interface * -------------------- * * This file exposes a get/put/delete interface on top of XMLHttpRequest. * It requires to be configured with parameters about the remotestorage server to * connect to. * Each instance of WireClient is always associated with a single remotestorage * server and access token. * * Usually the WireClient instance can be accessed via `remoteStorage.remote`. * * This is the get/put/delete interface: * * - #get() takes a path and optionally a ifNoneMatch option carrying a version * string to check. It returns a promise that will be fulfilled with the HTTP * response status, the response body, the MIME type as returned in the * 'Content-Type' header and the current revision, as returned in the 'ETag' * header. * - #put() takes a path, the request body and a content type string. It also * accepts the ifMatch and ifNoneMatch options, that map to the If-Match and * If-None-Match headers respectively. See the remotestorage-01 specification * for details on handling these headers. It returns a promise, fulfilled with * the same values as the one for #get(). * - #delete() takes a path and the ifMatch option as well. It returns a promise * fulfilled with the same values as the one for #get(). * * In addition to this, the WireClient has some compatibility features to work with * remotestorage 2012.04 compatible storages. For example it will cache revisions * from folder listings in-memory and return them accordingly as the "revision" * parameter in response to #get() requests. Similarly it will return 404 when it * receives an empty folder listing, to mimic remotestorage-01 behavior. Note * that it is not always possible to know the revision beforehand, hence it may * be undefined at times (especially for caching-roots). */ var hasLocalStorage; var SETTINGS_KEY = 'remotestorage:wireclient'; var API_2012 = 1, API_00 = 2, API_01 = 3, API_02 = 4, API_HEAD = 5; var STORAGE_APIS = { 'draft-dejong-remotestorage-00': API_00, 'draft-dejong-remotestorage-01': API_01, 'draft-dejong-remotestorage-02': API_02, 'https://www.w3.org/community/rww/wiki/read-write-web-00#simple': API_2012 }; var isArrayBufferView; if (typeof(ArrayBufferView) === 'function') { isArrayBufferView = function (object) { return object && (object instanceof ArrayBufferView); }; } else { var arrayBufferViews = [ Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ]; isArrayBufferView = function (object) { for (var i=0;i<8;i++) { if (object instanceof arrayBufferViews[i]) { return true; } } return false; }; } var isFolder = RemoteStorage.util.isFolder; var cleanPath = RemoteStorage.util.cleanPath; function addQuotes(str) { if (typeof(str) !== 'string') { return str; } if (str === '*') { return '*'; } return '"' + str + '"'; } function stripQuotes(str) { if (typeof(str) !== 'string') { return str; } return str.replace(/^["']|["']$/g, ''); } function readBinaryData(content, mimeType, callback) { var blob; global.BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder; if (typeof global.BlobBuilder !== 'undefined') { var bb = new global.BlobBuilder(); bb.append(content); blob = bb.getBlob(mimeType); } else { blob = new Blob([content], { type: mimeType }); } var reader = new FileReader(); if (typeof reader.addEventListener === 'function') { reader.addEventListener('loadend', function () { callback(reader.result); // reader.result contains the contents of blob as a typed array }); } else { reader.onloadend = function() { callback(reader.result); // reader.result contains the contents of blob as a typed array }; } reader.readAsArrayBuffer(blob); } function getTextFromArrayBuffer(arrayBuffer, encoding) { var pending = Promise.defer(); if (typeof Blob === 'undefined') { var buffer = new Buffer(new Uint8Array(arrayBuffer)); pending.resolve(buffer.toString(encoding)); } else { var blob; global.BlobBuilder = global.BlobBuilder || global.WebKitBlobBuilder; if (typeof global.BlobBuilder !== 'undefined') { var bb = new global.BlobBuilder(); bb.append(arrayBuffer); blob = bb.getBlob(); } else { blob = new Blob([arrayBuffer]); } var fileReader = new FileReader(); if (typeof fileReader.addEventListener === 'function') { fileReader.addEventListener('loadend', function (evt) { pending.resolve(evt.target.result); }); } else { fileReader.onloadend = function(evt) { pending.resolve(evt.target.result); }; } fileReader.readAsText(blob, encoding); } return pending.promise; } function determineCharset(mimeType) { var charset = 'UTF-8'; var charsetMatch; if (mimeType) { charsetMatch = mimeType.match(/charset=(.+)$/); if (charsetMatch) { charset = charsetMatch[1]; } } return charset; } function isFolderDescription(body) { return ((body['@context'] === 'http://remotestorage.io/spec/folder-description') && (typeof(body['items']) === 'object')); } function isSuccessStatus(status) { return [201, 204, 304].indexOf(status) >= 0; } function isErrorStatus(status) { return [401, 403, 404, 412].indexOf(status) >= 0; } var onErrorCb; /** * Class : RemoteStorage.WireClient **/ RS.WireClient = function (rs) { this.connected = false; /** * Event: change * Never fired for some reason * # TODO create issue and fix or remove * * Event: connected * Fired when the wireclient connect method realizes that it is in * possession of a token and href **/ RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected'); onErrorCb = function (error){ if (error instanceof RemoteStorage.Unauthorized) { this.configure({token: null}); } }.bind(this); rs.on('error', onErrorCb); if (hasLocalStorage) { var settings; try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e) {} if (settings) { setTimeout(function () { this.configure(settings); }.bind(this), 0); } } this._revisionCache = {}; if (this.connected) { setTimeout(this._emit.bind(this), 0, 'connected'); } }; RS.WireClient.REQUEST_TIMEOUT = 30000; RS.WireClient.prototype = { /** * Property: token * * Holds the bearer token of this WireClient, as obtained in the OAuth dance * * Example: * (start code) * * remoteStorage.remote.token * // -> 'DEADBEEF01==' */ /** * Property: href * * Holds the server's base URL, as obtained in the Webfinger discovery * * Example: * (start code) * * remoteStorage.remote.href * // -> 'https://storage.example.com/users/jblogg/' */ /** * Property: storageApi * * Holds the spec version the server claims to be compatible with * * Example: * (start code) * * remoteStorage.remote.storageApi * // -> 'draft-dejong-remotestorage-01' */ _request: function (method, uri, token, headers, body, getEtag, fakeRevision) { if ((method === 'PUT' || method === 'DELETE') && uri[uri.length - 1] === '/') { return Promise.reject('Don\'t ' + method + ' on directories!'); } var revision; var reqType; var self = this; if (token !== RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN) { headers['Authorization'] = 'Bearer ' + token; } this._emit('wire-busy', { method: method, isFolder: isFolder(uri) }); return RS.WireClient.request(method, uri, { body: body, headers: headers, responseType: 'arraybuffer' }).then(function (response) { self._emit('wire-done', { method: method, isFolder: isFolder(uri), success: true }); self.online = true; if (isErrorStatus(response.status)) { RemoteStorage.log('[WireClient] Error response status', response.status); if (getEtag) { revision = stripQuotes(response.getResponseHeader('ETag')); } else { revision = undefined; } return Promise.resolve({statusCode: response.status, revision: revision}); } else if (isSuccessStatus(response.status) || (response.status === 200 && method !== 'GET')) { revision = stripQuotes(response.getResponseHeader('ETag')); RemoteStorage.log('[WireClient] Successful request', revision); return Promise.resolve({statusCode: response.status, revision: revision}); } else { var mimeType = response.getResponseHeader('Content-Type'); var body; if (getEtag) { revision = stripQuotes(response.getResponseHeader('ETag')); } else { revision = response.status === 200 ? fakeRevision : undefined; } var charset = determineCharset(mimeType); if ((!mimeType) || charset === 'binary') { RemoteStorage.log('[WireClient] Successful request with unknown or binary mime-type', revision); return Promise.resolve({statusCode: response.status, body: response.response, contentType: mimeType, revision: revision}); } else { return getTextFromArrayBuffer(response.response, charset).then(function (body) { RemoteStorage.log('[WireClient] Successful request', revision); return Promise.resolve({statusCode: response.status, body: body, contentType: mimeType, revision: revision}); }); } } }, function (error) { self._emit('wire-done', { method: method, isFolder: isFolder(uri), success: false }); return Promise.reject(error); }); }, /** * * Method: configure * * Sets the userAddress, href, storageApi, token, and properties of a * remote store. Also sets connected and online to true and emits the * 'connected' event, if both token and href are present. * * Parameters: * settings - An object that may contain userAddress (string or null), * href (string or null), storageApi (string or null), token (string * or null), and/or properties (the JSON-parsed properties object * from the user's WebFinger record, see section 10 of * http://tools.ietf.org/html/draft-dejong-remotestorage-03 * or null). * Fields that are not included (i.e. `undefined`), stay at * their current value. To set a field, include that field * with a `string` value. To reset a field, for instance when * the user disconnected their storage, or you found that the * token you have has expired, simply set that field to `null`. */ configure: function (settings) { if (typeof settings !== 'object') { throw new Error('WireClient configure settings parameter should be an object'); } if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; } if (typeof settings.href !== 'undefined') { this.href = settings.href; } if (typeof settings.storageApi !== 'undefined') { this.storageApi = settings.storageApi; } if (typeof settings.token !== 'undefined') { this.token = settings.token; } if (typeof settings.properties !== 'undefined') { this.properties = settings.properties; } if (typeof this.storageApi !== 'undefined') { this._storageApi = STORAGE_APIS[this.storageApi] || API_HEAD; this.supportsRevs = this._storageApi >= API_00; } if (this.href && this.token) { this.connected = true; this.online = true; this._emit('connected'); } else { this.connected = false; } if (hasLocalStorage) { localStorage[SETTINGS_KEY] = JSON.stringify({ userAddress: this.userAddress, href: this.href, storageApi: this.storageApi, token: this.token, properties: this.properties }); } }, stopWaitingForToken: function () { if (!this.connected) { this._emit('not-connected'); } }, get: function (path, options) { var self = this; if (!this.connected) { return Promise.reject('not connected (path: ' + path + ')'); } if (!options) { options = {}; } var headers = {}; if (this.supportsRevs) { if (options.ifNoneMatch) { headers['If-None-Match'] = addQuotes(options.ifNoneMatch); } } else if (options.ifNoneMatch) { var oldRev = this._revisionCache[path]; } return this._request('GET', this.href + cleanPath(path), this.token, headers, undefined, this.supportsRevs, this._revisionCache[path]) .then(function (r) { if (!isFolder(path)) { return Promise.resolve(r); } var itemsMap = {}; if (typeof(r.body) !== 'undefined') { try { r.body = JSON.parse(r.body); } catch (e) { return Promise.reject('Folder description at ' + self.href + cleanPath(path) + ' is not JSON'); } } if (r.statusCode === 200 && typeof(r.body) === 'object') { // New folder listing received if (Object.keys(r.body).length === 0) { // Empty folder listing of any spec r.statusCode = 404; } else if (isFolderDescription(r.body)) { // >= 02 spec for (var item in r.body.items) { self._revisionCache[path + item] = r.body.items[item].ETag; } itemsMap = r.body.items; } else { // < 02 spec Object.keys(r.body).forEach(function (key){ self._revisionCache[path + key] = r.body[key]; itemsMap[key] = {'ETag': r.body[key]}; }); } r.body = itemsMap; return Promise.resolve(r); } else { return Promise.resolve(r); } }); }, put: function (path, body, contentType, options) { if (!this.connected) { return Promise.reject('not connected (path: ' + path + ')'); } if (!options) { options = {}; } if ((!contentType.match(/charset=/)) && (body instanceof ArrayBuffer || isArrayBufferView(body))) { contentType += '; charset=binary'; } var headers = { 'Content-Type': contentType }; if (this.supportsRevs) { if (options.ifMatch) { headers['If-Match'] = addQuotes(options.ifMatch); } if (options.ifNoneMatch) { headers['If-None-Match'] = addQuotes(options.ifNoneMatch); } } return this._request('PUT', this.href + cleanPath(path), this.token, headers, body, this.supportsRevs); }, 'delete': function (path, options) { if (!this.connected) { throw new Error('not connected (path: ' + path + ')'); } if (!options) { options = {}; } var headers = {}; if (this.supportsRevs) { if (options.ifMatch) { headers['If-Match'] = addQuotes(options.ifMatch); } } return this._request('DELETE', this.href + cleanPath(path), this.token, headers, undefined, this.supportsRevs); } }; // Shared cleanPath used by Dropbox RS.WireClient.cleanPath = cleanPath; // Shared isArrayBufferView used by WireClient and Dropbox RS.WireClient.isArrayBufferView = isArrayBufferView; RS.WireClient.readBinaryData = readBinaryData; // Shared request function used by WireClient, GoogleDrive and Dropbox. RS.WireClient.request = function (method, url, options) { var pending = Promise.defer(); RemoteStorage.log('[WireClient]', method, url); var timedOut = false; var timer = setTimeout(function () { timedOut = true; pending.reject('timeout'); }, RS.WireClient.REQUEST_TIMEOUT); var xhr = new XMLHttpRequest(); xhr.open(method, url, true); if (options.responseType) { xhr.responseType = options.responseType; } if (options.headers) { for (var key in options.headers) { xhr.setRequestHeader(key, options.headers[key]); } } xhr.onload = function () { if (timedOut) { return; } clearTimeout(timer); pending.resolve(xhr); }; xhr.onerror = function (error) { if (timedOut) { return; } clearTimeout(timer); pending.reject(error); }; var body = options.body; if (typeof(body) === 'object' && !isArrayBufferView(body) && body instanceof ArrayBuffer) { body = new Uint8Array(body); } xhr.send(body); return pending.promise; }; Object.defineProperty(RemoteStorage.WireClient.prototype, 'storageType', { get: function () { if (this.storageApi) { var spec = this.storageApi.match(/draft-dejong-(remotestorage-\d\d)/); return spec ? spec[1] : '2012.04'; } } }); RS.WireClient._rs_init = function (remoteStorage) { hasLocalStorage = remoteStorage.localStorageAvailable(); remoteStorage.remote = new RS.WireClient(remoteStorage); this.online = true; }; RS.WireClient._rs_supported = function () { return !! global.XMLHttpRequest; }; RS.WireClient._rs_cleanup = function (remoteStorage){ if (hasLocalStorage){ delete localStorage[SETTINGS_KEY]; } remoteStorage.removeEventListener('error', onErrorCb); }; })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/discover.js **/ (function (global) { // feature detection flags var haveXMLHttpRequest, hasLocalStorage; // used to store settings in localStorage var SETTINGS_KEY = 'remotestorage:discover'; // cache loaded from localStorage var cachedInfo = {}; /** * Class: RemoteStorage.Discover * * This function deals with the Webfinger lookup, discovering a connecting * user's storage details. * * The discovery timeout can be configured via * `RemoteStorage.config.discoveryTimeout` (in ms). * * Arguments: * * userAddress - user@host * * Returns: * * A promise for an object with the following properties. * * href - Storage base URL, * storageType - Storage type, * authUrl - OAuth URL, * properties - Webfinger link properties **/ RemoteStorage.Discover = function (userAddress) { if (userAddress in cachedInfo) { return Promise.resolve(cachedInfo[userAddress]); } var webFinger = new WebFinger({ tls_only: false, uri_fallback: true, request_timeout: 5000 }); var pending = Promise.defer(); webFinger.lookup(userAddress, function (err, response) { if (err) { return pending.reject(err.message); } else if ((typeof response.idx.links.remotestorage !== 'object') || (typeof response.idx.links.remotestorage.length !== 'number') || (response.idx.links.remotestorage.length <= 0)) { RemoteStorage.log("[Discover] WebFinger record for " + userAddress + " does not have remotestorage defined in the links section ", JSON.stringify(response.json)); return pending.reject("WebFinger record for " + userAddress + " does not have remotestorage defined in the links section."); } var rs = response.idx.links.remotestorage[0]; var authURL = rs.properties['http://tools.ietf.org/html/rfc6749#section-4.2'] || rs.properties['auth-endpoint']; var storageType = rs.properties['http://remotestorage.io/spec/version'] || rs.type; // cache fetched data cachedInfo[userAddress] = { href: rs.href, storageType: storageType, authURL: authURL, properties: rs.properties }; if (hasLocalStorage) { localStorage[SETTINGS_KEY] = JSON.stringify({ cache: cachedInfo }); } return pending.resolve(cachedInfo[userAddress]); }); return pending.promise; }; RemoteStorage.Discover._rs_init = function (remoteStorage) { hasLocalStorage = remoteStorage.localStorageAvailable(); if (hasLocalStorage) { var settings; try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e) {} if (settings) { cachedInfo = settings.cache; } } }; RemoteStorage.Discover._rs_supported = function () { haveXMLHttpRequest = !! global.XMLHttpRequest; return haveXMLHttpRequest; }; RemoteStorage.Discover._rs_cleanup = function () { if (hasLocalStorage) { delete localStorage[SETTINGS_KEY]; } }; })(typeof(window) !== 'undefined' ? window : global); /** FILE: node_modules/webfinger.js/src/webfinger.js **/ /*! * webfinger.js * version 2.2.1 * http://github.com/silverbucket/webfinger.js * * Developed and Maintained by: * Nick Jennings <nick@silverbucket.net> 2012 - 2014 * * webfinger.js is released under the AGPL (see LICENSE). * * You don't have to do anything special to choose one license or the other and you don't * have to notify anyone which license you are using. * Please see the corresponding license file for details of these licenses. * You are free to use, modify and distribute this software, but all copyright * information must remain. * */ if (typeof XMLHttpRequest === 'undefined') { XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; } (function (undefined) { // URI to property name map var LINK_URI_MAPS = { 'http://webfist.org/spec/rel': 'webfist', 'http://webfinger.net/rel/avatar': 'avatar', 'remotestorage': 'remotestorage', 'http://tools.ietf.org/id/draft-dejong-remotestorage': 'remotestorage', 'remoteStorage': 'remotestorage', 'http://www.packetizer.com/rel/share': 'share', 'http://webfinger.net/rel/profile-page': 'profile', 'me': 'profile', 'vcard': 'vcard', 'blog': 'blog', 'http://packetizer.com/rel/blog': 'blog', 'http://schemas.google.com/g/2010#updates-from': 'updates', 'https://camlistore.org/rel/server': 'camilstore' }; var LINK_PROPERTIES = { 'avatar': [], 'remotestorage': [], 'blog': [], 'vcard': [], 'updates': [], 'share': [], 'profile': [], 'webfist': [], 'camlistore': [] }; // list of endpoints to try, fallback from beginning to end. var URIS = ['webfinger', 'host-meta', 'host-meta.json']; function _err(obj) { obj.toString = function () { return this.message; }; return obj; } /** * Function: WebFinger * * WebFinger constructor * * Returns: * * return WebFinger object */ function WebFinger(config) { if (typeof config !== 'object') { config = {}; } this.config = { tls_only: (typeof config.tls_only !== 'undefined') ? config.tls_only : true, webfist_fallback: (typeof config.webfist_fallback !== 'undefined') ? config.webfist_fallback : false, uri_fallback: (typeof config.uri_fallback !== 'undefined') ? config.uri_fallback : false, request_timeout: (typeof config.request_timeout !== 'undefined') ? config.request_timeout : 10000 }; } // make an http request and look for JRD response, fails if request fails // or response not json. WebFinger.prototype._fetchJRD = function (url, cb) { var self = this; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4) { if (xhr.status === 200) { if (self._isValidJSON(xhr.responseText)) { cb(null, xhr.responseText); } else { cb(_err({ message: 'invalid json', url: url, status: xhr.status })); } } else if (xhr.status === 404) { cb(_err({ message: 'endpoint unreachable', url: url, status: xhr.status })); } else { cb(_err({ message: 'error during request', url: url, status: xhr.status })); } } }; xhr.open('GET', url, true); xhr.setRequestHeader('Accept', 'application/jrd+json, application/json'); xhr.send(); }; WebFinger.prototype._isValidJSON = function (str) { try { JSON.parse(str); } catch (e) { return false; } return true; }; WebFinger.prototype._isLocalhost = function (host) { var local = /^localhost(\.localdomain)?(\:[0-9]+)?$/; return local.test(host); }; // processes JRD object as if it's a webfinger response object // looks for known properties and adds them to profile datat struct. WebFinger.prototype._processJRD = function (JRD, cb) { var self = this; var parsedJRD = JSON.parse(JRD); if ((typeof parsedJRD !== 'object') || (typeof parsedJRD.links !== 'object')) { if (typeof parsedJRD.error !== 'undefined') { cb(_err({ message: parsedJRD.error })); } else { cb(_err({ message: 'unknown response from server' })); } return false; } var links = parsedJRD.links; var result = { // webfinger JRD - object, json, and our own indexing object: parsedJRD, json: JRD, idx: {} }; result.idx.properties = { 'name': undefined }; result.idx.links = JSON.parse(JSON.stringify(LINK_PROPERTIES)); // process links links.map(function (link, i) { if (LINK_URI_MAPS.hasOwnProperty(link.rel)) { if (result.idx.links[LINK_URI_MAPS[link.rel]]) { var entry = {}; Object.keys(link).map(function (item, n) { entry[item] = link[item]; }); result.idx.links[LINK_URI_MAPS[link.rel]].push(entry); } } }); // process properties var props = JSON.parse(JRD).properties; for (var key in props) { if (props.hasOwnProperty(key)) { if (key === 'http://packetizer.com/ns/name') { result.idx.properties.name = props[key]; } } } cb(null, result); }; WebFinger.prototype.lookup = function (address, cb) { if (typeof address !== 'string') { throw new Error('first parameter must be a user address'); } else if (typeof cb !== 'function') { throw new Error('second parameter must be a callback'); } var self = this; var parts = address.replace(/ /g,'').split('@'); var host = parts[1]; // host name for this useraddress var uri_index = 0; // track which URIS we've tried already var protocol = 'https'; // we use https by default if (parts.length !== 2) { cb(_err({ message: 'invalid user address ' + address + ' ( expected format: user@host.com )' })); return false; } else if (self._isLocalhost(host)) { protocol = 'http'; } function _buildURL() { return protocol + '://' + host + '/.well-known/' + URIS[uri_index] + '?resource=acct:' + address; } // control flow for failures, what to do in various cases, etc. function _fallbackChecks(err) { if ((self.config.uri_fallback) && (host !== 'webfist.org') && (uri_index !== URIS.length - 1)) { // we have uris left to try uri_index = uri_index + 1; _call(); } else if ((!self.config.tls_only) && (protocol === 'https')) { // try normal http uri_index = 0; protocol = 'http'; _call(); } else if ((self.config.webfist_fallback) && (host !== 'webfist.org')) { // webfist attempt uri_index = 0; protocol = 'http'; host = 'webfist.org'; // webfist will // 1. make a query to the webfist server for the users account // 2. from the response, get a link to the actual webfinger json data // (stored somewhere in control of the user) // 3. make a request to that url and get the json // 4. process it like a normal webfinger response self._fetchJRD(_buildURL(), function (err, data) { // get link to users JRD if (err) { cb(err); return false; } self._processJRD(data, function (err, result) { if ((typeof result.idx.links.webfist === 'object') && (typeof result.idx.links.webfist[0].href === 'string')) { self._fetchJRD(result.idx.links.webfist[0].href, function (err, JRD) { if (err) { cb(err); } else { self._processJRD(JRD, cb); } }); } }); }); } else { cb(err); return false; } } function _call() { // make request self._fetchJRD(_buildURL(), function (err, JRD) { if (err) { _fallbackChecks(err); } else { self._processJRD(JRD, cb); } }); } setTimeout(_call, 0); }; WebFinger.prototype.lookupLink = function (address, rel, cb) { if (LINK_PROPERTIES.hasOwnProperty(rel)) { this.lookup(address, function (err, p) { var links = p.idx.links[rel]; if (err) { cb (err); } else if (links.length === 0) { cb ('no links found with rel="' + rel + '"'); } else { cb (null, links[0]); } }); } else { cb ('unsupported rel ' + rel); } }; if (typeof window === 'object') { window.WebFinger = WebFinger; } else if (typeof (define) === 'function' && define.amd) { define([], function () { return WebFinger; }); } else { try { module.exports = WebFinger; } catch (e) {} } })(); /** FILE: src/authorize.js **/ (function (global) { function extractParams(url) { //FF already decodes the URL fragment in document.location.hash, so use this instead: var location = url || RemoteStorage.Authorize.getLocation().href, hashPos = location.indexOf('#'), hash; if (hashPos === -1) { return; } hash = location.substring(hashPos+1); // if hash is not of the form #key=val&key=val, it's probably not for us if (hash.indexOf('=') === -1) { return; } return hash.split('&').reduce(function (m, kvs) { var kv = kvs.split('='); m[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]); return m; }, {}); } RemoteStorage.ImpliedAuth = function (storageApi, redirectUri) { RemoteStorage.log('ImpliedAuth proceeding due to absent authURL; storageApi = ' + storageApi + ' redirectUri = ' + redirectUri); // Set a fixed access token, signalling to not send it as Bearer remoteStorage.remote.configure({ token: RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN }); document.location = redirectUri; }; RemoteStorage.Authorize = function (authURL, scope, redirectUri, clientId) { RemoteStorage.log('[Authorize] authURL = ', authURL, 'scope = ', scope, 'redirectUri = ', redirectUri, 'clientId = ', clientId); var url = authURL, hashPos = redirectUri.indexOf('#'); url += authURL.indexOf('?') > 0 ? '&' : '?'; url += 'redirect_uri=' + encodeURIComponent(redirectUri.replace(/#.*$/, '')); url += '&scope=' + encodeURIComponent(scope); url += '&client_id=' + encodeURIComponent(clientId); if (hashPos !== -1) { url += '&state=' + encodeURIComponent(redirectUri.substring(hashPos+1)); } url += '&response_type=token'; if (global.cordova) { return RemoteStorage.Authorize.openWindow( url, redirectUri, 'location=yes,clearsessioncache=yes,clearcache=yes' ) .then(function(authResult) { remoteStorage.remote.configure({ token: authResult.access_token }); // TODO // sync doesn't start until after reload // possibly missing some initialization step? global.location.reload(); }) .then(null, function(error) { console.error(error); remoteStorage.widget.view.setState('initial'); }); } RemoteStorage.Authorize.setLocation(url); }; RemoteStorage.Authorize.IMPLIED_FAKE_TOKEN = false; RemoteStorage.prototype.authorize = function (authURL, cordovaRedirectUri) { this.access.setStorageType(this.remote.storageType); var scope = this.access.scopeParameter; var redirectUri = global.cordova ? cordovaRedirectUri : String(RemoteStorage.Authorize.getLocation()); var clientId = redirectUri.match(/^(https?:\/\/[^\/]+)/)[0]; RemoteStorage.Authorize(authURL, scope, redirectUri, clientId); }; /** * Get current document location * * Override this method if access to document.location is forbidden */ RemoteStorage.Authorize.getLocation = function () { return global.document.location; }; /** * Set current document location * * Override this method if access to document.location is forbidden */ RemoteStorage.Authorize.setLocation = function (location) { if (typeof location === 'string') { global.document.location.href = location; } else if (typeof location === 'object') { global.document.location = location; } else { throw "Invalid location " + location; } }; /** * Open new InAppBrowser window for OAuth in Cordova */ RemoteStorage.Authorize.openWindow = function (url, redirectUri, options) { var pending = Promise.defer(); var newWindow = global.open(url, '_blank', options); if (!newWindow || newWindow.closed) { pending.reject('Authorization popup was blocked'); return pending.promise; } var handleExit = function () { pending.reject('Authorization was canceled'); }; var handleLoadstart = function (event) { if (event.url.indexOf(redirectUri) !== 0) { return; } newWindow.removeEventListener('exit', handleExit); newWindow.close(); var authResult = extractParams(event.url); if (!authResult) { return pending.reject('Authorization error'); } return pending.resolve(authResult); }; newWindow.addEventListener('loadstart', handleLoadstart); newWindow.addEventListener('exit', handleExit); return pending.promise; }; RemoteStorage.prototype.impliedauth = function () { RemoteStorage.ImpliedAuth(this.remote.storageApi, String(document.location)); }; RemoteStorage.Authorize._rs_supported = function () { return typeof(document) !== 'undefined'; }; var onFeaturesLoaded; RemoteStorage.Authorize._rs_init = function (remoteStorage) { onFeaturesLoaded = function () { var authParamsUsed = false; if (params) { if (params.error) { throw "Authorization server errored: " + params.error; } if (params.access_token) { remoteStorage.remote.configure({ token: params.access_token }); authParamsUsed = true; } if (params.remotestorage) { remoteStorage.connect(params.remotestorage); authParamsUsed = true; } if (params.state) { RemoteStorage.Authorize.setLocation('#'+params.state); } } if (!authParamsUsed) { remoteStorage.remote.stopWaitingForToken(); } }; var params = extractParams(), location; if (params) { location = RemoteStorage.Authorize.getLocation(); location.hash = ''; } remoteStorage.on('features-loaded', onFeaturesLoaded); }; RemoteStorage.Authorize._rs_cleanup = function (remoteStorage) { remoteStorage.removeEventListener('features-loaded', onFeaturesLoaded); }; })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/access.js **/ (function(global) { var SETTINGS_KEY = "remotestorage:access"; /** * Class: RemoteStorage.Access * * Keeps track of claimed access and scopes. */ RemoteStorage.Access = function() { this.reset(); }; RemoteStorage.Access.prototype = { /** * Method: claim * * Claim access on a given scope with given mode. * * Parameters: * scope - An access scope, such as "contacts" or "calendar" * mode - Access mode. Either "r" for read-only or "rw" for read/write * * Example: * (start code) * remoteStorage.access.claim('contacts', 'r'); * remoteStorage.access.claim('pictures', 'rw'); * (end code) * * Root access: * Claiming root access, meaning complete access to all files and folders * of a storage, can be done using an asterisk: * * (start code) * remoteStorage.access.claim('*', 'rw'); * (end code) */ claim: function(scope, mode) { if (typeof(scope) !== 'string' || scope.indexOf('/') !== -1 || scope.length === 0) { throw new Error('Scope should be a non-empty string without forward slashes'); } if (!mode.match(/^rw?$/)) { throw new Error('Mode should be either \'r\' or \'rw\''); } this._adjustRootPaths(scope); this.scopeModeMap[scope] = mode; }, get: function(scope) { return this.scopeModeMap[scope]; }, remove: function(scope) { var savedMap = {}; var name; for (name in this.scopeModeMap) { savedMap[name] = this.scopeModeMap[name]; } this.reset(); delete savedMap[scope]; for (name in savedMap) { this.set(name, savedMap[name]); } }, /** * Verify permission for a given scope. */ checkPermission: function(scope, mode) { var actualMode = this.get(scope); return actualMode && (mode === 'r' || actualMode === 'rw'); }, /** * Verify permission for a given path. */ checkPathPermission: function(path, mode) { if (this.checkPermission('*', mode)) { return true; } return !!this.checkPermission(this._getModuleName(path), mode); }, reset: function() { this.rootPaths = []; this.scopeModeMap = {}; }, /** * Return the module name for a given path. */ _getModuleName: function(path) { if (path[0] !== '/') { throw new Error('Path should start with a slash'); } var moduleMatch = path.replace(/^\/public/, '').match(/^\/([^\/]*)\//); return moduleMatch ? moduleMatch[1] : '*'; }, _adjustRootPaths: function(newScope) { if ('*' in this.scopeModeMap || newScope === '*') { this.rootPaths = ['/']; } else if (! (newScope in this.scopeModeMap)) { this.rootPaths.push('/' + newScope + '/'); this.rootPaths.push('/public/' + newScope + '/'); } }, _scopeNameForParameter: function(scope) { if (scope.name === '*' && this.storageType) { if (this.storageType === '2012.04') { return ''; } else if (this.storageType.match(/remotestorage-0[01]/)) { return 'root'; } } return scope.name; }, setStorageType: function(type) { this.storageType = type; } }; /** * Property: scopes * * Holds an array of claimed scopes in the form * > { name: "<scope-name>", mode: "<mode>" } */ Object.defineProperty(RemoteStorage.Access.prototype, 'scopes', { get: function() { return Object.keys(this.scopeModeMap).map(function(key) { return { name: key, mode: this.scopeModeMap[key] }; }.bind(this)); } }); Object.defineProperty(RemoteStorage.Access.prototype, 'scopeParameter', { get: function() { return this.scopes.map(function(scope) { return this._scopeNameForParameter(scope) + ':' + scope.mode; }.bind(this)).join(' '); } }); // Documented in src/remotestorage.js Object.defineProperty(RemoteStorage.prototype, 'access', { get: function() { var access = new RemoteStorage.Access(); Object.defineProperty(this, 'access', { value: access }); return access; }, configurable: true }); RemoteStorage.Access._rs_init = function() {}; })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/env.js **/ (function (pMode) { var mode = pMode, env = {}, isBackground = false; RemoteStorage.Env = function () { return env; }; RemoteStorage.Env.isBrowser = function () { return mode === "browser"; }; RemoteStorage.Env.isNode = function () { return mode === "node"; }; RemoteStorage.Env.goBackground = function () { isBackground = true; RemoteStorage.Env._emit("background"); }; RemoteStorage.Env.goForeground = function () { isBackground = false; RemoteStorage.Env._emit("foreground"); }; RemoteStorage.Env._rs_init = function (remoteStorage) { RemoteStorage.eventHandling(RemoteStorage.Env, "background", "foreground"); function visibility() { if (document[env.hiddenProperty]) { RemoteStorage.Env.goBackground(); } else { RemoteStorage.Env.goForeground(); } } if ( mode === 'browser') { if ( typeof(document.hidden) !== "undefined" ) { env.hiddenProperty = "hidden"; env.visibilityChangeEvent = "visibilitychange"; } else if ( typeof(document.mozHidden) !== "undefined" ) { env.hiddenProperty = "mozHidden"; env.visibilityChangeEvent = "mozvisibilitychange"; } else if ( typeof(document.msHidden) !== "undefined" ) { env.hiddenProperty = "msHidden"; env.visibilityChangeEvent = "msvisibilitychange"; } else if ( typeof(document.webkitHidden) !== "undefined" ) { env.hiddenProperty = "webkitHidden"; env.visibilityChangeEvent = "webkitvisibilitychange"; } document.addEventListener(env.visibilityChangeEvent, visibility, false); visibility(); } }; RemoteStorage.Env._rs_cleanup = function (remoteStorage) { }; })(typeof(window) !== 'undefined' ? 'browser' : 'node'); /** FILE: src/i18n.js **/ (function () { /** * Class: RemoteStorage.I18n * * TODO add documentation **/ "use strict"; var dictionary = { "view_info": 'This app allows you to use your own storage. <a href="http://remotestorage.io/" target="_blank">Learn more!</a>', "view_connect": "<strong>Connect</strong> remote storage", "view_connecting": "Connecting <strong>%s</strong>", "view_offline": "Offline", "view_error_occured": "Sorry! An error occured.", "view_invalid_key": "Wrong key!", "view_confirm_reset": "Are you sure you want to reset everything? This will clear your local data and reload the page.", "view_get_me_out": "Get me out of here!", "view_error_plz_report": 'If this problem persists, please <a href="http://remotestorage.io/community/" target="_blank">let us know</a>!', "view_unauthorized": "Unauthorized! Click here to reconnect." }; RemoteStorage.I18n = { translate: function () { var str = arguments[0], params = Array.prototype.splice.call(arguments, 1); if (typeof dictionary[str] !== "string") { throw "Unknown translation string: " + str; } else { str = dictionary[str]; } return (str.replace(/%s/g, function (){ return params.shift(); })); }, getDictionary: function () { return dictionary; }, setDictionary: function (newDictionary) { dictionary = newDictionary; } }; })(); /** FILE: src/assets.js **/ /** THIS FILE WAS GENERATED BY build/compile-assets.js. DO NOT CHANGE IT MANUALLY, BUT INSTEAD CHANGE THE ASSETS IN assets/. **/ RemoteStorage.Assets = { cipherIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTQiIHdpZHRoPSIyNS4xNzciIHZlcnNpb249IjEuMSIgeG1sbnM6Y2M9Imh0dHA6Ly9jcmVhdGl2ZWNvbW1vbnMub3JnL25zIyIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxwYXRoIGQ9Im0yNS4xNzcgNS41MzIzYy0wLjA1NjQtMC4xMTI5MS0wLjA1NjQtMC4yMjU4MS0wLjE2OTM2LTAuMzM4NzEtMC4xMTI5LTAuMTEyOS0wLjI4MjI1LTAuMTY5MzYtMC4zOTUxNi0wLjE2OTM2aC0xMS40MDNjLTAuNzMzLTIuODc5LTMuMzg2NC01LjAyNDItNi40OTEzLTUuMDI0Mi0zLjY2OTMgMC02LjcxNzcgMy4wNDg0LTYuNzE3NyA2LjcxNzcgMCAzLjcyNjMgMy4wNDg0IDYuNzE3MyA2LjcxNzcgNi43MTczIDMuMzMwNyAwIDYuMDQwMy0yLjQyNzQgNi42MDQ4LTUuNTg4N2gyLjU0MDN2My42Njk0YzAgMC4yODIyNiAwLjI4MjI2IDAuNTA4MDYgMC41NjQ1MiAwLjUwODA2aDEuNzVjMC4yODIyNiAwIDAuNTY0NTItMC4yMjU4IDAuNTY0NTItMC41MDgwNnYtMy42Njk0aDEuNDY3N3Y1LjY0NTJjMCAwLjI4MjI1IDAuMjI1OCAwLjUwODA2IDAuNTA4MDYgMC41MDgwNmgxLjgwNjRjMC4yODIyNiAwIDAuNTA4MDctMC4yMjU4MSAwLjU2NDUyLTAuNTA4MDZ2LTUuNjQ1MmgxLjUyNDJjMC4xMTI5MSAwIDAuMjgyMjYgMCAwLjM5NTE2LTAuMTEyOSAwLjExMjkxLTAuMTEyOSAwLjE2OTM2LTAuMjgyMjYgMC4xNjkzNi0wLjM5NTE2di0xLjgwNjR6bS0xOC40NTkgNS4wODA3Yy0yLjA4ODcgMC0zLjgzODctMS42OTM2LTMuODM4Ny0zLjgzODcgMC0yLjE0NTIgMS43NS0zLjgzODcgMy44Mzg3LTMuODM4NyAyLjE0NTIgMCAzLjgzODcgMS42OTM2IDMuODM4NyAzLjgzODcgMCAyLjE0NTItMS42OTM2IDMuODM4Ny0zLjgzODcgMy44Mzg3eiIgZmlsbD0iI2ZmZiIvPgo8L3N2Zz4K', connectIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCAtMTAzNi40KSI+CiAgPHBhdGggZD0ibTEgMTA0Ny40di02aDd2LTRsNyA3LTcgN3YtNHoiIGZpbGw9IiNmZmYiLz4KIDwvZz4KPC9zdmc+Cg==', disconnectIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4wIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxwYXRoIHN0eWxlPSJibG9jay1wcm9ncmVzc2lvbjp0Yjt0ZXh0LWluZGVudDowO2NvbG9yOiMwMDAwMDA7dGV4dC10cmFuc2Zvcm06bm9uZSIgZD0ibTguMDAwMSAwYy0wLjQ3MTQgMC0wLjk2MTAzIDAuNTQxOS0wLjk1IDF2NmMtMC4wMDc0NyAwLjUyODMxIDAuNDIxNjMgMSAwLjk1IDFzMC45NTc0Ny0wLjQ3MTY5IDAuOTUtMXYtNmMwLjAxNDYyMi0wLjYwNTEtMC40Nzg2LTEtMC45NS0xem0tMy4zNDM4IDIuNWMtMC4wODcxODYgMC4wMTkyOTQtMC4xNzE2MyAwLjA1MDk1OS0wLjI1IDAuMDkzNzUtMi45OTk1IDEuNTcxNS0zLjkxODQgNC43OTc5LTMuMTI1IDcuNDY4OCAwLjc5MzQgMi42NyAzLjI3OTkgNC45MzcgNi42ODc1IDQuOTM3IDMuMzU5MiAwIDUuODc3Mi0yLjE0OSA2LjcxOTItNC43ODEgMC44NDEtMi42MzIxLTAuMDU4LTUuODIzNC0zLjEyNS03LjU5NC0wLjQzNC0wLjI1MzYtMS4wNTktMC4wODk5LTEuMzEzIDAuMzQzNy0wLjI1MzYgMC40MzM2LTAuMDkgMS4wNTg5IDAuMzQ0IDEuMzEyNSAyLjM5MDggMS4zNzk4IDIuODgyNSAzLjQ5NDQgMi4yODEyIDUuMzc1LTAuNjAxMiAxLjg4MDYtMi4zNDQgMy40Mzc1LTQuOTA2MiAzLjQzNzUtMi41NzU5IDAtNC4yOTc2LTEuNjUwMi00Ljg3NS0zLjU5MzgtMC41Nzc2LTEuOTQzNS0wLjA0Ny00LjA0OCAyLjE4NzMtNS4yMTg3IDAuMzc4Ny0wLjIwNjMgMC41NzkxLTAuNjkyNSAwLjQ1NTgtMS4xMDU3LTAuMTIzMi0wLjQxMzMtMC41NTcyLTAuNzEwMy0wLjk4Ny0wLjY3NTUtMC4wMzEzLTAuMDAxNS0wLjA2MjYtMC4wMDE1LTAuMDkzOCAweiIgZmlsbD0iI2ZmZiIvPgo8L3N2Zz4K', dropbox: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgPEBAhEOpfuQAABhZJREFUWMPVl31snVUdxz+/5/2577e3b7QbHaOD0nXshW4ZZkpGQmJYZkJUDAaZzCBGAxGd+pdZQsJIjCaKgFu09GWybIggm8yhMCsY92rcOkPHunbdtKOUbX36svX23uc+xz+eDsrWlztiNJzk5D7JPS+fc8739/2dA5+EsqJtyK18ZlCKbX9Lk6fd1uo5xbTVZmtwa4v35Np5Mry4TLYXCzAnyhsry2SwrmnokdnaTruq6i3e0lXl0tqQlkURCxwdDp9Th5p3+p9iS8afqk/VZq9kaZoDN8apdU3B1KFnmLde7AkezH0n3V0UQOJpz2hIsqEhLU+WOeAagmtCxISYBe1nVf4vfWrByYdSpyf3W9ziLapy6JgbAduAiBn2S1rCQBYODAQP7H01/zxby4JpAW5s8mproxypiRKNGIJrQNT8EMA1wTGEU8MBP/q7umPw0dSbAA3N3n3zI2yLG2oScPgbNYWICY4Be86o/le6g0W576bPXQWwcqvXdJ2t1idMsA1hJoCoCRfGYdOhwsa4TUWFrr7pGmDrzAiQCHfD//Xxwk/33Z/6HoA0tnhLXZ3XMoYqsy4PYs4M4Ohg6pB2ddqO+vR6BWL27AARXbBNiBjwh9Oqs+O8ukcT4eaopjLqGsJSCdSX29SX23x/lctXlzgE1zBAANxWIQuGxlWNACxr8WozJp0lljKsGXbA0qGu1GRBxsTUQRAGLgboIuQVvHI8S+f7eeK2TLsDSQd296rhPaeDm09+PdX/gQYqN3uZ+jh7ro+oRusKDdgmVEY1GqstSiOhdegCmoQAIoImIWTPYIHdXVlyBYhaVwLA70+rPz7fllvLi2W5KcPw9q3eS/VJ7kmYgm1A3BIWV5osq7IIlMLUQJOrAXQBXQtr1BR2d2XpOu8TtULR+gq2nQh+vv8rqUdnNaKGZm/9qnJpmp/U+fxCB5lYsaGFdTYAY9L3jmNj9F9S7OgKVh9/KNVelBVf8untv8TYSS8gbsrHyh8C2LqQtGE0z9CJYfVuUblgRZv3WGOJvJG0cF8/lWPNdo+O93xsHYoVuqkL/xzIs/HPHt2DPg0Zko+v0I8vbfHun9aKE5sH9YaobJsf5V4mRLXv33kSlmAYwspqgw23R7A1EJlahKYOSsHTB0cZHQ9IOBA3NSrjGo4hWAY82xH8rH1b/jF2laoPAOb80jPqYtKTMdRcTQNd+xAgbgmuJbiGELfh3lsc7q41KQSTABBcC1qPjLH/XzniNqScsP1kgMsm9nJ34e2mNcmFAMby1qFPZyz1WlxXrprhuEUgUPDbd8Y59n6edbe61KZ1TF14vSfPLw5dYjhXIOMIM6lGAV+u0+tv+ttI/2+6/LsMQVXpUFCAqJkS9MT5anB2NGDjWxf5Yp3DvjN5th/LUhETolaRTqigxMGIWVKtHVyX2tGTJd2X5agUIfi8CmvUFOKGT++gT8wqLlKUgnwATxwq7P32m35Z+32pPQZA54MpH1iSb/XWZmx2VthTD1AATCBlCZ+dpwNg6EJjlUH3hQIKRaCujhZFaOPtfUH+8HvBnQceSP11yjA8vC616+A5FevL8jt/YiCR0HiQcAUVrnDHHO0jHTUNllXrpC0NRXiefjAxM4rhHLzQpZqf+eFFd/LkM17JGlu9p+xC8IgPhGlaqE1rNJZrxOzQok0dnjviY+nhbSntCH3DAWN+QMIWEhYsqTD4wYHChrPfSP9kqnmM6QAMkYtz4xqmDqeGA+rLNObGZVozkglx1ZfqZAvC2ZGAz9RYlEbAlsLoNd+Kx5RqO5/njKXDsnKdhCXFOaFAZUzjznlhyt5xIjiSLbBz2oVO98fRdalOoGZ5m/dUQ4pvJZ3Zr/CXlS5A74gabzlYePztr6U2faxr+eRy/RYvtjgjHauvkxvi9oTDXaGBuAUJWyh1hb3vqsOvfiG5/L/yMAE483BqdNeuXO3LvcGX3vEUhsZVsaYL9IzACz3BXcVOXvQOfKRsupBZv8R4bnW19rmqGPzqHz4BcMGn5U/Hgod5oiT3P3kvVj7rrfnx/pHBu7d7Azc1eY3/l0drzWbPXNjsGXySy38AbtMqneWU7BkAAAAASUVORK5CYII=', googledrive: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgPEA85ztzJcQAABZVJREFUWMPtl1uoXVcVhr8x5tprn7M1NG1i0pQqSG2jLcXipYJXjPogqFgpaHMSFUkpIjU+leKbDxIQSiHgjZgmrfXgQ6SKj5Ji7YVS05aUUqKQlNLQeDnN5Zzk9Jy99xy/D3OttU/StDlV33TBZM3FXmuMf/5jjv+fG/7XL1vti9tnv3Dtnnf+87JY8YmZNxEMM1sZ7tWpjz764mriVqvKvmfb1ONLy3+dGyWu6EWbvQwoydv5BMSqFuereakmfnls1GP25IDaBGYYjplhljDz5tk7YMtPfurAf6UE9Z6tNwDPAPXwtcxL1x9n4zRgDjjm1gCyC6JpCLoW/OX65of1nzCwG6gNo3aYeXF981mTvK2/WWFiMmoj7X+z5JcE0N87c4e7b3EvyTwZT5/r8ezZHu6GuWGpSegJ8/ZeBu6fHv35s1/7t0rQv29mjWF/ATZ1L4bQwohrpkYc/sBpwhJYAVdKYECzYAESIk4Am3sf+sPCW2LAzb9jbpvMDXfD3fEqkRIcGdbsevlt9LylPYG1K6/K3QzK75uAr78lBgb3b7sc2cl2Uaa21sDiGMvB2iQeu/EMm6bKHjD3SUsCEChnpEAKiLisd/PB+UsyMPjZNwzzh1ixcnOfsFCX51NU/PTvA6pkTUdYw4R3zyu1ArMDqyvBQB82+FiJUQJ4C8YgVT1SSvSTs+vEmkcwe7qEsUnt233Aij0BW4ZPbfngKpRQs7hXpYQNvRiuEtATWOW4bLi+z04pJbCnBAkBJggBQlIBIZCUJM0Cm9+QgcED2+/G7BprdMZaAFZExm1FWcz+NLdj32G/6XfPCB5GoJKp7H5FARHRtgRI1y0/+cm7Lwpg+v7t64DvNd5S2mqirKXHy6RoArp1Ykrc2hKtKCtXlNEyoQ6Ydi498fF1F2FAdwEbV9UnZne+8q19Z7o63vTb+TPnRneeWxwxHGdyziii6wApQNEydKUUd5wHYGrftvci7tKKLSME5bvCaruynI9rNL7vdZgiHhiP898Wl8bMnxty+uyIhcURo1FgjSg1DCDph4uPfuR9AFbvvS25p2cxbiyKVuh2o1O44n2lLLacb5v75v5fX6yl5h753IwUD+YcRAQ5B6FMMhj0jboSRhnAE258wvp7Z7aYcbCYCeCGt97ubfICLDP/q4WZ32x7M20fPfb+hxbH9ZdjHOQIIoR74EDywA3coa6MqtJnrP+LmRmcB63ob8dA1wllRm95LVc//22S16TGeKqqpqoHk10ESGJj/zjjgIhAISKCyJmcY6Uu8Pbq7C0V6ABh35dzvYWQG0QAhmSYCaUlNhzdCrlX2jpE6tV4b9DYcGFKEgG8svQucoicC4CsII8zeTxutAEQzx1duPL3vrxjdlnou0SDLdTulxJQmalXNzN98jpEJiSo+qTeoEnsnWC5lVZNRhkOZiq0G8XCmz1gpp3j/ZYdYLhj9qCkn3fJQ4QKeh9OccWxz6O0hGKM9wakeoBEZ1BmqfOMyYFk4gXS+edG4J4ju6/644VK+AOJhSIYpVRBpn/qPVRL65A51dRavJoG2UQkOqf0hgVrGG7u6syoJDObB+55nRANb589Afy40W0UwkY91h39CiLweg1UU+W3ohLNvC2VurJ1htR6A3QaYPCjI7uvOvGGOlfv2XoSuBzEhmNfZXDqBrweUPVqUlWodneSG+6J1NTevThfDpEjmnsmzuuCPPfCvRvfcakT0S2Aeq9tYPr0ZryeBvOOlZBKUIEiCAVZwTgy41x6v6hm0LFZ4o7N7IuXPA+EDx+XjQ+tP/4lUrW2vCI1ydR0iYgmWdtu4yzG7bOiAdn8iYlA0iFJh1Z1JJv+ye2b3n1419XRH2riP0aqqlKClABIjUMW+rtSlw5qmCpgsynnl56/d+M/+P91wfUvQjDgTzx9h9AAAAAASUVORK5CYII=', nocipherIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMTYiIHdpZHRoPSIxNiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iPgogPHBhdGggZD0ibSAxMy4yMDMxMjQsMTEuNzczNDM4IGMgMC4yODEyNSwwLjI4MTI1IDAuNDIxODc1LDAuNjA5Mzc1IDAuNDIxODc1LDEuMDMxMjUgMCwwLjM3NSAtMC4xNDA2MjUsMC43NSAtMC40MjE4NzUsMS4wMzEyNSAtMC4yODEyNSwwLjIzNDM3NSAtMC42MDkzNzUsMC4zNzUgLTEuMDMxMjUsMC4zNzUgLTAuMzc1LDAgLTAuNzUsLTAuMTQwNjI1IC0xLjAzMTI1LC0wLjM3NSAwLDAgLTMuMTg3NDk4MSwtMy42NTYyNSAtMy4xODc0OTgxLC0zLjY1NjI1IDAsMCAtMy4xNDA2MjUsMy42NTYyNSAtMy4xNDA2MjUsMy42NTYyNSAtMC4yODEyNSwwLjIzNDM3NSAtMC42NTYyNSwwLjM3NSAtMS4wMzEyNSwwLjM3NSAtMC40MjE4NzUsMCAtMC43NSwtMC4xNDA2MjUgLTEuMDMxMjUsLTAuMzc1IC0wLjI4MTI1LC0wLjI4MTI1IC0wLjM3NSwtMC42NTYyNSAtMC4zNzUsLTEuMDMxMjUgMCwtMC40MjE4NzUgMC4wOTM3NSwtMC43NSAwLjM3NSwtMS4wMzEyNSAwLDAgMy4zMjgxMjUsLTMuNzUwMDAwNSAzLjMyODEyNSwtMy43NTAwMDA1IDAsMCAtMy4zMjgxMjUsLTMuNzk2ODc1IC0zLjMyODEyNSwtMy43OTY4NzUgLTAuMjgxMjUsLTAuMjgxMjUgLTAuMzc1LC0wLjYwOTM3NSAtMC4zNzUsLTEuMDMxMjUgMCwtMC4zNzUgMC4wOTM3NSwtMC43NSAwLjM3NSwtMS4wMzEyNSAwLjI4MTI1LC0wLjIzNDM3NSAwLjYwOTM3NSwtMC4zNzUgMS4wMzEyNSwtMC4zNzUgMC4zNzUsMCAwLjc1LDAuMTQwNjI1IDEuMDMxMjUsMC4zNzUgMCwwIDMuMTQwNjI1LDMuNjU2MjUgMy4xNDA2MjUsMy42NTYyNSAwLDAgMy4xODc0OTgxLC0zLjY1NjI1IDMuMTg3NDk4MSwtMy42NTYyNSAwLjI4MTI1LC0wLjIzNDM3NSAwLjY1NjI1LC0wLjM3NSAxLjAzMTI1LC0wLjM3NSAwLjQyMTg3NSwwIDAuNzUsMC4xNDA2MjUgMS4wMzEyNSwwLjM3NSAwLjI4MTI1LDAuMjgxMjUgMC40MjE4NzUsMC42NTYyNSAwLjQyMTg3NSwxLjAzMTI1IDAsMC40MjE4NzUgLTAuMTQwNjI1LDAuNzUgLTAuNDIxODc1LDEuMDMxMjUgMCwwIC0zLjMyODEyMzEsMy43OTY4NzUgLTMuMzI4MTIzMSwzLjc5Njg3NSAwLDAgMy4zMjgxMjMxLDMuNzUwMDAwNSAzLjMyODEyMzEsMy43NTAwMDA1IiBmaWxsPSIjZmZmIi8+Cjwvc3ZnPgo=', remoteStorageIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2ZmNGEwNCIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZmY0YTA0IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==', remoteStorageIconCiphered: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2ZmNGEwNCIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZmY0YTA0IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xNiAwbDAuMTI1IDYuMzc1YzIuMDk4IDAuMDY3IDMuNzUgMS43NTk1IDMuNzUgMy44NzV2MS45NjloMS45MzcgMC4wMzJsOC00LjIxOS0xMy44NDQtOHpsLTEzLjg0NCA4IDggNC4yMTloMC4wMzIgMS45MDZ2LTEuOTY5YzAtMi4xMTU1IDEuNjgzLTMuODA4IDMuNzgxLTMuODc1bDAuMTI1LTYuMzc1em0tMTMuODQ0IDh2MTZsNy45OTk4LTQuODQ0di02LjA5NGwtNy45OTk4LTUuMDYyem0wIDE2bDEzLjg0NCA4LTAuMzc1LTEwLjA2MmgtNS40Njl2LTIuMzQ0bC03Ljk5OTggNC40MDZ6bTEzLjg0NCA4bDEzLjg0NC04LTgtNC40MDZ2Mi4zNDRoLTUuNDY5bC0wLjM3NSAxMC4wNjJ6bTEzLjg0NC04di0xNmwtOCA1LjA2MnY2LjA5NGw4IDQuODQ0em0tMTMuOTY5LTE3Yy0xLjczNSAwLjA2NjYtMy4xMjUgMS40OTg3LTMuMTI1IDMuMjV2MS45NjloMy4wMzFsMC4wOTQtNS4yMTl6bTAuMjUgMGwwLjA5NCA1LjIxOWgzLjAzMXYtMS45NjljMC0xLjc1MTMtMS4zOS0zLjE4MzQtMy4xMjUtMy4yNXptLTQuNzUgNS44NDRsNC4zNDQgMi4yODEgMC4wMzEtMi4yODFoLTQuMzc1em00Ljg3NSAwbDAuMDMxIDIuMjgxIDQuMzQ0LTIuMjgxaC00LjM3NXptLTUuNDM4IDAuNjI1djUuMzEybDQuMjgyLTIuNTkzLTQuMjgyLTIuNzE5em0xMC4zNzYgMGwtNC4yODIgMi43MTkgNC4yODIgMi41OTN2LTUuMzEyem0tNS43ODIgMy4yMTlsLTQuNTk0IDIuNTMxdjIuMDYyaDQuNzgybC0wLjE4OC00LjU5M3ptMS4xODggMGwtMC4xODggNC41OTNoNC43ODJ2LTIuMDYybC00LjU5NC0yLjUzMXoiIGZpbGw9InVybCgjYSkiLz4KPC9zdmc+Cg==', remoteStorageIconError: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iI2U5MDAwMCIgc3RvcC1vcGFjaXR5PSIuNzYwNzgiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjZTkwMDAwIiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==', remoteStorageIconOffline: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMzIiIHdpZHRoPSIzMiIgdmVyc2lvbj0iMS4xIiB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeG1sbnM6ZGM9Imh0dHA6Ly9wdXJsLm9yZy9kYy9lbGVtZW50cy8xLjEvIj4KIDxkZWZzPgogIDxyYWRpYWxHcmFkaWVudCBpZD0iYSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiIGN5PSI1NzEuNDIiIGN4PSIxMDQ2LjUiIGdyYWRpZW50VHJhbnNmb3JtPSJtYXRyaXgoLjE0NDMzIDAgMCAuMTY2NjcgMTIwMS41IDg3Ny4xMSkiIHI9Ijk2Ij4KICAgPHN0b3Agc3RvcC1jb2xvcj0iIzY5Njk2OSIgc3RvcC1vcGFjaXR5PSIuNzYxNTQiIG9mZnNldD0iMCIvPgogICA8c3RvcCBzdG9wLWNvbG9yPSIjNjc2NzY3IiBvZmZzZXQ9IjEiLz4KICA8L3JhZGlhbEdyYWRpZW50PgogPC9kZWZzPgogPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEzMzYuNiAtOTU2LjM1KSI+CiAgPHBhdGggc3R5bGU9ImNvbG9yOiMwMDAwMDAiIGQ9Im0xMzUyLjYgOTU2LjM1IDAuMjg4NiAxNS4xMzYgMTMuNTY3LTcuMTM1Mi0xMy44NTUtOC4wMDExemwtMTMuODU1IDguMDAxMSAxMy41NjcgNy4xMzUyIDAuMjg4Ny0xNS4xMzZ6bS0xMy44NTUgOC4wMDExdjE1Ljk5OGwxMi45NTgtNy44MTYyLTEyLjk1OC04LjE4MTV6bTAgMTUuOTk4IDEzLjg1NSA4LjAwMTEtMC42MDg5LTE1LjMxNy0xMy4yNDYgNy4zMTU2em0xMy44NTUgOC4wMDExIDEzLjg1NS04LjAwMTEtMTMuMjUxLTcuMzE1Ni0wLjYwNDQgMTUuMzE3em0xMy44NTUtOC4wMDExdi0xNS45OThsLTEyLjk2MiA4LjE4MTUgMTIuOTYyIDcuODE2MnoiIGZpbGw9InVybCgjYSkiLz4KIDwvZz4KPC9zdmc+Cg==', syncIcon: 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDg3LjUgMTAwIiB4bWw6c3BhY2U9InByZXNlcnZlIiBoZWlnaHQ9IjE2IiB2aWV3Qm94PSIwIDAgMTUuOTk5OTk5IDE2IiB3aWR0aD0iMTYiIHZlcnNpb249IjEuMSIgeT0iMHB4IiB4PSIwcHgiIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKC01LjUxMTIgLTc2LjUyNSkiIGRpc3BsYXk9Im5vbmUiPgoJPHBhdGggZGlzcGxheT0iaW5saW5lIiBkPSJtNTEuNDczIDQyLjI1NS0yLjIwNSAyLjIxMmMxLjQ3OCAxLjQ3NyAyLjI5NSAzLjQ0MiAyLjI5NSA1LjUzMyAwIDQuMzA5LTMuNTA0IDcuODEyLTcuODEyIDcuODEydi0xLjU2MmwtMy4xMjUgMy4xMjUgMy4xMjQgMy4xMjV2LTEuNTYyYzYuMDI5IDAgMTAuOTM4LTQuOTA2IDEwLjkzOC0xMC45MzggMC0yLjkyNy0xLjE0MS01LjY3Ni0zLjIxNS03Ljc0NXoiLz4KCTxwYXRoIGRpc3BsYXk9ImlubGluZSIgZD0ibTQ2Ljg3NSA0MC42MjUtMy4xMjUtMy4xMjV2MS41NjJjLTYuMDMgMC0xMC45MzggNC45MDctMTAuOTM4IDEwLjkzOCAwIDIuOTI3IDEuMTQxIDUuNjc2IDMuMjE3IDcuNzQ1bDIuMjAzLTIuMjEyYy0xLjQ3Ny0xLjQ3OS0yLjI5NC0zLjQ0Mi0yLjI5NC01LjUzMyAwLTQuMzA5IDMuNTA0LTcuODEyIDcuODEyLTcuODEydjEuNTYybDMuMTI1LTMuMTI1eiIvPgo8L2c+CjxwYXRoIGZpbGw9IiNmZmYiIGQ9Im0xMCAwbC0wLjc1IDEuOTA2MmMtMS4wMDc4LTAuMjk0Mi0zLjQ1ODYtMC43NzA4LTUuNjU2MiAwLjkzNzYgMC0wLjAwMDItMy45MzAyIDIuNTk0MS0yLjA5MzggNy41OTQybDEuNjU2Mi0wLjcxOTJzLTEuNTM5OS0zLjExMjIgMS42ODc2LTUuNTMxM2MwIDAgMS42OTU3LTEuMTMzOSAzLjY4NzQtMC41OTM3bC0wLjcxODcgMS44MTI0IDMuODEyNS0xLjYyNS0xLjYyNS0zLjc4MTJ6Ii8+PHBhdGggZmlsbD0iI2ZmZiIgZD0ibTE0IDUuNTYyNWwtMS42NTYgMC43MTg3czEuNTQxIDMuMTEzNS0xLjY4OCA1LjUzMDhjMCAwLTEuNzI3MiAxLjEzNS0zLjcxODUgMC41OTRsMC43NS0xLjgxMi0zLjgxMjUgMS41OTQgMS41OTM4IDMuODEyIDAuNzgxMi0xLjkwNmMxLjAxMTMgMC4yOTUgMy40NjE1IDAuNzY2IDUuNjU2LTAuOTM4IDAgMCAzLjkyOC0yLjU5NCAyLjA5NC03LjU5MzV6Ii8+Cjwvc3ZnPgo=', widget: '<div class="rs-bubble rs-hidden"> <div class="rs-bubble-text remotestorage-initial remotestorage-error remotestorage-authing remotestorage-offline"> <span class="rs-status-text">{{view_connect}}</span> </div> <div class="rs-bubble-expandable"> <!-- error --> <div class="remotestorage-error"> <pre class="rs-status-text rs-error-msg">{{ERROR_MSG}}</pre> <button class="remotestorage-reset">{{view_get_me_out}}</button> <p class="rs-centered-text rs-error-plz-report">{{view_error_plz_report}}</p> </div> <!-- connected --> <div class="rs-bubble-text remotestorage-connected"> <strong class="userAddress">{{USER_ADDRESS}}</strong> <p class="remotestorage-unauthorized">{{view_unauthorized}}</p> <p class="remotestorage-invalid-key">{{view_invalid_key}}</p> <form novalidate class="remotestorage-cipher-form"> <input placeholder="Secret key" name="userSecretKey" novalidate> <button class="rs-cipher" name="rs-cipher" title="cipher" disabled="disabled"> <img> </button> <button class="rs-nocipher" name="rs-nocipher" title="no cipher"> <img> </button> </form> </div> <div class="rs-content remotestorage-connected"> <button class="rs-sync" title="sync"><img></button> <button class="rs-disconnect" title="disconnect"><img></button> </div> <!-- initial --> <form novalidate class="remotestorage-initial"> <input type="email" placeholder="user@provider.com" name="userAddress" novalidate> <button class="connect" name="connect" title="connect" disabled="disabled"> <img> </button> </form> <div class="rs-info-msg remotestorage-initial">{{view_info}}</div> </div> </div> <img class="rs-dropbox rs-backends rs-action" alt="Connect to Dropbox"> <img class="rs-googledrive rs-backends rs-action" alt="Connect to Google Drive"> <img class="rs-cube rs-action"> ', widgetCss: '/** encoding:utf-8 **/ /* RESET */ #remotestorage-widget{text-align:left;}#remotestorage-widget input, #remotestorage-widget button{font-size:11px;}#remotestorage-widget form input[type=email]{margin-bottom:0;/* HTML5 Boilerplate */}#remotestorage-widget form input[type=submit]{margin-top:0;/* HTML5 Boilerplate */}/* /RESET */ #remotestorage-widget, #remotestorage-widget *{-moz-box-sizing:border-box;box-sizing:border-box;}#remotestorage-widget{position:absolute;right:10px;top:10px;font:normal 16px/100% sans-serif !important;user-select:none;-webkit-user-select:none;-moz-user-select:-moz-none;cursor:default;z-index:10000;}#remotestorage-widget .rs-bubble{background:rgba(80, 80, 80, .7);border-radius:5px 15px 5px 5px;color:white;font-size:0.8em;padding:5px;position:absolute;right:3px;top:9px;min-height:24px;white-space:nowrap;text-decoration:none;}.rs-bubble .rs-bubble-text{padding-right:32px;/* make sure the bubble doesn\'t "jump" when initially opening. */ min-width:182px;}#remotestorage-widget .rs-action{cursor:pointer;}/* less obtrusive cube when connected */ #remotestorage-widget.remotestorage-state-connected .rs-cube, #remotestorage-widget.remotestorage-state-busy .rs-cube{opacity:.3;-webkit-transition:opacity .3s ease;-moz-transition:opacity .3s ease;-ms-transition:opacity .3s ease;-o-transition:opacity .3s ease;transition:opacity .3s ease;}#remotestorage-widget.remotestorage-state-connected:hover .rs-cube, #remotestorage-widget.remotestorage-state-busy:hover .rs-cube, #remotestorage-widget.remotestorage-state-connected .rs-bubble:not(.rs-hidden) + .rs-cube{opacity:1 !important;}#remotestorage-widget .rs-backends{position:relative;top:5px;right:0;}#remotestorage-widget .rs-cube{position:relative;top:5px;right:0;}/* pulsing animation for cube when loading */ #remotestorage-widget .rs-cube.remotestorage-loading{-webkit-animation:remotestorage-loading .5s ease-in-out infinite alternate;-moz-animation:remotestorage-loading .5s ease-in-out infinite alternate;-o-animation:remotestorage-loading .5s ease-in-out infinite alternate;-ms-animation:remotestorage-loading .5s ease-in-out infinite alternate;animation:remotestorage-loading .5s ease-in-out infinite alternate;}@-webkit-keyframes remotestorage-loading{to{opacity:.7}}@-moz-keyframes remotestorage-loading{to{opacity:.7}}@-o-keyframes remotestorage-loading{to{opacity:.7}}@-ms-keyframes remotestorage-loading{to{opacity:.7}}@keyframes remotestorage-loading{to{opacity:.7}}#remotestorage-widget a{text-decoration:underline;color:inherit;}#remotestorage-widget form{margin-top:.7em;position:relative;}#remotestorage-widget form input{display:table-cell;vertical-align:top;border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:2em;}#remotestorage-widget form input:disabled{color:#999;background:#444 !important;cursor:default !important;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget form input[type=email], #remotestorage-widget form input[type=password]{background:#000;width:100%;height:26px;padding:0 30px 0 5px;border-top:1px solid #111;border-bottom:1px solid #999;}#remotestorage-widget form input[type=email]:focus, #remotestorage-widget form input[type=password]:focus{background:#223;}#remotestorage-widget button:focus, #remotestorage-widget input:focus{box-shadow:0 0 4px #ccc;}#remotestorage-widget form input[type=email]::-webkit-input-placeholder, #remotestorage-widget form input[type=password]::-webkit-input-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-moz-placeholder, #remotestorage-widget form input[type=password]:-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]::-moz-placeholder, #remotestorage-widget form input[type=password]::-moz-placeholder{color:#999;}#remotestorage-widget form input[type=email]:-ms-input-placeholder, #remotestorage-widget form input[type=password]:-ms-input-placeholder{color:#999;}#remotestorage-widget form input[type=submit]{background:#000;cursor:pointer;padding:0 5px;}#remotestorage-widget form input[type=submit]:hover{background:#333;}#remotestorage-widget .rs-info-msg{font-size:10px;color:#eee;margin-top:0.7em;white-space:normal;}#remotestorage-widget .rs-info-msg.last-synced-message{display:inline;white-space:nowrap;margin-bottom:.7em}#remotestorage-widget .rs-info-msg a:hover, #remotestorage-widget .rs-info-msg a:active{color:#fff;}#remotestorage-widget button img{vertical-align:baseline;}#remotestorage-widget button{border:none;border-radius:6px;font-weight:bold;color:white;outline:none;line-height:1.5em;height:26px;width:26px;background:#000;cursor:pointer;margin:0;padding:5px;}#remotestorage-widget button:hover{background:#333;}#remotestorage-widget .rs-bubble button.connect, #remotestorage-widget .rs-bubble button.rs-cipher, #remotestorage-widget .rs-bubble button.rs-nocipher{display:block;background:none;position:absolute;right:0;top:0;opacity:1;/* increase clickable area of connect, rs-cipher & rs-nocipher buttons */ margin:-5px;padding:10px;width:36px;height:36px;}#remotestorage-widget .rs-bubble button.rs-cipher{width:46px;}#remotestorage-widget .rs-bubble button.rs-nocipher{height:26px;margin:0;padding:4px 5px 5px;right:-32px;width:26px;}#remotestorage-widget .rs-bubble button.connect:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-cipher:not([disabled]):hover, #remotestorage-widget .rs-bubble button.rs-nocipher:not([disabled]):hover{background:rgba(150,150,150,.5);}#remotestorage-widget .rs-bubble button.connect[disabled], #remotestorage-widget .rs-bubble button.rs-cipher[disabled]{opacity:.5;cursor:default !important;}#remotestorage-widget .rs-bubble button.rs-sync{position:relative;left:-5px;bottom:-5px;padding:4px 4px 0 4px;background:#555;}#remotestorage-widget .rs-bubble button.rs-sync:hover{background:#444;}#remotestorage-widget .rs-bubble button.rs-disconnect{background:#721;position:absolute;right:0;bottom:0;padding:4px 4px 0 4px;}#remotestorage-widget .rs-bubble button.rs-disconnect:hover{background:#921;}#remotestorage-widget .remotestorage-error-info{color:#f92;}#remotestorage-widget .remotestorage-reset{width:100%;background:#721;}#remotestorage-widget .remotestorage-reset:hover{background:#921;}#remotestorage-widget .rs-bubble .rs-content{margin-top:7px;}#remotestorage-widget pre{user-select:initial;-webkit-user-select:initial;-moz-user-select:text;max-width:27em;margin-top:1em;overflow:auto;}#remotestorage-widget .rs-centered-text{text-align:center;}#remotestorage-widget .rs-bubble.rs-hidden{padding-bottom:2px;border-radius:5px 15px 15px 5px;}#remotestorage-widget .rs-error-msg{min-height:5em;}.rs-bubble.rs-hidden .rs-bubble-expandable{display:none;}.remotestorage-state-connected .rs-bubble.rs-hidden{display:none;}.remotestorage-connected{display:none;}.remotestorage-state-connected .remotestorage-connected{display:block;}.remotestorage-cipher-form{display:none;}.remotestorage-cipher .remotestorage-cipher-form{display:block;}.remotestorage-invalid-key{display:none;}.remotestorage-invalid-key.remotestorage-cipher-error{display:block;}.remotestorage-initial{display:none;}.remotestorage-state-initial .remotestorage-initial{display:block;}.remotestorage-error{display:none;}.remotestorage-state-error .remotestorage-error{display:block;}.remotestorage-state-authing .remotestorage-authing{display:block;}.remotestorage-state-offline .remotestorage-connected, .remotestorage-state-offline .remotestorage-offline{display:block;}.remotestorage-unauthorized{display:none;}.remotestorage-state-unauthorized .rs-bubble.rs-hidden{display:none;}.remotestorage-state-unauthorized .remotestorage-connected, .remotestorage-state-unauthorized .remotestorage-unauthorized{display:block;}.remotestorage-state-unauthorized .rs-sync{display:none;}.remotestorage-state-busy .rs-bubble.rs-hidden{display:none;}.remotestorage-state-busy .rs-bubble{display:block;}.remotestorage-state-busy .remotestorage-connected{display:block;}.remotestorage-state-authing .rs-bubble-expandable{display:none;}' }; /** FILE: src/widget.js **/ (function (window) { var hasLocalStorage; var LS_STATE_KEY = 'remotestorage:widget:state'; // states allowed to immediately jump into after a reload. var VALID_ENTRY_STATES = { initial: true, connected: true, offline: true }; /** * Class: RemoteStorage.Widget * * The widget controller that communicates with the view and listens to * its remoteStorage instance. * * While listening to the events emitted by its remoteStorage it sets * corresponding states of the view. * * - connected -> connected * - disconnected -> initial * - connecting -> authing * - authing -> authing * - wire-busy -> busy * - wire-done -> connected * - error -> one of initial, offline, unauthorized, or error **/ RemoteStorage.Widget = function (remoteStorage) { var self = this; var requestsToFlashFor = 0; // setting event listeners on rs events to put // the widget into corresponding states this.rs = remoteStorage; this.rs.remote.on('connected', stateSetter(this, 'connected')); this.rs.on('disconnected', stateSetter(this, 'initial')); this.rs.on('connecting', stateSetter(this, 'authing')); this.rs.on('authing', stateSetter(this, 'authing')); this.rs.on('error', errorsHandler(this)); if (this.rs.remote) { this.rs.remote.on('wire-busy', function (evt) { if (flashFor(evt)) { requestsToFlashFor++; stateSetter(self, 'busy')(); } }); this.rs.remote.on('wire-done', function (evt) { if (flashFor(evt)) { requestsToFlashFor--; } if (requestsToFlashFor <= 0 && evt.success) { stateSetter(self, 'connected')(); } }); } if (hasLocalStorage) { var state = localStorage[LS_STATE_KEY]; if (state && VALID_ENTRY_STATES[state]) { this._rememberedState = state; } } }; RemoteStorage.Widget.prototype = { /** * Method: display * * Displays the widget via the view.display method * * Parameters: * * options **/ display: function (options) { if (typeof(options) === 'string') { options = { domID: options }; } else if (typeof(options) === 'undefined') { options = {}; } if (! this.view) { this.setView(new RemoteStorage.Widget.View(this.rs)); } this.view.display(options); return this; }, linkWidgetToSync: function () { if (typeof(this.rs.sync) === 'object' && typeof(this.rs.sync.sync) === 'function') { this.view.on('sync', this.rs.sync.sync.bind(this.rs.sync)); } else { RemoteStorage.log('[Widget] typeof this.rs.sync check fail', this.rs.sync); setTimeout(this.linkWidgetToSync.bind(this), 1000); } }, /** * Method: setView(view) * * Sets the view and initializes event listeners to react on * widget (widget.view) events **/ setView: function (view) { this.view = view; this.view.on('connect', function (options) { if (typeof(options) === 'string') { // options is simply a useraddress this.rs.connect(options); } else if (options.special) { this.rs[options.special].connect(options); } }.bind(this)); this.view.on('secret-entered', function (secretKey) { this.view.setUserSecretKey(secretKey); stateSetter(this, 'ciphered')(); }.bind(this)); this.view.on('secret-cancelled', function () { stateSetter(this, 'notciphered')(); }.bind(this)); this.view.on('disconnect', this.rs.disconnect.bind(this.rs)); this.linkWidgetToSync(); try { this.view.on('reset', function (){ var location = RemoteStorage.Authorize.getLocation(); this.rs.on('disconnected', location.reload.bind(location)); this.rs.disconnect(); }.bind(this)); } catch(e) { if (!(e.message && e.message.match(/Unknown event/))) { // ignored. (the 0.7 widget-view interface didn't have a 'reset' event) throw e; } } if (this._rememberedState) { setTimeout(stateSetter(this, this._rememberedState), 0); delete this._rememberedState; } } }; /** * Method: displayWidget * * Same as <display> **/ RemoteStorage.prototype.displayWidget = function (options) { return this.widget.display(options); }; RemoteStorage.Widget._rs_init = function (remoteStorage) { hasLocalStorage = remoteStorage.localStorageAvailable(); if (! remoteStorage.widget) { remoteStorage.widget = new RemoteStorage.Widget(remoteStorage); } }; RemoteStorage.Widget._rs_supported = function (remoteStorage) { return typeof(document) !== 'undefined'; }; function stateSetter(widget, state) { RemoteStorage.log('[Widget] Producing stateSetter for', state); return function () { RemoteStorage.log('[Widget] Setting state', state, arguments); if (hasLocalStorage) { localStorage[LS_STATE_KEY] = state; } if (widget.view) { if (widget.rs.remote) { widget.view.setUserAddress(widget.rs.remote.userAddress); } widget.view.setState(state, arguments); } else { widget._rememberedState = state; } }; } function errorsHandler(widget) { return function (error) { var s; if (error instanceof RemoteStorage.DiscoveryError) { console.error('Discovery failed', error, '"' + error.message + '"'); s = stateSetter(widget, 'initial', [error.message]); } else if (error instanceof RemoteStorage.SyncError) { s = stateSetter(widget, 'offline', []); } else if (error instanceof RemoteStorage.Unauthorized) { s = stateSetter(widget, 'unauthorized'); } else { RemoteStorage.log('[Widget] Unknown error'); s = stateSetter(widget, 'error', [error]); } s.apply(); }; } function flashFor(evt) { if (evt.method === 'GET' && evt.isFolder) { return false; } return true; } })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/view.js **/ (function (window){ var t = RemoteStorage.I18n.translate; /** * Class: RemoteStorage.Widget.View * * Controls the visible widget * * States: * * initial - not connected * authing - in auth flow * connected - connected to remote storage, not syncing at the moment * ciphered - connected, with cipher * notciphered - connected, without cipher * busy - connected, syncing at the moment * offline - connected, but no network connectivity * error - connected, but sync error happened * unauthorized - connected, but request returned 401 **/ RemoteStorage.Widget.View = function (remoteStorage) { this.rs = remoteStorage; if (typeof(document) === 'undefined') { throw "Widget not supported"; } RemoteStorage.eventHandling(this, 'connect', 'secret-entered', 'secret-cancelled', 'disconnect', 'sync', 'display', 'reset'); // Re-binding the event so they can be called from the window for (var event in this.events){ this.events[event] = this.events[event].bind(this); } this.hideBubbleOnBodyClick = function (event) { for (var p = event.target; p !== document.body; p = p.parentElement) { if (p.id === 'remotestorage-widget') { return; } } this.hideBubble(); }.bind(this); }; RemoteStorage.Widget.View.prototype = { connectGdrive: function () { this._emit('connect', { special: 'googledrive' }); }, connectDropbox: function (){ this._emit('connect', { special: 'dropbox'}); }, /** * Method: setState * * Call the function that applies the state to the widget * * Parameters: * * state * args **/ setState: function (state, args) { RemoteStorage.log('[View] widget.view.setState(',state,',',args,');'); var s = this.states[state]; if (typeof(s) === 'undefined') { throw new Error("Bad State assigned to view: " + state); } s.apply(this, args); }, /** * Method: setUserAddress * * Set user address of the input field **/ setUserAddress: function (addr) { this.userAddress = addr || ''; var el; if (this.div && (el = this.div.querySelector('form.remotestorage-initial').userAddress)) { el.value = this.userAddress; } }, /** * Method: setUserSecretKey * * Set user secret key **/ setUserSecretKey: function (secretKey) { this.userSecretKey = secretKey; }, /** * Method: toggleBubble * * Show the bubble when hidden and the other way around **/ toggleBubble: function (event) { if (this.bubble.className.search('rs-hidden') < 0) { this.hideBubble(event); } else { this.showBubble(event); } }, /** * Method: hideBubble * * Hide the bubble **/ hideBubble: function (){ addClass(this.bubble, 'rs-hidden'); document.body.removeEventListener('click', this.hideBubbleOnBodyClick); }, /** * Method: showBubble * * Show the bubble **/ showBubble: function (event){ removeClass(this.bubble, 'rs-hidden'); if (typeof(event) !== 'undefined') { stopPropagation(event); } document.body.addEventListener('click', this.hideBubbleOnBodyClick); if (this.div.querySelector('.remotestorage-connected').classList.contains('remotestorage-cipher') && !this.userSecretKey) { this.bubble.querySelector('form.remotestorage-cipher-form').userSecretKey.focus(); } else { this.bubble.querySelector('form.remotestorage-initial').userAddress.focus(); } }, /** * Method: display * * Draw the widget inside of the dom element with the id options.domID * * Parameters: * * options * * Returns: * * The widget div **/ display: function (options) { if (typeof this.div !== 'undefined') { return this.div; } var element = document.createElement('div'); var style = document.createElement('style'); style.innerHTML = RemoteStorage.Assets.widgetCss; element.id = "remotestorage-widget"; element.innerHTML = RemoteStorage.Assets.widget; element.appendChild(style); if (options.domID) { var parent = document.getElementById(options.domID); if (! parent) { throw "Failed to find target DOM element with id=\"" + options.domID + "\""; } parent.appendChild(element); } else { document.body.appendChild(element); } // Sync button setupButton(element, 'rs-sync', 'syncIcon', this.events.sync); // Disconnect button setupButton(element, 'rs-disconnect', 'disconnectIcon', this.events.disconnect); // Get me out of here setupButton(element, 'remotestorage-reset', undefined, this.events.reset); // Connect button var connectButton = setupButton(element, 'connect', 'connectIcon', this.events.connect); // Handle connectButton state this.form = element.querySelector('form.remotestorage-initial'); var el = this.form.userAddress; el.addEventListener('load', handleButtonState); el.addEventListener('keyup', handleButtonState); if (this.userAddress) { el.value = this.userAddress; } if (options.encryption) { this.cipher = true; var secretKeyInput = element.querySelector('form.remotestorage-cipher-form').userSecretKey; // This is to avoid the 'password field on an insecured page' warning, when not used and on http (not https) secretKeyInput.type = 'password'; // Cipher button var cipherButton = setupButton(element, 'rs-cipher', 'cipherIcon', this.events['secret-entered']); // Handle cipherButton state secretKeyInput.addEventListener('load', handleButtonState); secretKeyInput.addEventListener('keyup', handleButtonState); // No cipher button setupButton(element, 'rs-nocipher', 'nocipherIcon', this.events['secret-cancelled']); } // The cube this.cube = setupButton(element, 'rs-cube', 'remoteStorageIcon', this.toggleBubble.bind(this)); // Google Drive and Dropbox icons setupButton(element, 'rs-dropbox', 'dropbox', this.connectDropbox.bind(this)); setupButton(element, 'rs-googledrive', 'googledrive', this.connectGdrive.bind(this)); var bubbleDontCatch = { INPUT: true, BUTTON: true, IMG: true }; var eventListener = function (event) { if (! bubbleDontCatch[event.target.tagName] && ! (this.div.classList.contains('remotestorage-state-unauthorized') )) { this.showBubble(event); } }.bind(this); this.bubble = setupButton(element, 'rs-bubble', undefined, eventListener); this.hideBubble(); this.div = element; this.states.initial.call(this); this.events.display.call(this); return this.div; }, states: { initial: function (message) { var cube = this.cube; var info = message || t("view_info"); cube.src = RemoteStorage.Assets.remoteStorageIcon; this._renderTranslatedInitialContent(); if (message) { cube.src = RemoteStorage.Assets.remoteStorageIconError; removeClass(this.cube, 'remotestorage-loading'); this.showBubble(); // Show the red error cube for 5 seconds, then show the normal orange one again setTimeout(function (){ cube.src = RemoteStorage.Assets.remoteStorageIcon; },2000); } else { this.hideBubble(); } this.div.className = "remotestorage-state-initial"; if (this.userSecretKey) { delete this.userSecretKey; } // Google Drive and Dropbox icons var backends = 1; if (this._activateBackend('dropbox')) { backends += 1; } if (this._activateBackend('googledrive')) { backends += 1; } this.div.querySelector('.rs-bubble-text').style.paddingRight = backends*32+8+'px'; // If address not empty connect button enabled var cb = this.div.querySelector('.connect'); if (this.form.userAddress.value) { cb.removeAttribute('disabled'); } var infoEl = this.div.querySelector('.rs-info-msg'); infoEl.innerHTML = info; if (message) { infoEl.classList.add('remotestorage-error-info'); } else { infoEl.classList.remove('remotestorage-error-info'); } }, authing: function () { this.div.removeEventListener('click', this.events.connect); this.div.className = "remotestorage-state-authing"; this.div.querySelector('.rs-status-text').innerHTML = t("view_connecting", this.userAddress); addClass(this.cube, 'remotestorage-loading'); }, connected: function () { var cube = this.cube; this.div.className = "remotestorage-state-connected"; this.div.querySelector('.userAddress').innerHTML = this.userAddress; cube.src = RemoteStorage.Assets.remoteStorageIcon; removeClass(cube, 'remotestorage-loading'); if (this.cipher) { if (this.userSecretKey) { if (this.userSecretKeyError) { cube.src = RemoteStorage.Assets.remoteStorageIconError; addClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher'); addClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error'); this.showBubble(); // Show the red error cube for 5 seconds, then show the normal orange one again setTimeout(function (){ cube.src = RemoteStorage.Assets.remoteStorageIcon; },5000); } else { removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error'); cube.src = RemoteStorage.Assets.remoteStorageIconCiphered; } } else { addClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher'); this.showBubble(); } } var icons = { googledrive: this.div.querySelector('.rs-googledrive'), dropbox: this.div.querySelector('.rs-dropbox') }; icons.googledrive.style.display = icons.dropbox.style.display = 'none'; if (icons[this.rs.backend]) { icons[this.rs.backend].style.display = 'inline-block'; this.div.querySelector('.rs-bubble-text').style.paddingRight = 2*32+8+'px'; } else { this.div.querySelector('.rs-bubble-text').style.paddingRight = 32+8+'px'; } }, ciphered: function () { this.div.querySelector('form.remotestorage-cipher-form').userSecretKey.value = ''; removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error'); removeClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher'); this.cube.src = RemoteStorage.Assets.remoteStorageIconCiphered; this.hideBubble(); }, notciphered: function () { this.cipher = false; removeClass(this.div.querySelector('.remotestorage-invalid-key'), 'remotestorage-cipher-error'); removeClass(this.div.querySelector('.remotestorage-connected'), 'remotestorage-cipher'); this.hideBubble(); }, busy: function () { this.div.className = "remotestorage-state-busy"; addClass(this.cube, 'remotestorage-loading'); //TODO needs to be undone when is that neccesary }, offline: function () { this.div.className = "remotestorage-state-offline"; this.cube.src = RemoteStorage.Assets.remoteStorageIconOffline; this.div.querySelector('.rs-status-text').innerHTML = t("view_offline"); }, error: function (err) { var errorMsg = err; this.div.className = "remotestorage-state-error"; this.div.querySelector('.rs-bubble-text').innerHTML = '<strong>'+t('view_error_occured')+'</strong>'; //FIXME I don't know what an DOMError is and my browser doesn't know too(how to handle this?) if (err instanceof Error /*|| err instanceof DOMError*/) { errorMsg = err.message + '\n\n' + err.stack; } this.div.querySelector('.rs-error-msg').textContent = errorMsg; this.cube.src = RemoteStorage.Assets.remoteStorageIconError; this.showBubble(); }, unauthorized: function () { this.div.className = "remotestorage-state-unauthorized"; this.cube.src = RemoteStorage.Assets.remoteStorageIconError; this.showBubble(); this.div.addEventListener('click', this.events.connect); } }, events: { /** * Event: connect * * Emitted when the connect button is clicked **/ connect: function (event) { stopPropagation(event); event.preventDefault(); this._emit('connect', this.div.querySelector('form.remotestorage-initial').userAddress.value); }, /** * Event: secret-entered * * Emitted when the cipher button is clicked **/ 'secret-entered': function (event) { stopPropagation(event); event.preventDefault(); this._emit('secret-entered', this.div.querySelector('form.remotestorage-cipher-form').userSecretKey.value); }, /** * Event: secret-cancelled * * Emitted when the nocipher button is clicked **/ 'secret-cancelled': function (event) { stopPropagation(event); event.preventDefault(); this._emit('secret-cancelled'); }, /** * Event: sync * * Emitted when the sync button is clicked **/ sync: function (event) { stopPropagation(event); event.preventDefault(); this._emit('sync'); }, /** * Event: disconnect * * Emitted when the disconnect button is clicked **/ disconnect: function (event) { stopPropagation(event); event.preventDefault(); this._emit('disconnect'); }, /** * Event: reset * * Emitted after crash triggers disconnect **/ reset: function (event){ event.preventDefault(); var result = window.confirm(t('view_confirm_reset')); if (result){ this._emit('reset'); } }, /** * Event: display * * Emitted when finished displaying the widget **/ display : function (event) { if (event) { event.preventDefault(); } this._emit('display'); } }, _renderTranslatedInitialContent: function () { this.div.querySelector('.rs-status-text').innerHTML = t("view_connect"); this.div.querySelector('.remotestorage-reset').innerHTML = t("view_get_me_out"); this.div.querySelector('.rs-error-plz-report').innerHTML = t("view_error_plz_report"); this.div.querySelector('.remotestorage-unauthorized').innerHTML = t("view_unauthorized"); this.div.querySelector('.remotestorage-invalid-key').innerHTML = t("view_invalid_key"); }, _activateBackend: function activateBackend(backendName) { var className = 'rs-' + backendName; if (this.rs.apiKeys[backendName]) { this.div.querySelector('.' + className).style.display = 'inline-block'; return true; } else { this.div.querySelector('.' + className).style.display = 'none'; return false; } } }; function removeClass(el, className) { return el.classList.remove(className); } function addClass(el, className) { return el.classList.add(className); } function stopPropagation(event) { if (typeof(event.stopPropagation) === 'function') { event.stopPropagation(); } else { event.cancelBubble = true; } } function setupButton(parent, className, iconName, eventListener) { var element = parent.querySelector('.' + className); if (typeof iconName !== 'undefined') { var img = element.querySelector('img'); (img || element).src = RemoteStorage.Assets[iconName]; } element.addEventListener('click', eventListener); return element; } function handleButtonState(event) { if (event.target.value) { event.target.nextElementSibling.removeAttribute('disabled'); } else { event.target.nextElementSibling.setAttribute('disabled','disabled'); } } })(typeof(window) !== 'undefined' ? window : global); /** FILE: node_modules/tv4/tv4.js **/ /* Author: Geraint Luff and others Year: 2013 This code is released into the "public domain" by its author(s). Anybody may use, alter and distribute the code without restriction. The author makes no guarantees, and takes no liability of any kind for use of this code. If you find a bug or make an improvement, it would be courteous to let the author know, but it is not compulsory. */ (function (global, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof module !== 'undefined' && module.exports){ // CommonJS. Define export. module.exports = factory(); } else { // Browser globals global.tv4 = factory(); } }(this, function () { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FObject%2Fkeys if (!Object.keys) { Object.keys = (function () { var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function (obj) { if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) { throw new TypeError('Object.keys called on non-object'); } var result = []; for (var prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (var i=0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; })(); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create if (!Object.create) { Object.create = (function(){ function F(){} return function(o){ if (arguments.length !== 1) { throw new Error('Object.create implementation only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FisArray if(!Array.isArray) { Array.isArray = function (vArg) { return Object.prototype.toString.call(vArg) === "[object Array]"; }; } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FindexOf 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; }; } // Grungey Object.isFrozen hack if (!Object.isFrozen) { Object.isFrozen = function (obj) { var key = "tv4_test_frozen_key"; while (obj.hasOwnProperty(key)) { key += Math.random(); } try { obj[key] = true; delete obj[key]; return false; } catch (e) { return true; } }; } // Based on: https://github.com/geraintluff/uri-templates, but with all the de-substitution stuff removed var uriTemplateGlobalModifiers = { "+": true, "#": true, ".": true, "/": true, ";": true, "?": true, "&": true }; var uriTemplateSuffices = { "*": true }; function notReallyPercentEncode(string) { return encodeURI(string).replace(/%25[0-9][0-9]/g, function (doubleEncoded) { return "%" + doubleEncoded.substring(3); }); } function uriTemplateSubstitution(spec) { var modifier = ""; if (uriTemplateGlobalModifiers[spec.charAt(0)]) { modifier = spec.charAt(0); spec = spec.substring(1); } var separator = ""; var prefix = ""; var shouldEscape = true; var showVariables = false; var trimEmptyString = false; if (modifier === '+') { shouldEscape = false; } else if (modifier === ".") { prefix = "."; separator = "."; } else if (modifier === "/") { prefix = "/"; separator = "/"; } else if (modifier === '#') { prefix = "#"; shouldEscape = false; } else if (modifier === ';') { prefix = ";"; separator = ";"; showVariables = true; trimEmptyString = true; } else if (modifier === '?') { prefix = "?"; separator = "&"; showVariables = true; } else if (modifier === '&') { prefix = "&"; separator = "&"; showVariables = true; } var varNames = []; var varList = spec.split(","); var varSpecs = []; var varSpecMap = {}; for (var i = 0; i < varList.length; i++) { var varName = varList[i]; var truncate = null; if (varName.indexOf(":") !== -1) { var parts = varName.split(":"); varName = parts[0]; truncate = parseInt(parts[1], 10); } var suffices = {}; while (uriTemplateSuffices[varName.charAt(varName.length - 1)]) { suffices[varName.charAt(varName.length - 1)] = true; varName = varName.substring(0, varName.length - 1); } var varSpec = { truncate: truncate, name: varName, suffices: suffices }; varSpecs.push(varSpec); varSpecMap[varName] = varSpec; varNames.push(varName); } var subFunction = function (valueFunction) { var result = ""; var startIndex = 0; for (var i = 0; i < varSpecs.length; i++) { var varSpec = varSpecs[i]; var value = valueFunction(varSpec.name); if (value === null || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof value === 'object' && Object.keys(value).length === 0)) { startIndex++; continue; } if (i === startIndex) { result += prefix; } else { result += (separator || ","); } if (Array.isArray(value)) { if (showVariables) { result += varSpec.name + "="; } for (var j = 0; j < value.length; j++) { if (j > 0) { result += varSpec.suffices['*'] ? (separator || ",") : ","; if (varSpec.suffices['*'] && showVariables) { result += varSpec.name + "="; } } result += shouldEscape ? encodeURIComponent(value[j]).replace(/!/g, "%21") : notReallyPercentEncode(value[j]); } } else if (typeof value === "object") { if (showVariables && !varSpec.suffices['*']) { result += varSpec.name + "="; } var first = true; for (var key in value) { if (!first) { result += varSpec.suffices['*'] ? (separator || ",") : ","; } first = false; result += shouldEscape ? encodeURIComponent(key).replace(/!/g, "%21") : notReallyPercentEncode(key); result += varSpec.suffices['*'] ? '=' : ","; result += shouldEscape ? encodeURIComponent(value[key]).replace(/!/g, "%21") : notReallyPercentEncode(value[key]); } } else { if (showVariables) { result += varSpec.name; if (!trimEmptyString || value !== "") { result += "="; } } if (varSpec.truncate != null) { value = value.substring(0, varSpec.truncate); } result += shouldEscape ? encodeURIComponent(value).replace(/!/g, "%21"): notReallyPercentEncode(value); } } return result; }; subFunction.varNames = varNames; return { prefix: prefix, substitution: subFunction }; } function UriTemplate(template) { if (!(this instanceof UriTemplate)) { return new UriTemplate(template); } var parts = template.split("{"); var textParts = [parts.shift()]; var prefixes = []; var substitutions = []; var varNames = []; while (parts.length > 0) { var part = parts.shift(); var spec = part.split("}")[0]; var remainder = part.substring(spec.length + 1); var funcs = uriTemplateSubstitution(spec); substitutions.push(funcs.substitution); prefixes.push(funcs.prefix); textParts.push(remainder); varNames = varNames.concat(funcs.substitution.varNames); } this.fill = function (valueFunction) { var result = textParts[0]; for (var i = 0; i < substitutions.length; i++) { var substitution = substitutions[i]; result += substitution(valueFunction); result += textParts[i + 1]; } return result; }; this.varNames = varNames; this.template = template; } UriTemplate.prototype = { toString: function () { return this.template; }, fillFromObject: function (obj) { return this.fill(function (varName) { return obj[varName]; }); } }; var ValidatorContext = function ValidatorContext(parent, collectMultiple, errorReporter, checkRecursive, trackUnknownProperties) { this.missing = []; this.missingMap = {}; this.formatValidators = parent ? Object.create(parent.formatValidators) : {}; this.schemas = parent ? Object.create(parent.schemas) : {}; this.collectMultiple = collectMultiple; this.errors = []; this.handleError = collectMultiple ? this.collectError : this.returnError; if (checkRecursive) { this.checkRecursive = true; this.scanned = []; this.scannedFrozen = []; this.scannedFrozenSchemas = []; this.scannedFrozenValidationErrors = []; this.validatedSchemasKey = 'tv4_validation_id'; this.validationErrorsKey = 'tv4_validation_errors_id'; } if (trackUnknownProperties) { this.trackUnknownProperties = true; this.knownPropertyPaths = {}; this.unknownPropertyPaths = {}; } this.errorReporter = errorReporter || defaultErrorReporter('en'); if (typeof this.errorReporter === 'string') { throw new Error('debug'); } this.definedKeywords = {}; if (parent) { for (var key in parent.definedKeywords) { this.definedKeywords[key] = parent.definedKeywords[key].slice(0); } } }; ValidatorContext.prototype.defineKeyword = function (keyword, keywordFunction) { this.definedKeywords[keyword] = this.definedKeywords[keyword] || []; this.definedKeywords[keyword].push(keywordFunction); }; ValidatorContext.prototype.createError = function (code, messageParams, dataPath, schemaPath, subErrors, data, schema) { var error = new ValidationError(code, messageParams, dataPath, schemaPath, subErrors); error.message = this.errorReporter(error, data, schema); return error; }; ValidatorContext.prototype.returnError = function (error) { return error; }; ValidatorContext.prototype.collectError = function (error) { if (error) { this.errors.push(error); } return null; }; ValidatorContext.prototype.prefixErrors = function (startIndex, dataPath, schemaPath) { for (var i = startIndex; i < this.errors.length; i++) { this.errors[i] = this.errors[i].prefixWith(dataPath, schemaPath); } return this; }; ValidatorContext.prototype.banUnknownProperties = function (data, schema) { for (var unknownPath in this.unknownPropertyPaths) { var error = this.createError(ErrorCodes.UNKNOWN_PROPERTY, {path: unknownPath}, unknownPath, "", null, data, schema); var result = this.handleError(error); if (result) { return result; } } return null; }; ValidatorContext.prototype.addFormat = function (format, validator) { if (typeof format === 'object') { for (var key in format) { this.addFormat(key, format[key]); } return this; } this.formatValidators[format] = validator; }; ValidatorContext.prototype.resolveRefs = function (schema, urlHistory) { if (schema['$ref'] !== undefined) { urlHistory = urlHistory || {}; if (urlHistory[schema['$ref']]) { return this.createError(ErrorCodes.CIRCULAR_REFERENCE, {urls: Object.keys(urlHistory).join(', ')}, '', '', null, undefined, schema); } urlHistory[schema['$ref']] = true; schema = this.getSchema(schema['$ref'], urlHistory); } return schema; }; ValidatorContext.prototype.getSchema = function (url, urlHistory) { var schema; if (this.schemas[url] !== undefined) { schema = this.schemas[url]; return this.resolveRefs(schema, urlHistory); } var baseUrl = url; var fragment = ""; if (url.indexOf('#') !== -1) { fragment = url.substring(url.indexOf("#") + 1); baseUrl = url.substring(0, url.indexOf("#")); } if (typeof this.schemas[baseUrl] === 'object') { schema = this.schemas[baseUrl]; var pointerPath = decodeURIComponent(fragment); if (pointerPath === "") { return this.resolveRefs(schema, urlHistory); } else if (pointerPath.charAt(0) !== "/") { return undefined; } var parts = pointerPath.split("/").slice(1); for (var i = 0; i < parts.length; i++) { var component = parts[i].replace(/~1/g, "/").replace(/~0/g, "~"); if (schema[component] === undefined) { schema = undefined; break; } schema = schema[component]; } if (schema !== undefined) { return this.resolveRefs(schema, urlHistory); } } if (this.missing[baseUrl] === undefined) { this.missing.push(baseUrl); this.missing[baseUrl] = baseUrl; this.missingMap[baseUrl] = baseUrl; } }; ValidatorContext.prototype.searchSchemas = function (schema, url) { if (Array.isArray(schema)) { for (var i = 0; i < schema.length; i++) { this.searchSchemas(schema[i], url); } } else if (schema && typeof schema === "object") { if (typeof schema.id === "string") { if (isTrustedUrl(url, schema.id)) { if (this.schemas[schema.id] === undefined) { this.schemas[schema.id] = schema; } } } for (var key in schema) { if (key !== "enum") { if (typeof schema[key] === "object") { this.searchSchemas(schema[key], url); } else if (key === "$ref") { var uri = getDocumentUri(schema[key]); if (uri && this.schemas[uri] === undefined && this.missingMap[uri] === undefined) { this.missingMap[uri] = uri; } } } } } }; ValidatorContext.prototype.addSchema = function (url, schema) { //overload if (typeof url !== 'string' || typeof schema === 'undefined') { if (typeof url === 'object' && typeof url.id === 'string') { schema = url; url = schema.id; } else { return; } } if (url === getDocumentUri(url) + "#") { // Remove empty fragment url = getDocumentUri(url); } this.schemas[url] = schema; delete this.missingMap[url]; normSchema(schema, url); this.searchSchemas(schema, url); }; ValidatorContext.prototype.getSchemaMap = function () { var map = {}; for (var key in this.schemas) { map[key] = this.schemas[key]; } return map; }; ValidatorContext.prototype.getSchemaUris = function (filterRegExp) { var list = []; for (var key in this.schemas) { if (!filterRegExp || filterRegExp.test(key)) { list.push(key); } } return list; }; ValidatorContext.prototype.getMissingUris = function (filterRegExp) { var list = []; for (var key in this.missingMap) { if (!filterRegExp || filterRegExp.test(key)) { list.push(key); } } return list; }; ValidatorContext.prototype.dropSchemas = function () { this.schemas = {}; this.reset(); }; ValidatorContext.prototype.reset = function () { this.missing = []; this.missingMap = {}; this.errors = []; }; ValidatorContext.prototype.validateAll = function (data, schema, dataPathParts, schemaPathParts, dataPointerPath) { var topLevel; schema = this.resolveRefs(schema); if (!schema) { return null; } else if (schema instanceof ValidationError) { this.errors.push(schema); return schema; } var startErrorCount = this.errors.length; var frozenIndex, scannedFrozenSchemaIndex = null, scannedSchemasIndex = null; if (this.checkRecursive && data && typeof data === 'object') { topLevel = !this.scanned.length; if (data[this.validatedSchemasKey]) { var schemaIndex = data[this.validatedSchemasKey].indexOf(schema); if (schemaIndex !== -1) { this.errors = this.errors.concat(data[this.validationErrorsKey][schemaIndex]); return null; } } if (Object.isFrozen(data)) { frozenIndex = this.scannedFrozen.indexOf(data); if (frozenIndex !== -1) { var frozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].indexOf(schema); if (frozenSchemaIndex !== -1) { this.errors = this.errors.concat(this.scannedFrozenValidationErrors[frozenIndex][frozenSchemaIndex]); return null; } } } this.scanned.push(data); if (Object.isFrozen(data)) { if (frozenIndex === -1) { frozenIndex = this.scannedFrozen.length; this.scannedFrozen.push(data); this.scannedFrozenSchemas.push([]); } scannedFrozenSchemaIndex = this.scannedFrozenSchemas[frozenIndex].length; this.scannedFrozenSchemas[frozenIndex][scannedFrozenSchemaIndex] = schema; this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = []; } else { if (!data[this.validatedSchemasKey]) { try { Object.defineProperty(data, this.validatedSchemasKey, { value: [], configurable: true }); Object.defineProperty(data, this.validationErrorsKey, { value: [], configurable: true }); } catch (e) { //IE 7/8 workaround data[this.validatedSchemasKey] = []; data[this.validationErrorsKey] = []; } } scannedSchemasIndex = data[this.validatedSchemasKey].length; data[this.validatedSchemasKey][scannedSchemasIndex] = schema; data[this.validationErrorsKey][scannedSchemasIndex] = []; } } var errorCount = this.errors.length; var error = this.validateBasic(data, schema, dataPointerPath) || this.validateNumeric(data, schema, dataPointerPath) || this.validateString(data, schema, dataPointerPath) || this.validateArray(data, schema, dataPointerPath) || this.validateObject(data, schema, dataPointerPath) || this.validateCombinations(data, schema, dataPointerPath) || this.validateHypermedia(data, schema, dataPointerPath) || this.validateFormat(data, schema, dataPointerPath) || this.validateDefinedKeywords(data, schema, dataPointerPath) || null; if (topLevel) { while (this.scanned.length) { var item = this.scanned.pop(); delete item[this.validatedSchemasKey]; } this.scannedFrozen = []; this.scannedFrozenSchemas = []; } if (error || errorCount !== this.errors.length) { while ((dataPathParts && dataPathParts.length) || (schemaPathParts && schemaPathParts.length)) { var dataPart = (dataPathParts && dataPathParts.length) ? "" + dataPathParts.pop() : null; var schemaPart = (schemaPathParts && schemaPathParts.length) ? "" + schemaPathParts.pop() : null; if (error) { error = error.prefixWith(dataPart, schemaPart); } this.prefixErrors(errorCount, dataPart, schemaPart); } } if (scannedFrozenSchemaIndex !== null) { this.scannedFrozenValidationErrors[frozenIndex][scannedFrozenSchemaIndex] = this.errors.slice(startErrorCount); } else if (scannedSchemasIndex !== null) { data[this.validationErrorsKey][scannedSchemasIndex] = this.errors.slice(startErrorCount); } return this.handleError(error); }; ValidatorContext.prototype.validateFormat = function (data, schema) { if (typeof schema.format !== 'string' || !this.formatValidators[schema.format]) { return null; } var errorMessage = this.formatValidators[schema.format].call(null, data, schema); if (typeof errorMessage === 'string' || typeof errorMessage === 'number') { return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage}, '', '/format', null, data, schema); } else if (errorMessage && typeof errorMessage === 'object') { return this.createError(ErrorCodes.FORMAT_CUSTOM, {message: errorMessage.message || "?"}, errorMessage.dataPath || '', errorMessage.schemaPath || "/format", null, data, schema); } return null; }; ValidatorContext.prototype.validateDefinedKeywords = function (data, schema, dataPointerPath) { for (var key in this.definedKeywords) { if (typeof schema[key] === 'undefined') { continue; } var validationFunctions = this.definedKeywords[key]; for (var i = 0; i < validationFunctions.length; i++) { var func = validationFunctions[i]; var result = func(data, schema[key], schema, dataPointerPath); if (typeof result === 'string' || typeof result === 'number') { return this.createError(ErrorCodes.KEYWORD_CUSTOM, {key: key, message: result}, '', '', null, data, schema).prefixWith(null, key); } else if (result && typeof result === 'object') { var code = result.code; if (typeof code === 'string') { if (!ErrorCodes[code]) { throw new Error('Undefined error code (use defineError): ' + code); } code = ErrorCodes[code]; } else if (typeof code !== 'number') { code = ErrorCodes.KEYWORD_CUSTOM; } var messageParams = (typeof result.message === 'object') ? result.message : {key: key, message: result.message || "?"}; var schemaPath = result.schemaPath || ("/" + key.replace(/~/g, '~0').replace(/\//g, '~1')); return this.createError(code, messageParams, result.dataPath || null, schemaPath, null, data, schema); } } } return null; }; function recursiveCompare(A, B) { if (A === B) { return true; } if (A && B && typeof A === "object" && typeof B === "object") { if (Array.isArray(A) !== Array.isArray(B)) { return false; } else if (Array.isArray(A)) { if (A.length !== B.length) { return false; } for (var i = 0; i < A.length; i++) { if (!recursiveCompare(A[i], B[i])) { return false; } } } else { var key; for (key in A) { if (B[key] === undefined && A[key] !== undefined) { return false; } } for (key in B) { if (A[key] === undefined && B[key] !== undefined) { return false; } } for (key in A) { if (!recursiveCompare(A[key], B[key])) { return false; } } } return true; } return false; } ValidatorContext.prototype.validateBasic = function validateBasic(data, schema, dataPointerPath) { var error; if (error = this.validateType(data, schema, dataPointerPath)) { return error.prefixWith(null, "type"); } if (error = this.validateEnum(data, schema, dataPointerPath)) { return error.prefixWith(null, "type"); } return null; }; ValidatorContext.prototype.validateType = function validateType(data, schema) { if (schema.type === undefined) { return null; } var dataType = typeof data; if (data === null) { dataType = "null"; } else if (Array.isArray(data)) { dataType = "array"; } var allowedTypes = schema.type; if (!Array.isArray(allowedTypes)) { allowedTypes = [allowedTypes]; } for (var i = 0; i < allowedTypes.length; i++) { var type = allowedTypes[i]; if (type === dataType || (type === "integer" && dataType === "number" && (data % 1 === 0))) { return null; } } return this.createError(ErrorCodes.INVALID_TYPE, {type: dataType, expected: allowedTypes.join("/")}, '', '', null, data, schema); }; ValidatorContext.prototype.validateEnum = function validateEnum(data, schema) { if (schema["enum"] === undefined) { return null; } for (var i = 0; i < schema["enum"].length; i++) { var enumVal = schema["enum"][i]; if (recursiveCompare(data, enumVal)) { return null; } } return this.createError(ErrorCodes.ENUM_MISMATCH, {value: (typeof JSON !== 'undefined') ? JSON.stringify(data) : data}, '', '', null, data, schema); }; ValidatorContext.prototype.validateNumeric = function validateNumeric(data, schema, dataPointerPath) { return this.validateMultipleOf(data, schema, dataPointerPath) || this.validateMinMax(data, schema, dataPointerPath) || this.validateNaN(data, schema, dataPointerPath) || null; }; var CLOSE_ENOUGH_LOW = Math.pow(2, -51); var CLOSE_ENOUGH_HIGH = 1 - CLOSE_ENOUGH_LOW; ValidatorContext.prototype.validateMultipleOf = function validateMultipleOf(data, schema) { var multipleOf = schema.multipleOf || schema.divisibleBy; if (multipleOf === undefined) { return null; } if (typeof data === "number") { var remainder = (data/multipleOf)%1; if (remainder >= CLOSE_ENOUGH_LOW && remainder < CLOSE_ENOUGH_HIGH) { return this.createError(ErrorCodes.NUMBER_MULTIPLE_OF, {value: data, multipleOf: multipleOf}, '', '', null, data, schema); } } return null; }; ValidatorContext.prototype.validateMinMax = function validateMinMax(data, schema) { if (typeof data !== "number") { return null; } if (schema.minimum !== undefined) { if (data < schema.minimum) { return this.createError(ErrorCodes.NUMBER_MINIMUM, {value: data, minimum: schema.minimum}, '', '/minimum', null, data, schema); } if (schema.exclusiveMinimum && data === schema.minimum) { return this.createError(ErrorCodes.NUMBER_MINIMUM_EXCLUSIVE, {value: data, minimum: schema.minimum}, '', '/exclusiveMinimum', null, data, schema); } } if (schema.maximum !== undefined) { if (data > schema.maximum) { return this.createError(ErrorCodes.NUMBER_MAXIMUM, {value: data, maximum: schema.maximum}, '', '/maximum', null, data, schema); } if (schema.exclusiveMaximum && data === schema.maximum) { return this.createError(ErrorCodes.NUMBER_MAXIMUM_EXCLUSIVE, {value: data, maximum: schema.maximum}, '', '/exclusiveMaximum', null, data, schema); } } return null; }; ValidatorContext.prototype.validateNaN = function validateNaN(data, schema) { if (typeof data !== "number") { return null; } if (isNaN(data) === true || data === Infinity || data === -Infinity) { return this.createError(ErrorCodes.NUMBER_NOT_A_NUMBER, {value: data}, '', '/type', null, data, schema); } return null; }; ValidatorContext.prototype.validateString = function validateString(data, schema, dataPointerPath) { return this.validateStringLength(data, schema, dataPointerPath) || this.validateStringPattern(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateStringLength = function validateStringLength(data, schema) { if (typeof data !== "string") { return null; } if (schema.minLength !== undefined) { if (data.length < schema.minLength) { return this.createError(ErrorCodes.STRING_LENGTH_SHORT, {length: data.length, minimum: schema.minLength}, '', '/minLength', null, data, schema); } } if (schema.maxLength !== undefined) { if (data.length > schema.maxLength) { return this.createError(ErrorCodes.STRING_LENGTH_LONG, {length: data.length, maximum: schema.maxLength}, '', '/maxLength', null, data, schema); } } return null; }; ValidatorContext.prototype.validateStringPattern = function validateStringPattern(data, schema) { if (typeof data !== "string" || (typeof schema.pattern !== "string" && !(schema.pattern instanceof RegExp))) { return null; } var regexp; if (schema.pattern instanceof RegExp) { regexp = schema.pattern; } else { var body, flags = ''; // Check for regular expression literals // @see http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5 var literal = schema.pattern.match(/^\/(.+)\/([img]*)$/); if (literal) { body = literal[1]; flags = literal[2]; } else { body = schema.pattern; } regexp = new RegExp(body, flags); } if (!regexp.test(data)) { return this.createError(ErrorCodes.STRING_PATTERN, {pattern: schema.pattern}, '', '/pattern', null, data, schema); } return null; }; ValidatorContext.prototype.validateArray = function validateArray(data, schema, dataPointerPath) { if (!Array.isArray(data)) { return null; } return this.validateArrayLength(data, schema, dataPointerPath) || this.validateArrayUniqueItems(data, schema, dataPointerPath) || this.validateArrayItems(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateArrayLength = function validateArrayLength(data, schema) { var error; if (schema.minItems !== undefined) { if (data.length < schema.minItems) { error = this.createError(ErrorCodes.ARRAY_LENGTH_SHORT, {length: data.length, minimum: schema.minItems}, '', '/minItems', null, data, schema); if (this.handleError(error)) { return error; } } } if (schema.maxItems !== undefined) { if (data.length > schema.maxItems) { error = this.createError(ErrorCodes.ARRAY_LENGTH_LONG, {length: data.length, maximum: schema.maxItems}, '', '/maxItems', null, data, schema); if (this.handleError(error)) { return error; } } } return null; }; ValidatorContext.prototype.validateArrayUniqueItems = function validateArrayUniqueItems(data, schema) { if (schema.uniqueItems) { for (var i = 0; i < data.length; i++) { for (var j = i + 1; j < data.length; j++) { if (recursiveCompare(data[i], data[j])) { var error = this.createError(ErrorCodes.ARRAY_UNIQUE, {match1: i, match2: j}, '', '/uniqueItems', null, data, schema); if (this.handleError(error)) { return error; } } } } } return null; }; ValidatorContext.prototype.validateArrayItems = function validateArrayItems(data, schema, dataPointerPath) { if (schema.items === undefined) { return null; } var error, i; if (Array.isArray(schema.items)) { for (i = 0; i < data.length; i++) { if (i < schema.items.length) { if (error = this.validateAll(data[i], schema.items[i], [i], ["items", i], dataPointerPath + "/" + i)) { return error; } } else if (schema.additionalItems !== undefined) { if (typeof schema.additionalItems === "boolean") { if (!schema.additionalItems) { error = (this.createError(ErrorCodes.ARRAY_ADDITIONAL_ITEMS, {}, '/' + i, '/additionalItems', null, data, schema)); if (this.handleError(error)) { return error; } } } else if (error = this.validateAll(data[i], schema.additionalItems, [i], ["additionalItems"], dataPointerPath + "/" + i)) { return error; } } } } else { for (i = 0; i < data.length; i++) { if (error = this.validateAll(data[i], schema.items, [i], ["items"], dataPointerPath + "/" + i)) { return error; } } } return null; }; ValidatorContext.prototype.validateObject = function validateObject(data, schema, dataPointerPath) { if (typeof data !== "object" || data === null || Array.isArray(data)) { return null; } return this.validateObjectMinMaxProperties(data, schema, dataPointerPath) || this.validateObjectRequiredProperties(data, schema, dataPointerPath) || this.validateObjectProperties(data, schema, dataPointerPath) || this.validateObjectDependencies(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateObjectMinMaxProperties = function validateObjectMinMaxProperties(data, schema) { var keys = Object.keys(data); var error; if (schema.minProperties !== undefined) { if (keys.length < schema.minProperties) { error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MINIMUM, {propertyCount: keys.length, minimum: schema.minProperties}, '', '/minProperties', null, data, schema); if (this.handleError(error)) { return error; } } } if (schema.maxProperties !== undefined) { if (keys.length > schema.maxProperties) { error = this.createError(ErrorCodes.OBJECT_PROPERTIES_MAXIMUM, {propertyCount: keys.length, maximum: schema.maxProperties}, '', '/maxProperties', null, data, schema); if (this.handleError(error)) { return error; } } } return null; }; ValidatorContext.prototype.validateObjectRequiredProperties = function validateObjectRequiredProperties(data, schema) { if (schema.required !== undefined) { for (var i = 0; i < schema.required.length; i++) { var key = schema.required[i]; if (data[key] === undefined) { var error = this.createError(ErrorCodes.OBJECT_REQUIRED, {key: key}, '', '/required/' + i, null, data, schema); if (this.handleError(error)) { return error; } } } } return null; }; ValidatorContext.prototype.validateObjectProperties = function validateObjectProperties(data, schema, dataPointerPath) { var error; for (var key in data) { var keyPointerPath = dataPointerPath + "/" + key.replace(/~/g, '~0').replace(/\//g, '~1'); var foundMatch = false; if (schema.properties !== undefined && schema.properties[key] !== undefined) { foundMatch = true; if (error = this.validateAll(data[key], schema.properties[key], [key], ["properties", key], keyPointerPath)) { return error; } } if (schema.patternProperties !== undefined) { for (var patternKey in schema.patternProperties) { var regexp = new RegExp(patternKey); if (regexp.test(key)) { foundMatch = true; if (error = this.validateAll(data[key], schema.patternProperties[patternKey], [key], ["patternProperties", patternKey], keyPointerPath)) { return error; } } } } if (!foundMatch) { if (schema.additionalProperties !== undefined) { if (this.trackUnknownProperties) { this.knownPropertyPaths[keyPointerPath] = true; delete this.unknownPropertyPaths[keyPointerPath]; } if (typeof schema.additionalProperties === "boolean") { if (!schema.additionalProperties) { error = this.createError(ErrorCodes.OBJECT_ADDITIONAL_PROPERTIES, {key: key}, '', '/additionalProperties', null, data, schema).prefixWith(key, null); if (this.handleError(error)) { return error; } } } else { if (error = this.validateAll(data[key], schema.additionalProperties, [key], ["additionalProperties"], keyPointerPath)) { return error; } } } else if (this.trackUnknownProperties && !this.knownPropertyPaths[keyPointerPath]) { this.unknownPropertyPaths[keyPointerPath] = true; } } else if (this.trackUnknownProperties) { this.knownPropertyPaths[keyPointerPath] = true; delete this.unknownPropertyPaths[keyPointerPath]; } } return null; }; ValidatorContext.prototype.validateObjectDependencies = function validateObjectDependencies(data, schema, dataPointerPath) { var error; if (schema.dependencies !== undefined) { for (var depKey in schema.dependencies) { if (data[depKey] !== undefined) { var dep = schema.dependencies[depKey]; if (typeof dep === "string") { if (data[dep] === undefined) { error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: dep}, '', '', null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies"); if (this.handleError(error)) { return error; } } } else if (Array.isArray(dep)) { for (var i = 0; i < dep.length; i++) { var requiredKey = dep[i]; if (data[requiredKey] === undefined) { error = this.createError(ErrorCodes.OBJECT_DEPENDENCY_KEY, {key: depKey, missing: requiredKey}, '', '/' + i, null, data, schema).prefixWith(null, depKey).prefixWith(null, "dependencies"); if (this.handleError(error)) { return error; } } } } else { if (error = this.validateAll(data, dep, [], ["dependencies", depKey], dataPointerPath)) { return error; } } } } } return null; }; ValidatorContext.prototype.validateCombinations = function validateCombinations(data, schema, dataPointerPath) { return this.validateAllOf(data, schema, dataPointerPath) || this.validateAnyOf(data, schema, dataPointerPath) || this.validateOneOf(data, schema, dataPointerPath) || this.validateNot(data, schema, dataPointerPath) || null; }; ValidatorContext.prototype.validateAllOf = function validateAllOf(data, schema, dataPointerPath) { if (schema.allOf === undefined) { return null; } var error; for (var i = 0; i < schema.allOf.length; i++) { var subSchema = schema.allOf[i]; if (error = this.validateAll(data, subSchema, [], ["allOf", i], dataPointerPath)) { return error; } } return null; }; ValidatorContext.prototype.validateAnyOf = function validateAnyOf(data, schema, dataPointerPath) { if (schema.anyOf === undefined) { return null; } var errors = []; var startErrorCount = this.errors.length; var oldUnknownPropertyPaths, oldKnownPropertyPaths; if (this.trackUnknownProperties) { oldUnknownPropertyPaths = this.unknownPropertyPaths; oldKnownPropertyPaths = this.knownPropertyPaths; } var errorAtEnd = true; for (var i = 0; i < schema.anyOf.length; i++) { if (this.trackUnknownProperties) { this.unknownPropertyPaths = {}; this.knownPropertyPaths = {}; } var subSchema = schema.anyOf[i]; var errorCount = this.errors.length; var error = this.validateAll(data, subSchema, [], ["anyOf", i], dataPointerPath); if (error === null && errorCount === this.errors.length) { this.errors = this.errors.slice(0, startErrorCount); if (this.trackUnknownProperties) { for (var knownKey in this.knownPropertyPaths) { oldKnownPropertyPaths[knownKey] = true; delete oldUnknownPropertyPaths[knownKey]; } for (var unknownKey in this.unknownPropertyPaths) { if (!oldKnownPropertyPaths[unknownKey]) { oldUnknownPropertyPaths[unknownKey] = true; } } // We need to continue looping so we catch all the property definitions, but we don't want to return an error errorAtEnd = false; continue; } return null; } if (error) { errors.push(error.prefixWith(null, "" + i).prefixWith(null, "anyOf")); } } if (this.trackUnknownProperties) { this.unknownPropertyPaths = oldUnknownPropertyPaths; this.knownPropertyPaths = oldKnownPropertyPaths; } if (errorAtEnd) { errors = errors.concat(this.errors.slice(startErrorCount)); this.errors = this.errors.slice(0, startErrorCount); return this.createError(ErrorCodes.ANY_OF_MISSING, {}, "", "/anyOf", errors, data, schema); } }; ValidatorContext.prototype.validateOneOf = function validateOneOf(data, schema, dataPointerPath) { if (schema.oneOf === undefined) { return null; } var validIndex = null; var errors = []; var startErrorCount = this.errors.length; var oldUnknownPropertyPaths, oldKnownPropertyPaths; if (this.trackUnknownProperties) { oldUnknownPropertyPaths = this.unknownPropertyPaths; oldKnownPropertyPaths = this.knownPropertyPaths; } for (var i = 0; i < schema.oneOf.length; i++) { if (this.trackUnknownProperties) { this.unknownPropertyPaths = {}; this.knownPropertyPaths = {}; } var subSchema = schema.oneOf[i]; var errorCount = this.errors.length; var error = this.validateAll(data, subSchema, [], ["oneOf", i], dataPointerPath); if (error === null && errorCount === this.errors.length) { if (validIndex === null) { validIndex = i; } else { this.errors = this.errors.slice(0, startErrorCount); return this.createError(ErrorCodes.ONE_OF_MULTIPLE, {index1: validIndex, index2: i}, "", "/oneOf", null, data, schema); } if (this.trackUnknownProperties) { for (var knownKey in this.knownPropertyPaths) { oldKnownPropertyPaths[knownKey] = true; delete oldUnknownPropertyPaths[knownKey]; } for (var unknownKey in this.unknownPropertyPaths) { if (!oldKnownPropertyPaths[unknownKey]) { oldUnknownPropertyPaths[unknownKey] = true; } } } } else if (error) { errors.push(error); } } if (this.trackUnknownProperties) { this.unknownPropertyPaths = oldUnknownPropertyPaths; this.knownPropertyPaths = oldKnownPropertyPaths; } if (validIndex === null) { errors = errors.concat(this.errors.slice(startErrorCount)); this.errors = this.errors.slice(0, startErrorCount); return this.createError(ErrorCodes.ONE_OF_MISSING, {}, "", "/oneOf", errors, data, schema); } else { this.errors = this.errors.slice(0, startErrorCount); } return null; }; ValidatorContext.prototype.validateNot = function validateNot(data, schema, dataPointerPath) { if (schema.not === undefined) { return null; } var oldErrorCount = this.errors.length; var oldUnknownPropertyPaths, oldKnownPropertyPaths; if (this.trackUnknownProperties) { oldUnknownPropertyPaths = this.unknownPropertyPaths; oldKnownPropertyPaths = this.knownPropertyPaths; this.unknownPropertyPaths = {}; this.knownPropertyPaths = {}; } var error = this.validateAll(data, schema.not, null, null, dataPointerPath); var notErrors = this.errors.slice(oldErrorCount); this.errors = this.errors.slice(0, oldErrorCount); if (this.trackUnknownProperties) { this.unknownPropertyPaths = oldUnknownPropertyPaths; this.knownPropertyPaths = oldKnownPropertyPaths; } if (error === null && notErrors.length === 0) { return this.createError(ErrorCodes.NOT_PASSED, {}, "", "/not", null, data, schema); } return null; }; ValidatorContext.prototype.validateHypermedia = function validateCombinations(data, schema, dataPointerPath) { if (!schema.links) { return null; } var error; for (var i = 0; i < schema.links.length; i++) { var ldo = schema.links[i]; if (ldo.rel === "describedby") { var template = new UriTemplate(ldo.href); var allPresent = true; for (var j = 0; j < template.varNames.length; j++) { if (!(template.varNames[j] in data)) { allPresent = false; break; } } if (allPresent) { var schemaUrl = template.fillFromObject(data); var subSchema = {"$ref": schemaUrl}; if (error = this.validateAll(data, subSchema, [], ["links", i], dataPointerPath)) { return error; } } } } }; // parseURI() and resolveUrl() are from https://gist.github.com/1088850 // - released as public domain by author ("Yaffle") - see comments on gist function parseURI(url) { var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/); // authority = '//' + user + ':' + pass '@' + hostname + ':' port return (m ? { href : m[0] || '', protocol : m[1] || '', authority: m[2] || '', host : m[3] || '', hostname : m[4] || '', port : m[5] || '', pathname : m[6] || '', search : m[7] || '', hash : m[8] || '' } : null); } function resolveUrl(base, href) {// RFC 3986 function removeDotSegments(input) { var output = []; input.replace(/^(\.\.?(\/|$))+/, '') .replace(/\/(\.(\/|$))+/g, '/') .replace(/\/\.\.$/, '/../') .replace(/\/?[^\/]*/g, function (p) { if (p === '/..') { output.pop(); } else { output.push(p); } }); return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : ''); } href = parseURI(href || ''); base = parseURI(base || ''); return !href || !base ? null : (href.protocol || base.protocol) + (href.protocol || href.authority ? href.authority : base.authority) + removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) + (href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) + href.hash; } function getDocumentUri(uri) { return uri.split('#')[0]; } function normSchema(schema, baseUri) { if (schema && typeof schema === "object") { if (baseUri === undefined) { baseUri = schema.id; } else if (typeof schema.id === "string") { baseUri = resolveUrl(baseUri, schema.id); schema.id = baseUri; } if (Array.isArray(schema)) { for (var i = 0; i < schema.length; i++) { normSchema(schema[i], baseUri); } } else { if (typeof schema['$ref'] === "string") { schema['$ref'] = resolveUrl(baseUri, schema['$ref']); } for (var key in schema) { if (key !== "enum") { normSchema(schema[key], baseUri); } } } } } function defaultErrorReporter(language) { language = language || 'en'; var errorMessages = languages[language]; return function (error) { var messageTemplate = errorMessages[error.code] || ErrorMessagesDefault[error.code]; if (typeof messageTemplate !== 'string') { return "Unknown error code " + error.code + ": " + JSON.stringify(error.messageParams); } var messageParams = error.params; // Adapted from Crockford's supplant() return messageTemplate.replace(/\{([^{}]*)\}/g, function (whole, varName) { var subValue = messageParams[varName]; return typeof subValue === 'string' || typeof subValue === 'number' ? subValue : whole; }); }; } var ErrorCodes = { INVALID_TYPE: 0, ENUM_MISMATCH: 1, ANY_OF_MISSING: 10, ONE_OF_MISSING: 11, ONE_OF_MULTIPLE: 12, NOT_PASSED: 13, // Numeric errors NUMBER_MULTIPLE_OF: 100, NUMBER_MINIMUM: 101, NUMBER_MINIMUM_EXCLUSIVE: 102, NUMBER_MAXIMUM: 103, NUMBER_MAXIMUM_EXCLUSIVE: 104, NUMBER_NOT_A_NUMBER: 105, // String errors STRING_LENGTH_SHORT: 200, STRING_LENGTH_LONG: 201, STRING_PATTERN: 202, // Object errors OBJECT_PROPERTIES_MINIMUM: 300, OBJECT_PROPERTIES_MAXIMUM: 301, OBJECT_REQUIRED: 302, OBJECT_ADDITIONAL_PROPERTIES: 303, OBJECT_DEPENDENCY_KEY: 304, // Array errors ARRAY_LENGTH_SHORT: 400, ARRAY_LENGTH_LONG: 401, ARRAY_UNIQUE: 402, ARRAY_ADDITIONAL_ITEMS: 403, // Custom/user-defined errors FORMAT_CUSTOM: 500, KEYWORD_CUSTOM: 501, // Schema structure CIRCULAR_REFERENCE: 600, // Non-standard validation options UNKNOWN_PROPERTY: 1000 }; var ErrorCodeLookup = {}; for (var key in ErrorCodes) { ErrorCodeLookup[ErrorCodes[key]] = key; } var ErrorMessagesDefault = { INVALID_TYPE: "Invalid type: {type} (expected {expected})", ENUM_MISMATCH: "No enum match for: {value}", ANY_OF_MISSING: "Data does not match any schemas from \"anyOf\"", ONE_OF_MISSING: "Data does not match any schemas from \"oneOf\"", ONE_OF_MULTIPLE: "Data is valid against more than one schema from \"oneOf\": indices {index1} and {index2}", NOT_PASSED: "Data matches schema from \"not\"", // Numeric errors NUMBER_MULTIPLE_OF: "Value {value} is not a multiple of {multipleOf}", NUMBER_MINIMUM: "Value {value} is less than minimum {minimum}", NUMBER_MINIMUM_EXCLUSIVE: "Value {value} is equal to exclusive minimum {minimum}", NUMBER_MAXIMUM: "Value {value} is greater than maximum {maximum}", NUMBER_MAXIMUM_EXCLUSIVE: "Value {value} is equal to exclusive maximum {maximum}", NUMBER_NOT_A_NUMBER: "Value {value} is not a valid number", // String errors STRING_LENGTH_SHORT: "String is too short ({length} chars), minimum {minimum}", STRING_LENGTH_LONG: "String is too long ({length} chars), maximum {maximum}", STRING_PATTERN: "String does not match pattern: {pattern}", // Object errors OBJECT_PROPERTIES_MINIMUM: "Too few properties defined ({propertyCount}), minimum {minimum}", OBJECT_PROPERTIES_MAXIMUM: "Too many properties defined ({propertyCount}), maximum {maximum}", OBJECT_REQUIRED: "Missing required property: {key}", OBJECT_ADDITIONAL_PROPERTIES: "Additional properties not allowed", OBJECT_DEPENDENCY_KEY: "Dependency failed - key must exist: {missing} (due to key: {key})", // Array errors ARRAY_LENGTH_SHORT: "Array is too short ({length}), minimum {minimum}", ARRAY_LENGTH_LONG: "Array is too long ({length}), maximum {maximum}", ARRAY_UNIQUE: "Array items are not unique (indices {match1} and {match2})", ARRAY_ADDITIONAL_ITEMS: "Additional items not allowed", // Format errors FORMAT_CUSTOM: "Format validation failed ({message})", KEYWORD_CUSTOM: "Keyword failed: {key} ({message})", // Schema structure CIRCULAR_REFERENCE: "Circular $refs: {urls}", // Non-standard validation options UNKNOWN_PROPERTY: "Unknown property (not in schema)" }; function ValidationError(code, params, dataPath, schemaPath, subErrors) { Error.call(this); if (code === undefined) { throw new Error ("No error code supplied: " + schemaPath); } this.message = ''; this.params = params; this.code = code; this.dataPath = dataPath || ""; this.schemaPath = schemaPath || ""; this.subErrors = subErrors || null; var err = new Error(this.message); this.stack = err.stack || err.stacktrace; if (!this.stack) { try { throw err; } catch(err) { this.stack = err.stack || err.stacktrace; } } } ValidationError.prototype = Object.create(Error.prototype); ValidationError.prototype.constructor = ValidationError; ValidationError.prototype.name = 'ValidationError'; ValidationError.prototype.prefixWith = function (dataPrefix, schemaPrefix) { if (dataPrefix !== null) { dataPrefix = dataPrefix.replace(/~/g, "~0").replace(/\//g, "~1"); this.dataPath = "/" + dataPrefix + this.dataPath; } if (schemaPrefix !== null) { schemaPrefix = schemaPrefix.replace(/~/g, "~0").replace(/\//g, "~1"); this.schemaPath = "/" + schemaPrefix + this.schemaPath; } if (this.subErrors !== null) { for (var i = 0; i < this.subErrors.length; i++) { this.subErrors[i].prefixWith(dataPrefix, schemaPrefix); } } return this; }; function isTrustedUrl(baseUrl, testUrl) { if(testUrl.substring(0, baseUrl.length) === baseUrl){ var remainder = testUrl.substring(baseUrl.length); if ((testUrl.length > 0 && testUrl.charAt(baseUrl.length - 1) === "/") || remainder.charAt(0) === "#" || remainder.charAt(0) === "?") { return true; } } return false; } var languages = {}; function createApi(language) { var globalContext = new ValidatorContext(); var currentLanguage; var customErrorReporter; var api = { setErrorReporter: function (reporter) { if (typeof reporter === 'string') { return this.language(reporter); } customErrorReporter = reporter; return true; }, addFormat: function () { globalContext.addFormat.apply(globalContext, arguments); }, language: function (code) { if (!code) { return currentLanguage; } if (!languages[code]) { code = code.split('-')[0]; // fall back to base language } if (languages[code]) { currentLanguage = code; return code; // so you can tell if fall-back has happened } return false; }, addLanguage: function (code, messageMap) { var key; for (key in ErrorCodes) { if (messageMap[key] && !messageMap[ErrorCodes[key]]) { messageMap[ErrorCodes[key]] = messageMap[key]; } } var rootCode = code.split('-')[0]; if (!languages[rootCode]) { // use for base language if not yet defined languages[code] = messageMap; languages[rootCode] = messageMap; } else { languages[code] = Object.create(languages[rootCode]); for (key in messageMap) { if (typeof languages[rootCode][key] === 'undefined') { languages[rootCode][key] = messageMap[key]; } languages[code][key] = messageMap[key]; } } return this; }, freshApi: function (language) { var result = createApi(); if (language) { result.language(language); } return result; }, validate: function (data, schema, checkRecursive, banUnknownProperties) { var def = defaultErrorReporter(currentLanguage); var errorReporter = customErrorReporter ? function (error, data, schema) { return customErrorReporter(error, data, schema) || def(error, data, schema); } : def; var context = new ValidatorContext(globalContext, false, errorReporter, checkRecursive, banUnknownProperties); if (typeof schema === "string") { schema = {"$ref": schema}; } context.addSchema("", schema); var error = context.validateAll(data, schema, null, null, ""); if (!error && banUnknownProperties) { error = context.banUnknownProperties(data, schema); } this.error = error; this.missing = context.missing; this.valid = (error === null); return this.valid; }, validateResult: function () { var result = {}; this.validate.apply(result, arguments); return result; }, validateMultiple: function (data, schema, checkRecursive, banUnknownProperties) { var def = defaultErrorReporter(currentLanguage); var errorReporter = customErrorReporter ? function (error, data, schema) { return customErrorReporter(error, data, schema) || def(error, data, schema); } : def; var context = new ValidatorContext(globalContext, true, errorReporter, checkRecursive, banUnknownProperties); if (typeof schema === "string") { schema = {"$ref": schema}; } context.addSchema("", schema); context.validateAll(data, schema, null, null, ""); if (banUnknownProperties) { context.banUnknownProperties(data, schema); } var result = {}; result.errors = context.errors; result.missing = context.missing; result.valid = (result.errors.length === 0); return result; }, addSchema: function () { return globalContext.addSchema.apply(globalContext, arguments); }, getSchema: function () { return globalContext.getSchema.apply(globalContext, arguments); }, getSchemaMap: function () { return globalContext.getSchemaMap.apply(globalContext, arguments); }, getSchemaUris: function () { return globalContext.getSchemaUris.apply(globalContext, arguments); }, getMissingUris: function () { return globalContext.getMissingUris.apply(globalContext, arguments); }, dropSchemas: function () { globalContext.dropSchemas.apply(globalContext, arguments); }, defineKeyword: function () { globalContext.defineKeyword.apply(globalContext, arguments); }, defineError: function (codeName, codeNumber, defaultMessage) { if (typeof codeName !== 'string' || !/^[A-Z]+(_[A-Z]+)*$/.test(codeName)) { throw new Error('Code name must be a string in UPPER_CASE_WITH_UNDERSCORES'); } if (typeof codeNumber !== 'number' || codeNumber%1 !== 0 || codeNumber < 10000) { throw new Error('Code number must be an integer > 10000'); } if (typeof ErrorCodes[codeName] !== 'undefined') { throw new Error('Error already defined: ' + codeName + ' as ' + ErrorCodes[codeName]); } if (typeof ErrorCodeLookup[codeNumber] !== 'undefined') { throw new Error('Error code already used: ' + ErrorCodeLookup[codeNumber] + ' as ' + codeNumber); } ErrorCodes[codeName] = codeNumber; ErrorCodeLookup[codeNumber] = codeName; ErrorMessagesDefault[codeName] = ErrorMessagesDefault[codeNumber] = defaultMessage; for (var langCode in languages) { var language = languages[langCode]; if (language[codeName]) { language[codeNumber] = language[codeNumber] || language[codeName]; } } }, reset: function () { globalContext.reset(); this.error = null; this.missing = []; this.valid = true; }, missing: [], error: null, valid: true, normSchema: normSchema, resolveUrl: resolveUrl, getDocumentUri: getDocumentUri, errorCodes: ErrorCodes }; api.language(language || 'en'); return api; } var tv4 = createApi(); tv4.addLanguage('en-gb', ErrorMessagesDefault); //legacy property tv4.tv4 = tv4; return tv4; // used by _header.js to globalise. })); /** FILE: lib/Math.uuid.js **/ /*! Math.uuid.js (v1.4) http://www.broofa.com mailto:robert@broofa.com Copyright (c) 2010 Robert Kieffer Dual licensed under the MIT and GPL licenses. ******** Changes within remoteStorage.js: 2012-10-31: - added AMD wrapper <niklas@unhosted.org> - moved extensions for Math object into exported object. */ /* * Generate a random uuid. * * USAGE: Math.uuid(length, radix) * length - the desired number of characters * radix - the number of allowable values for each character. * * EXAMPLES: * // No arguments - returns RFC4122, version 4 ID * >>> Math.uuid() * "92329D39-6F5C-4520-ABFC-AAB64544E172" * * // One argument - returns ID of the specified length * >>> Math.uuid(15) // 15 character ID (default base=62) * "VcydxgltxrVZSTV" * * // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62) * >>> Math.uuid(8, 2) // 8 character ID (base=2) * "01001010" * >>> Math.uuid(8, 10) // 8 character ID (base=10) * "47473046" * >>> Math.uuid(8, 16) // 8 character ID (base=16) * "098F4D35" */ // Private array of chars to use var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); Math.uuid = function (len, radix) { var chars = CHARS, uuid = [], i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | Math.random()*16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); }; /** FILE: src/baseclient.js **/ (function (global) { function deprecate(thing, replacement) { console.log('WARNING: ' + thing + ' is deprecated. Use ' + replacement + ' instead.'); } var RS = RemoteStorage; /** * Class: RemoteStorage.BaseClient * * Provides a high-level interface to access data below a given root path. * * A BaseClient deals with three types of data: folders, objects and files. * * <getListing> returns a mapping of all items within a folder. Items that * end with a forward slash ("/") are child folders. For instance: * { * 'folder/': true, * 'document.txt': true * } * * <getObject> / <storeObject> operate on JSON objects. Each object has a type. * * <getFile> / <storeFile> operates on files. Each file has a MIME type. * * <remove> operates on either objects or files (but not folders, folders are * created and removed implictly). */ RS.BaseClient = function (storage, base) { if (base[base.length - 1] !== '/') { throw "Not a folder: " + base; } if (base === '/') { // allow absolute and relative paths for the root scope. this.makePath = function (path) { return (path[0] === '/' ? '' : '/') + path; }; } /** * Property: storage * * The <RemoteStorage> instance this <BaseClient> operates on. */ this.storage = storage; /** * Property: base * * Base path this <BaseClient> operates on. * * For the module's privateClient this would be /<moduleName>/, for the * corresponding publicClient /public/<moduleName>/. */ this.base = base; var parts = this.base.split('/'); if (parts.length > 2) { this.moduleName = parts[1]; } else { this.moduleName = 'root'; } // Defined in baseclient/types.js /** * Property: schemas * * Contains schema objects of all types known to the BaseClient instance **/ /** * Event: change * * Emitted when a node changes * * Arguments: * event - Event object containing information about the changed node * * (start code) * { * path: path, // Absolute path of the changed node, from the storage root * relativePath: relativePath, // Path of the changed node, relative to this baseclient's scope root * origin: 'window', 'local', 'remote', or 'conflict' // emitted by user action within the app, local data store, remote sync, or versioning conflicts * oldValue: oldBody, // Old body of the changed node (local version in conflicts; undefined if creation) * newValue: newBody, // New body of the changed node (remote version in conflicts; undefined if deletion) * lastCommonValue: lastCommonValue, //most recent known common ancestor body of 'yours' and 'theirs' in case of conflict * oldContentType: oldContentType, // Old contentType of the changed node ('yours' for conflicts; undefined if creation) * newContentType: newContentType, // New contentType of the changed node ('theirs' for conflicts; undefined if deletion) * lastCommonContentType: lastCommonContentType // Most recent known common ancestor contentType of 'yours' and 'theirs' in case of conflict * } * (end code) * * Example of an event with origin 'local' (fired on page load): * * (start code) * { * path: '/public/design/color.txt', * relativePath: 'color.txt', * origin: 'local', * oldValue: undefined, * newValue: 'white', * oldContentType: undefined, * newContentType: 'text/plain' * } * (end code) * * Example of a conflict: * Say you changed 'color.txt' from 'white' to 'blue'; if you have set `RemoteStorage.config.changeEvents.window` to `true`, * then you will receive: * * (start code) * { * path: '/public/design/color.txt', * relativePath: 'color.txt', * origin: 'window', * oldValue: 'white', * newValue: 'blue', * oldContentType: 'text/plain', * newContentType: 'text/plain' * } * (end code) * * But when this change is pushed out by asynchronous synchronization, this change may rejected by the * server, if the remote version has in the meantime changed from 'white' to for instance 'red'; this will then lead to a change * event with origin 'conflict' (usually a few seconds after the event with origin 'window', if you had that activated). Note * that since you already changed it from 'white' to 'blue' in the local version a few seconds ago, `oldValue` is now your local * value of 'blue': * * (start code) * { * path: '/public/design/color.txt', * relativePath: 'color.txt', * origin: 'conflict', * oldValue: 'blue', * newValue: 'red', * lastCommonValue: 'white', * oldContentType: 'text/plain, * newContentType: 'text/plain' * lastCommonContentType: 'text/plain' * } * (end code) * * In practice, you should always redraw your views to display the content of the `newValue` field when a change event is received, * regardless of its origin. Events with origin 'local' are fired conveniently during the page load, so that you can fill your views * when the page loads. Events with origin 'window' are fired whenever you change a value by calling a method on the baseClient; * these are disabled by default. Events with origin 'remote' are fired when remote changes are discovered during sync (only for caching * startegies 'SEEN' and 'ALL'). Events with origin 'conflict' are fired when a conflict occurs while pushing out your local changes to * the remote store in asynchronous synchronization (see example above). **/ RS.eventHandling(this, 'change'); this.on = this.on.bind(this); storage.onChange(this.base, this._fireChange.bind(this)); }; RS.BaseClient.prototype = { extend: function (object) { for (var key in object) { this[key] = object[key]; } return this; }, /** * Method: scope * * Returns a new <BaseClient> operating on a subpath of the current <base> path. */ scope: function (path) { return new RS.BaseClient(this.storage, this.makePath(path)); }, // folder operations /** * Method: getListing * * Get a list of child nodes below a given path. * * The callback semantics of getListing are identical to those of getObject. * * Parameters: * path - The path to query. It MUST end with a forward slash. * maxAge - Either false or the maximum age of cached listing in * milliseconds. Defaults to false in anonymous mode and to * 2*syncInterval in connected mode. * * Returns: * * A promise for an object, representing child nodes. If the maxAge * requirement cannot be met because of network problems, this promise * will be rejected. If the maxAge requirement is set to false or the * library is in offline state, the promise will always be fulfilled with * data from the local store. * * Keys ending in a forward slash represent *folder nodes*, while all * other keys represent *data nodes*. * * For spec versions <= 01, the data node information will contain only * the item's ETag. For later spec versions, it will also contain the * content type and -length of the item. * * Example: * (start code) * client.getListing('', false).then(function (listing) { * // listing is for instance: * // { * // 'folder/': true, * // 'document.txt': true * // } * }); * (end code) */ getListing: function (path, maxAge) { if (typeof(path) !== 'string') { path = ''; } else if (path.length > 0 && path[path.length - 1] !== '/') { Promise.reject("Not a folder: " + path); } return this.storage.get(this.makePath(path), maxAge).then( function (r) { return (r.statusCode === 404) ? {} : r.body; } ); }, /** * Method: getAll * * Get all objects directly below a given path. * * Parameters: * path - Path to the folder. * maxAge - Either false or the maximum age of cached objects in * milliseconds. Defaults to false in anonymous mode and to * 2*syncInterval in connected mode. * * Returns: * A promise for an object in the form { path : object, ... }. If the * maxAge requirement cannot be met because of network problems, this * promise will be rejected. If the maxAge requirement is set to false, * the promise will always be fulfilled with data from the local store. * * For items that are not JSON-stringified objects (e.g. stored using * `storeFile` instead of `storeObject`), the object's value is filled in * with `true`. * * Example: * (start code) * client.getAll('', false).then(function (objects) { * for (var key in objects) { * console.log('- ' + key + ': ', objects[key]); * } * }); * (end code) */ getAll: function (path, maxAge) { if (typeof(path) !== 'string') { path = ''; } else if (path.length > 0 && path[path.length - 1] !== '/') { return Promise.reject("Not a folder: " + path); } return this.storage.get(this.makePath(path), maxAge).then(function (r) { if (r.statusCode === 404) { return {}; } if (typeof(r.body) === 'object') { var keys = Object.keys(r.body); if (keys.length === 0) { // treat this like 404. it probably means a folder listing that // has changes that haven't been pushed out yet. return {}; } var calls = keys.map(function (key) { return this.storage.get(this.makePath(path + key), maxAge) .then(function (o) { if (typeof(o.body) === 'string') { try { o.body = JSON.parse(o.body); } catch (e) { } } if (typeof(o.body) === 'object') { r.body[key] = o.body; } }); }.bind(this)); return Promise.all(calls).then(function () { return r.body; }); } }.bind(this)); }, // file operations /** * Method: getFile * * Get the file at the given path. A file is raw data, as opposed to * a JSON object (use <getObject> for that). * * Except for the return value structure, getFile works exactly like * getObject. * * Parameters: * path - See getObject. * maxAge - Either false or the maximum age of cached file in * milliseconds. Defaults to false in anonymous mode and to * 2*syncInterval in connected mode. * * Returns: * A promise for an object: * * mimeType - String representing the MIME Type of the document. * data - Raw data of the document (either a string or an ArrayBuffer) * * If the maxAge requirement cannot be met because of network problems, this * promise will be rejected. If the maxAge requirement is set to false, the * promise will always be fulfilled with data from the local store. * * Example: * (start code) * // Display an image: * client.getFile('path/to/some/image', false).then(function (file) { * var blob = new Blob([file.data], { type: file.mimeType }); * var targetElement = document.findElementById('my-image-element'); * targetElement.src = window.URL.createObjectURL(blob); * }); * (end code) */ getFile: function (path, maxAge) { if (typeof(path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.getFile must be a string'); } return this.storage.get(this.makePath(path), maxAge).then(function (r) { return { data: r.body, contentType: r.contentType, revision: r.revision // (this is new) }; }); }, /** * Method: storeFile * * Store raw data at a given path. * * Parameters: * mimeType - MIME media type of the data being stored * path - path relative to the module root. MAY NOT end in a forward slash. * data - string, ArrayBuffer or ArrayBufferView of raw data to store * * The given mimeType will later be returned, when retrieving the data * using <getFile>. * * Example (UTF-8 data): * (start code) * client.storeFile('text/html', 'index.html', '<h1>Hello World!</h1>'); * (end code) * * Example (Binary data): * (start code) * // MARKUP: * <input type="file" id="file-input"> * // CODE: * var input = document.getElementById('file-input'); * var file = input.files[0]; * var fileReader = new FileReader(); * * fileReader.onload = function () { * client.storeFile(file.type, file.name, fileReader.result); * }; * * fileReader.readAsArrayBuffer(file); * (end code) * */ storeFile: function (mimeType, path, body) { if (typeof(mimeType) !== 'string') { return Promise.reject('Argument \'mimeType\' of baseClient.storeFile must be a string'); } if (typeof(path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.storeFile must be a string'); } if (typeof(body) !== 'string' && typeof(body) !== 'object') { return Promise.reject('Argument \'body\' of baseClient.storeFile must be a string, ArrayBuffer, or ArrayBufferView'); } if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) { console.warn('WARNING: Editing a document to which only read access (\'r\') was claimed'); } return this.storage.put(this.makePath(path), body, mimeType).then(function (r) { if (r.statusCode === 200 || r.statusCode === 201) { return r.revision; } else { return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode); } }.bind(this)); }, // object operations /** * Method: getObject * * Get a JSON object from given path. * * Parameters: * path - Relative path from the module root (without leading slash). * maxAge - Either false or the maximum age of cached object in * milliseconds. Defaults to false in anonymous mode and to * 2*syncInterval in connected mode. * * Returns: * A promise for the object. If the maxAge requirement cannot be met * because of network problems, this promise will be rejected. If the * maxAge requirement is set to false, the promise will always be * fulfilled with data from the local store. * * Example: * (start code) * client.getObject('/path/to/object', false). * then(function (object) { * // object is either an object or null * }); * (end code) */ getObject: function (path, maxAge) { if (typeof(path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.getObject must be a string'); } return this.storage.get(this.makePath(path), maxAge).then(function (r) { if (typeof(r.body) === 'object') { // will be the case for documents stored with rs.js <= 0.10.0-beta2 return r.body; } else if (typeof(r.body) === 'string') { try { return JSON.parse(r.body); } catch (e) { throw "Not valid JSON: " + this.makePath(path); } } else if (typeof(r.body) !== 'undefined' && r.statusCode === 200) { return Promise.reject("Not an object: " + this.makePath(path)); } }.bind(this)); }, /** * Method: storeObject * * Store object at given path. Triggers synchronization. * * Parameters: * * type - unique type of this object within this module. See description below. * path - path relative to the module root. * object - an object to be saved to the given node. It must be serializable as JSON. * * Returns: * A promise to store the object. The promise fails with a ValidationError, when validations fail. * * * What about the type?: * * A great thing about having data on the web, is to be able to link to * it and rearrange it to fit the current circumstances. To facilitate * that, eventually you need to know how the data at hand is structured. * For documents on the web, this is usually done via a MIME type. The * MIME type of JSON objects however, is always application/json. * To add that extra layer of "knowing what this object is", remoteStorage * aims to use <JSON-LD at http://json-ld.org/>. * A first step in that direction, is to add a *@context attribute* to all * JSON data put into remoteStorage. * Now that is what the *type* is for. * * Within remoteStorage.js, @context values are built using three components: * http://remotestorage.io/spec/modules/ - A prefix to guarantee uniqueness * the module name - module names should be unique as well * the type given here - naming this particular kind of object within this module * * In retrospect that means, that whenever you introduce a new "type" in calls to * storeObject, you should make sure that once your code is in the wild, future * versions of the code are compatible with the same JSON structure. * * How to define types?: * * See <declareType> for examples. */ storeObject: function (typeAlias, path, object) { if (typeof(typeAlias) !== 'string') { return Promise.reject('Argument \'typeAlias\' of baseClient.storeObject must be a string'); } if (typeof(path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.storeObject must be a string'); } if (typeof(object) !== 'object') { return Promise.reject('Argument \'object\' of baseClient.storeObject must be an object'); } this._attachType(object, typeAlias); try { var validationResult = this.validate(object); if (! validationResult.valid) { return Promise.reject(validationResult); } } catch(exc) { return Promise.reject(exc); } return this.storage.put(this.makePath(path), JSON.stringify(object), 'application/json; charset=UTF-8').then(function (r) { if (r.statusCode === 200 || r.statusCode === 201) { return r.revision; } else { return Promise.reject("Request (PUT " + this.makePath(path) + ") failed with status: " + r.statusCode); } }.bind(this)); }, // generic operations /** * Method: remove * * Remove node at given path from storage. Triggers synchronization. * * Parameters: * path - Path relative to the module root. */ remove: function (path) { if (typeof(path) !== 'string') { return Promise.reject('Argument \'path\' of baseClient.remove must be a string'); } if (!this.storage.access.checkPathPermission(this.makePath(path), 'rw')) { console.warn('WARNING: Removing a document to which only read access (\'r\') was claimed'); } return this.storage.delete(this.makePath(path)); }, cache: function (path, strategy) { if (typeof(path) !== 'string') { throw 'Argument \'path\' of baseClient.cache must be a string'; } if (strategy === false) { deprecate('caching strategy <false>', '<"FLUSH">'); strategy = 'FLUSH'; } else if (strategy === undefined) { strategy = 'ALL'; } else if (typeof(strategy) !== 'string') { deprecate('that caching strategy', '<"ALL">'); strategy = 'ALL'; } if (strategy !== 'FLUSH' && strategy !== 'SEEN' && strategy !== 'ALL') { throw 'Argument \'strategy\' of baseclient.cache must be one of ' + '["FLUSH", "SEEN", "ALL"]'; } this.storage.caching.set(this.makePath(path), strategy); return this; }, flush: function (path) { return this.storage.local.flush(path); }, makePath: function (path) { return this.base + (path || ''); }, _fireChange: function (event) { if (RemoteStorage.config.changeEvents[event.origin]) { ['new', 'old', 'lastCommon'].forEach(function (fieldNamePrefix) { if ((!event[fieldNamePrefix+'ContentType']) || (/^application\/(.*)json(.*)/.exec(event[fieldNamePrefix+'ContentType']))) { if (typeof(event[fieldNamePrefix+'Value']) === 'string') { try { event[fieldNamePrefix+'Value'] = JSON.parse(event[fieldNamePrefix+'Value']); } catch(e) { } } } }); this._emit('change', event); } }, _cleanPath: RemoteStorage.util.cleanPath, /** * Method: getItemURL * * Retrieve full URL of item * * Parameters: * path - Path relative to the module root. */ getItemURL: function (path) { if (typeof(path) !== 'string') { throw 'Argument \'path\' of baseClient.getItemURL must be a string'; } if (this.storage.connected) { path = this._cleanPath( this.makePath(path) ); return this.storage.remote.href + path; } else { return undefined; } }, uuid: function () { return Math.uuid(); } }; /** * Method: RS#scope * * Returns a new <RS.BaseClient> scoped to the given path. * * Parameters: * path - Root path of new BaseClient. * * * Example: * (start code) * * var foo = remoteStorage.scope('/foo/'); * * // PUTs data "baz" to path /foo/bar * foo.storeFile('text/plain', 'bar', 'baz'); * * var something = foo.scope('something/'); * * // GETs listing from path /foo/something/bla/ * something.getListing('bla/'); * * (end code) * */ RS.BaseClient._rs_init = function () { RS.prototype.scope = function (path) { if (typeof(path) !== 'string') { throw 'Argument \'path\' of baseClient.scope must be a string'; } if (!this.access.checkPathPermission(path, 'r')) { var escapedPath = path.replace(/(['\\])/g, '\\$1'); console.warn('WARNING: please call remoteStorage.access.claim(\'' + escapedPath + '\', \'r\') (read only) or remoteStorage.access.claim(\'' + escapedPath + '\', \'rw\') (read/write) first'); } return new RS.BaseClient(this, path); }; }; /* e.g.: remoteStorage.defineModule('locations', function (priv, pub) { return { exports: { features: priv.scope('features/').defaultType('feature'), collections: priv.scope('collections/').defaultType('feature-collection'); } }; }); */ // Defined in baseclient/types.js /** * Method: declareType * * Declare a remoteStorage object type using a JSON schema. See * <RemoteStorage.BaseClient.Types> **/ })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/baseclient/types.js **/ (function(global) { /** * Class: RemoteStorage.BaseClient.Types * * - Manages and validates types of remoteStorage objects, using JSON-LD and * JSON Schema * - Adds schema declaration/validation methods to BaseClient instances. **/ RemoteStorage.BaseClient.Types = { // <alias> -> <uri> uris: {}, // <uri> -> <schema> schemas: {}, // <uri> -> <alias> aliases: {}, declare: function(moduleName, alias, uri, schema) { var fullAlias = moduleName + '/' + alias; if (schema.extends) { var extendedAlias; var parts = schema.extends.split('/'); if (parts.length === 1) { extendedAlias = moduleName + '/' + parts.shift(); } else { extendedAlias = parts.join('/'); } var extendedUri = this.uris[extendedAlias]; if (! extendedUri) { throw "Type '" + fullAlias + "' tries to extend unknown schema '" + extendedAlias + "'"; } schema.extends = this.schemas[extendedUri]; } this.uris[fullAlias] = uri; this.aliases[uri] = fullAlias; this.schemas[uri] = schema; }, resolveAlias: function(alias) { return this.uris[alias]; }, getSchema: function(uri) { return this.schemas[uri]; }, inScope: function(moduleName) { var ml = moduleName.length; var schemas = {}; for (var alias in this.uris) { if (alias.substr(0, ml + 1) === moduleName + '/') { var uri = this.uris[alias]; schemas[uri] = this.schemas[uri]; } } return schemas; } }; var SchemaNotFound = function(uri) { var error = new Error("Schema not found: " + uri); error.name = "SchemaNotFound"; return error; }; SchemaNotFound.prototype = Error.prototype; RemoteStorage.BaseClient.Types.SchemaNotFound = SchemaNotFound; /** * Class: RemoteStorage.BaseClient **/ RemoteStorage.BaseClient.prototype.extend({ /** * Method: declareType * * Declare a remoteStorage object type using a JSON schema. * * Parameters: * alias - A type alias/shortname * uri - (optional) JSON-LD URI of the schema. Automatically generated if none given * schema - A JSON Schema object describing the object type * * Example: * * (start code) * client.declareType('todo-item', { * "type": "object", * "properties": { * "id": { * "type": "string" * }, * "title": { * "type": "string" * }, * "finished": { * "type": "boolean" * "default": false * }, * "createdAt": { * "type": "date" * } * }, * "required": ["id", "title"] * }) * (end code) * * Visit <http://json-schema.org> for details on how to use JSON Schema. **/ declareType: function(alias, uri, schema) { if (! schema) { schema = uri; uri = this._defaultTypeURI(alias); } RemoteStorage.BaseClient.Types.declare(this.moduleName, alias, uri, schema); }, /** * Method: validate * * Validate an object against the associated schema. * * Parameters: * object - Object to validate. Must have a @context property. * * Returns: * An object containing information about validation errors **/ validate: function(object) { var schema = RemoteStorage.BaseClient.Types.getSchema(object['@context']); if (schema) { return tv4.validateResult(object, schema); } else { throw new SchemaNotFound(object['@context']); } }, _defaultTypeURI: function(alias) { return 'http://remotestorage.io/spec/modules/' + encodeURIComponent(this.moduleName) + '/' + encodeURIComponent(alias); }, _attachType: function(object, alias) { object['@context'] = RemoteStorage.BaseClient.Types.resolveAlias(this.moduleName + '/' + alias) || this._defaultTypeURI(alias); } }); // Documented in baseclient.js Object.defineProperty(RemoteStorage.BaseClient.prototype, 'schemas', { configurable: true, get: function() { return RemoteStorage.BaseClient.Types.inScope(this.moduleName); } }); })(typeof(window) !== 'undefined' ? window : global); /** FILE: src/modules.js **/ (function () { RemoteStorage.MODULES = {}; /* * Method: RemoteStorage.defineModule * * Method for defining a new remoteStorage data module * * Parameters: * moduleName - Name of the module * builder - Builder function defining the module * * The module builder function should return an object containing another * object called exports, which will be exported to any <RemoteStorage> * instance under the module's name. So when defining a locations module, * like in the example below, it would be accessible via * `remoteStorage.locations`, which would in turn have a `features` and a * `collections` property. * * The function receives a private and a public client, which are both * instances of <RemoteStorage.BaseClient>. In the following example, the * scope of privateClient is `/locations` and the scope of publicClient is * `/public/locations`. * * Example: * (start code) * RemoteStorage.defineModule('locations', function (privateClient, publicClient) { * return { * exports: { * features: privateClient.scope('features/').defaultType('feature'), * collections: privateClient.scope('collections/').defaultType('feature-collection') * } * }; * }); * (end code) */ RemoteStorage.defineModule = function (moduleName, builder) { RemoteStorage.MODULES[moduleName] = builder; Object.defineProperty(RemoteStorage.prototype, moduleName, { configurable: true, get: function () { var instance = this._loadModule(moduleName); Object.defineProperty(this, moduleName, { value: instance }); return instance; } }); if (moduleName.indexOf('-') !== -1) { var camelizedName = moduleName.replace(/\-[a-z]/g, function (s) { return s[1].toUpperCase(); }); Object.defineProperty(RemoteStorage.prototype, camelizedName, { get: function () { return this[moduleName]; } }); } }; RemoteStorage.prototype._loadModule = function (moduleName) { var builder = RemoteStorage.MODULES[moduleName]; if (builder) { var module = builder(new RemoteStorage.BaseClient(this, '/' + moduleName + '/'), new RemoteStorage.BaseClient(this, '/public/' + moduleName + '/')); return module.exports; } else { throw "Unknown module: " + moduleName; } }; RemoteStorage.prototype.defineModule = function (moduleName) { console.log("remoteStorage.defineModule is deprecated, use RemoteStorage.defineModule instead!"); RemoteStorage.defineModule.apply(RemoteStorage, arguments); }; })(); /** FILE: src/debug/inspect.js **/ (function() { function loadTable(table, storage, paths) { table.setAttribute('border', '1'); table.style.margin = '8px'; table.style.color = 'white'; table.innerHTML = ''; var thead = document.createElement('thead'); table.appendChild(thead); var titleRow = document.createElement('tr'); thead.appendChild(titleRow); ['Path', 'Content-Type', 'Revision'].forEach(function(label) { var th = document.createElement('th'); th.textContent = label; thead.appendChild(th); }); var tbody = document.createElement('tbody'); table.appendChild(tbody); function renderRow(tr, path, contentType, revision) { [path, contentType, revision].forEach(function(value) { var td = document.createElement('td'); td.textContent = value || ''; tr.appendChild(td); }); } function loadRow(path) { if (storage.connected === false) { return; } function processRow(status, body, contentType, revision) { if (status === 200) { var tr = document.createElement('tr'); tbody.appendChild(tr); renderRow(tr, path, contentType, revision); if (path[path.length - 1] === '/') { for (var key in body) { loadRow(path + key); } } } } storage.get(path).then(processRow); } paths.forEach(loadRow); } function renderWrapper(title, table, storage, paths) { var wrapper = document.createElement('div'); //wrapper.style.display = 'inline-block'; var heading = document.createElement('h2'); heading.textContent = title; wrapper.appendChild(heading); var updateButton = document.createElement('button'); updateButton.textContent = "Refresh"; updateButton.onclick = function() { loadTable(table, storage, paths); }; wrapper.appendChild(updateButton); if (storage.reset) { var resetButton = document.createElement('button'); resetButton.textContent = "Reset"; resetButton.onclick = function() { storage.reset(function(newStorage) { storage = newStorage; loadTable(table, storage, paths); }); }; wrapper.appendChild(resetButton); } wrapper.appendChild(table); loadTable(table, storage, paths); return wrapper; } function renderLocalChanges(local) { var wrapper = document.createElement('div'); //wrapper.style.display = 'inline-block'; var heading = document.createElement('h2'); heading.textContent = "Outgoing changes"; wrapper.appendChild(heading); var updateButton = document.createElement('button'); updateButton.textContent = "Refresh"; wrapper.appendChild(updateButton); var list = document.createElement('ul'); list.style.fontFamily = 'courier'; wrapper.appendChild(list); function updateList() { list.innerHTML = ''; local.forAllNodes(function(node) { if (node.local && node.local.body) { var el = document.createElement('li'); el.textContent = JSON.stringify(node.local); list.appendChild(el); } }); } updateButton.onclick = updateList; updateList(); return wrapper; } RemoteStorage.prototype.inspect = function() { var widget = document.createElement('div'); widget.id = 'remotestorage-inspect'; widget.style.position = 'absolute'; widget.style.top = 0; widget.style.left = 0; widget.style.background = 'black'; widget.style.color = 'white'; widget.style.border = 'groove 5px #ccc'; var controls = document.createElement('div'); controls.style.position = 'absolute'; controls.style.top = 0; controls.style.left = 0; var heading = document.createElement('strong'); heading.textContent = " remotestorage.js inspector "; controls.appendChild(heading); var syncButton; if (this.local) { syncButton = document.createElement('button'); syncButton.textContent = "Synchronize"; controls.appendChild(syncButton); } var closeButton = document.createElement('button'); closeButton.textContent = "Close"; closeButton.onclick = function() { document.body.removeChild(widget); }; controls.appendChild(closeButton); widget.appendChild(controls); var remoteRootPaths = []; for (var path in this.caching._rootPaths) { if (this.caching._rootPaths.hasOwnProperty(path)) { remoteRootPaths.push(path); } } var remoteTable = document.createElement('table'); var localTable = document.createElement('table'); widget.appendChild(renderWrapper("Remote", remoteTable, this.remote, remoteRootPaths)); if (this.local) { widget.appendChild(renderWrapper("Local", localTable, this.local, ['/'])); widget.appendChild(renderLocalChanges(this.local)); syncButton.onclick = function() { this.log('sync clicked'); this.sync.sync().then(function() { this.log('SYNC FINISHED'); loadTable(localTable, this.local, ['/']); }.bind(this), function(err) { console.error("SYNC FAILED", err, err.stack); }); }.bind(this); } document.body.appendChild(widget); }; })(); /** FILE: src/googledrive.js **/ (function (global) { /** * Class: RemoteStorage.GoogleDrive * * WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE * * To use this backend, you need to specify the app's client ID like so: * * (start code) * * remoteStorage.setApiKeys('googledrive', { * clientId: 'your-client-id' * }); * * (end code) * * An client ID can be obtained by registering your app in the Google * Developers Console: https://developers.google.com/drive/web/auth/web-client * * Docs: https://developers.google.com/drive/web/auth/web-client#create_a_client_id_and_client_secret **/ var RS = RemoteStorage; var BASE_URL = 'https://www.googleapis.com'; var AUTH_URL = 'https://accounts.google.com/o/oauth2/auth'; var AUTH_SCOPE = 'https://www.googleapis.com/auth/drive'; var GD_DIR_MIME_TYPE = 'application/vnd.google-apps.folder'; var RS_DIR_MIME_TYPE = 'application/json; charset=UTF-8'; function buildQueryString(params) { return Object.keys(params).map(function (key) { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); }).join('&'); } function fileNameFromMeta(meta) { return encodeURIComponent(meta.title) + (meta.mimeType === GD_DIR_MIME_TYPE ? '/' : ''); } function metaTitleFromFileName(filename) { if (filename.substr(-1) === '/') { filename = filename.substr(0, filename.length - 1); } return decodeURIComponent(filename); } function parentPath(path) { return path.replace(/[^\/]+\/?$/, ''); } function baseName(path) { var parts = path.split('/'); if (path.substr(-1) === '/') { return parts[parts.length-2]+'/'; } else { return parts[parts.length-1]; } } var Cache = function (maxAge) { this.maxAge = maxAge; this._items = {}; }; Cache.prototype = { get: function (key) { var item = this._items[key]; var now = new Date().getTime(); return (item && item.t >= (now - this.maxAge)) ? item.v : undefined; }, set: function (key, value) { this._items[key] = { v: value, t: new Date().getTime() }; } }; RS.GoogleDrive = function (remoteStorage, clientId) { RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected'); this.rs = remoteStorage; this.clientId = clientId; this._fileIdCache = new Cache(60 * 5); // ids expire after 5 minutes (is this a good idea?) }; RS.GoogleDrive.prototype = { connected: false, online: true, configure: function (settings) { // Settings parameter compatible with WireClient if (settings.token) { localStorage['remotestorage:googledrive:token'] = settings.token; this.token = settings.token; this.connected = true; this._emit('connected'); } else { this.connected = false; delete this.token; delete localStorage['remotestorage:googledrive:token']; } }, connect: function () { this.rs.setBackend('googledrive'); RS.Authorize(AUTH_URL, AUTH_SCOPE, String(RS.Authorize.getLocation()), this.clientId); }, stopWaitingForToken: function () { if (!this.connected) { this._emit('not-connected'); } }, get: function (path, options) { if (path.substr(-1) === '/') { return this._getFolder(path, options); } else { return this._getFile(path, options); } }, put: function (path, body, contentType, options) { var self = this; function putDone(response) { if (response.status >= 200 && response.status < 300) { var meta = JSON.parse(response.responseText); var etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1); return Promise.resolve({statusCode: 200, contentType: meta.mimeType, revision: etagWithoutQuotes}); } else if (response.status === 412) { return Promise.resolve({statusCode: 412, revision: 'conflict'}); } else { return Promise.reject("PUT failed with status " + response.status + " (" + response.responseText + ")"); } } return self._getFileId(path).then(function (id) { if (id) { if (options && (options.ifNoneMatch === '*')) { return putDone({ status: 412 }); } return self._updateFile(id, path, body, contentType, options).then(putDone); } else { return self._createFile(path, body, contentType, options).then(putDone); } }); }, 'delete': function (path, options) { var self = this; return self._getFileId(path).then(function (id) { if (!id) { // File doesn't exist. Ignore. return Promise.resolve({statusCode: 200}); } return self._getMeta(id).then(function (meta) { var etagWithoutQuotes; if ((typeof meta === 'object') && (typeof meta.etag === 'string')) { etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1); } if (options && options.ifMatch && (options.ifMatch !== etagWithoutQuotes)) { return {statusCode: 412, revision: etagWithoutQuotes}; } return self._request('DELETE', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) { if (response.status === 200 || response.status === 204) { return {statusCode: 200}; } else { return Promise.reject("Delete failed: " + response.status + " (" + response.responseText + ")"); } }); }); }); }, _updateFile: function (id, path, body, contentType, options) { var self = this; var metadata = { mimeType: contentType }; var headers = { 'Content-Type': 'application/json; charset=UTF-8' }; if (options && options.ifMatch) { headers['If-Match'] = '"' + options.ifMatch + '"'; } return self._request('PUT', BASE_URL + '/upload/drive/v2/files/' + id + '?uploadType=resumable', { body: JSON.stringify(metadata), headers: headers }).then(function (response) { if (response.status === 412) { return (response); } else { return self._request('PUT', response.getResponseHeader('Location'), { body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body }); } }); }, _createFile: function (path, body, contentType, options) { var self = this; return self._getParentId(path).then(function (parentId) { var fileName = baseName(path); var metadata = { title: metaTitleFromFileName(fileName), mimeType: contentType, parents: [{ kind: "drive#fileLink", id: parentId }] }; return self._request('POST', BASE_URL + '/upload/drive/v2/files?uploadType=resumable', { body: JSON.stringify(metadata), headers: { 'Content-Type': 'application/json; charset=UTF-8' } }).then(function (response) { return self._request('POST', response.getResponseHeader('Location'), { body: contentType.match(/^application\/json/) ? JSON.stringify(body) : body }); }); }); }, _getFile: function (path, options) { var self = this; return self._getFileId(path).then(function (id) { return self._getMeta(id).then(function (meta) { var etagWithoutQuotes; if (typeof(meta) === 'object' && typeof(meta.etag) === 'string') { etagWithoutQuotes = meta.etag.substring(1, meta.etag.length-1); } if (options && options.ifNoneMatch && (etagWithoutQuotes === options.ifNoneMatch)) { return Promise.resolve({statusCode: 304}); } var options2 = {}; if (!meta.downloadUrl) { if (meta.exportLinks && meta.exportLinks['text/html']) { // Documents that were generated inside GoogleDocs have no // downloadUrl, but you can export them to text/html instead: meta.mimeType += ';export=text/html'; meta.downloadUrl = meta.exportLinks['text/html']; } else { // empty file return Promise.resolve({statusCode: 200, body: '', contentType: meta.mimeType, revision: etagWithoutQuotes}); } } if (meta.mimeType.match(/charset=binary/)) { options2.responseType = 'blob'; } return self._request('GET', meta.downloadUrl, options2).then(function (response) { var body = response.response; if (meta.mimeType.match(/^application\/json/)) { try { body = JSON.parse(body); } catch(e) {} } return Promise.resolve({statusCode: 200, body: body, contentType: meta.mimeType, revision: etagWithoutQuotes}); }); }); }); }, _getFolder: function (path, options) { var self = this; return self._getFileId(path).then(function (id) { var query, fields, data, i, etagWithoutQuotes, itemsMap; if (! id) { return Promise.resolve({statusCode: 404}); } query = '\'' + id + '\' in parents'; fields = 'items(downloadUrl,etag,fileSize,id,mimeType,title)'; return self._request('GET', BASE_URL + '/drive/v2/files?' + 'q=' + encodeURIComponent(query) + '&fields=' + encodeURIComponent(fields) + '&maxResults=1000', {}) .then(function (response) { if (response.status !== 200) { return Promise.reject('request failed or something: ' + response.status); } try { data = JSON.parse(response.responseText); } catch(e) { return Promise.reject('non-JSON response from GoogleDrive'); } itemsMap = {}; for (var i = 0, len = data.items.length; i < len; i++) { etagWithoutQuotes = data.items[i].etag.substring(1, data.items[i].etag.length-1); if (data.items[i].mimeType === GD_DIR_MIME_TYPE) { self._fileIdCache.set(path + data.items[i].title + '/', data.items[i].id); itemsMap[data.items[i].title + '/'] = { ETag: etagWithoutQuotes }; } else { self._fileIdCache.set(path + data.items[i].title, data.items[i].id); itemsMap[data.items[i].title] = { ETag: etagWithoutQuotes, 'Content-Type': data.items[i].mimeType, 'Content-Length': data.items[i].fileSize }; } } // FIXME: add revision of folder! return Promise.resolve({statusCode: 200, body: itemsMap, contentType: RS_DIR_MIME_TYPE, revision: undefined}); }); }); }, _getParentId: function (path) { var foldername = parentPath(path); var self = this; return self._getFileId(foldername).then(function (parentId) { if (parentId) { return Promise.resolve(parentId); } else { return self._createFolder(foldername); } }); }, _createFolder: function (path) { var self = this; return self._getParentId(path).then(function (parentId) { return self._request('POST', BASE_URL + '/drive/v2/files', { body: JSON.stringify({ title: metaTitleFromFileName(baseName(path)), mimeType: GD_DIR_MIME_TYPE, parents: [{ id: parentId }] }), headers: { 'Content-Type': 'application/json; charset=UTF-8' } }).then(function (response) { var meta = JSON.parse(response.responseText); return Promise.resolve(meta.id); }); }); }, _getFileId: function (path) { var self = this; var id; if (path === '/') { // "root" is a special alias for the fileId of the root folder return Promise.resolve('root'); } else if ((id = this._fileIdCache.get(path))) { // id is cached. return Promise.resolve(id); } // id is not cached (or file doesn't exist). // load parent folder listing to propagate / update id cache. return self._getFolder(parentPath(path)).then(function () { id = self._fileIdCache.get(path); if (!id) { if (path.substr(-1) === '/') { return self._createFolder(path).then(function () { return self._getFileId(path); }); } else { return Promise.resolve(); } return; } return Promise.resolve(id); }); }, _getMeta: function (id) { return this._request('GET', BASE_URL + '/drive/v2/files/' + id, {}).then(function (response) { if (response.status === 200) { return Promise.resolve(JSON.parse(response.responseText)); } else { return Promise.reject("request (getting metadata for " + id + ") failed with status: " + response.status); } }); }, _request: function (method, url, options) { var self = this; if (! options.headers) { options.headers = {}; } options.headers['Authorization'] = 'Bearer ' + self.token; return RS.WireClient.request(method, url, options).then(function (xhr) { // google tokens expire from time to time... if (xhr && xhr.status === 401) { self.connect(); return; } return xhr; }); } }; RS.GoogleDrive._rs_init = function (remoteStorage) { var config = remoteStorage.apiKeys.googledrive; if (config) { remoteStorage.googledrive = new RS.GoogleDrive(remoteStorage, config.clientId); if (remoteStorage.backend === 'googledrive') { remoteStorage._origRemote = remoteStorage.remote; remoteStorage.remote = remoteStorage.googledrive; } } }; RS.GoogleDrive._rs_supported = function (rs) { return true; }; RS.GoogleDrive._rs_cleanup = function (remoteStorage) { remoteStorage.setBackend(undefined); if (remoteStorage._origRemote) { remoteStorage.remote = remoteStorage._origRemote; delete remoteStorage._origRemote; } }; })(this); /** FILE: src/dropbox.js **/ (function (global) { var RS = RemoteStorage; /** * File: Dropbox * * WORK IN PROGRESS, NOT RECOMMENDED FOR PRODUCTION USE * * Dropbox backend for RemoteStorage.js * This file exposes a get/put/delete interface which is compatible with * <RemoteStorage.WireClient>. * * When remoteStorage.backend is set to 'dropbox', this backend will * initialize and replace remoteStorage.remote with remoteStorage.dropbox. * * In order to ensure compatibility with the public folder, <BaseClient.getItemURL> * gets hijacked to return the Dropbox public share URL. * * To use this backend, you need to specify the Dropbox app key like so: * * (start code) * * remoteStorage.setApiKeys('dropbox', { * appKey: 'your-app-key' * }); * * (end code) * * An app key can be obtained by registering your app at https://www.dropbox.com/developers/apps * * Known issues: * * - Storing files larger than 150MB is not yet supported * - Listing and deleting folders with more than 10'000 files will cause problems * - Content-Type is not fully supported due to limitations of the Dropbox API * - Dropbox preserves cases but is not case-sensitive * - getItemURL is asynchronous which means getIetmURL returns useful values * after the syncCycle */ var hasLocalStorage; var AUTH_URL = 'https://www.dropbox.com/1/oauth2/authorize'; var SETTINGS_KEY = 'remotestorage:dropbox'; var cleanPath = RS.WireClient.cleanPath; /** * class: LowerCaseCache * * A cache which automatically converts all keys to lower case and can * propagate changes up to parent folders. * * By default the set and delete methods are aliased to justSet and justDelete. * * Parameters: * * defaultValue - the value that is returned for all keys that don't exist * in the cache */ function LowerCaseCache(defaultValue){ this.defaultValue = defaultValue; this._storage = { }; this.set = this.justSet; this.delete = this.justDelete; } LowerCaseCache.prototype = { /** * Method: get * * Get a value from the cache or defaultValue, if the key is not in the * cache. */ get : function (key) { key = key.toLowerCase(); var stored = this._storage[key]; if (typeof stored === 'undefined'){ stored = this.defaultValue; this._storage[key] = stored; } return stored; }, /** * Method: propagateSet * * Set a value and also update the parent folders with that value. */ propagateSet : function (key, value) { key = key.toLowerCase(); if (this._storage[key] === value) { return value; } this._propagate(key, value); this._storage[key] = value; return value; }, /** * Method: propagateDelete * * Delete a value and propagate the changes to the parent folders. */ propagateDelete : function (key) { key = key.toLowerCase(); this._propagate(key, this._storage[key]); return delete this._storage[key]; }, _activatePropagation: function (){ this.set = this.propagateSet; this.delete = this.propagateDelete; return true; }, /** * Method: justSet * * Set a value without propagating. */ justSet : function (key, value) { key = key.toLowerCase(); this._storage[key] = value; return value; }, /** * Method: justDelete * * Delete a value without propagating. */ justDelete : function (key, value) { key = key.toLowerCase(); return delete this._storage[key]; }, _propagate: function (key, rev){ var folders = key.split('/').slice(0,-1); var path = ''; for (var i = 0, len = folders.length; i < len; i++){ path += folders[i]+'/'; if (!rev) { rev = this._storage[path]+1; } this._storage[path] = rev; } } }; var onErrorCb; /** * Class: RemoteStorage.Dropbox */ RS.Dropbox = function (rs) { this.rs = rs; this.connected = false; this.rs = rs; var self = this; onErrorCb = function (error){ if (error instanceof RemoteStorage.Unauthorized) { // Delete all the settings - see the documentation of wireclient.configure self.configure({ userAddress: null, href: null, storageApi: null, token: null, options: null }); } }; RS.eventHandling(this, 'change', 'connected', 'wire-busy', 'wire-done', 'not-connected'); rs.on('error', onErrorCb); this.clientId = rs.apiKeys.dropbox.appKey; this._revCache = new LowerCaseCache('rev'); this._itemRefs = {}; this._metadataCache = {}; if (hasLocalStorage){ var settings; try { settings = JSON.parse(localStorage[SETTINGS_KEY]); } catch(e){} if (settings) { this.configure(settings); } try { this._itemRefs = JSON.parse(localStorage[ SETTINGS_KEY+':shares' ]); } catch(e) { } } if (this.connected) { setTimeout(this._emit.bind(this), 0, 'connected'); } }; RS.Dropbox.prototype = { online: true, /** * Method: connect * * Set the backed to 'dropbox' and start the authentication flow in order * to obtain an API token from Dropbox. */ connect: function () { // TODO handling when token is already present this.rs.setBackend('dropbox'); if (this.token){ hookIt(this.rs); } else { RS.Authorize(AUTH_URL, '', String(RS.Authorize.getLocation()), this.clientId); } }, /** * Method : configure(settings) * Accepts its parameters according to the <RemoteStorage.WireClient>. * Sets the connected flag **/ configure: function (settings) { // We only update this.userAddress if settings.userAddress is set to a string or to null: if (typeof settings.userAddress !== 'undefined') { this.userAddress = settings.userAddress; } // Same for this.token. If only one of these two is set, we leave the other one at its existing value: if (typeof settings.token !== 'undefined') { this.token = settings.token; } if (this.token) { this.connected = true; if ( !this.userAddress ){ this.info().then(function (info){ this.userAddress = info.display_name; this.rs.widget.view.setUserAddress(this.userAddress); this._emit('connected'); }.bind(this)); } } else { this.connected = false; } if (hasLocalStorage){ localStorage[SETTINGS_KEY] = JSON.stringify({ userAddress: this.userAddress, token: this.token }); } }, /** * Method: stopWaitingForToken * * Stop waiting for the token and emit not-connected */ stopWaitingForToken: function () { if (!this.connected) { this._emit('not-connected'); } }, /** * Method: _getFolder * * Get all items in a folder. * * Parameters: * * path - path of the folder to get, with leading slash * options - not used * * Returns: * * statusCode - HTTP status code * body - array of the items found * contentType - 'application/json; charset=UTF-8' * revision - revision of the folder */ _getFolder: function (path, options) { // FIXME simplify promise handling var url = 'https://api.dropbox.com/1/metadata/auto' + cleanPath(path); var revCache = this._revCache; var self = this; return this._request('GET', url, {}).then(function (resp) { var status = resp.status; if (status === 304) { return Promise.resolve({statusCode: status}); } var listing, body, mime, rev; try{ body = JSON.parse(resp.responseText); } catch (e) { return Promise.reject(e); } rev = self._revCache.get(path); mime = 'application/json; charset=UTF-8'; if (body.contents) { listing = body.contents.reduce(function (m, item) { var itemName = item.path.split('/').slice(-1)[0] + ( item.is_dir ? '/' : '' ); if (item.is_dir){ m[itemName] = { ETag: revCache.get(path+itemName) }; } else { m[itemName] = { ETag: item.rev }; } return m; }, {}); } return Promise.resolve({statusCode: status, body: listing, contentType: mime, revision: rev}); }); }, /** * Method: get * * Compatible with <RemoteStorage.WireClient.get> * * Checks for the path in _revCache and decides based on that if file has * changed. Calls _getFolder is the path points to a folder. * * Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs. */ get: function (path, options) { if (! this.connected) { return Promise.reject("not connected (path: " + path + ")"); } var url = 'https://api-content.dropbox.com/1/files/auto' + cleanPath(path); var self = this; var savedRev = this._revCache.get(path); if (savedRev === null) { // file was deleted server side return Promise.resolve({statusCode: 404}); } if (options && options.ifNoneMatch && savedRev && (savedRev === options.ifNoneMatch)) { // nothing changed. return Promise.resolve({statusCode: 304}); } //use _getFolder for folders if (path.substr(-1) === '/') { return this._getFolder(path, options); } return this._request('GET', url, {}).then(function (resp) { var status = resp.status; var meta, body, mime, rev; if (status !== 200) { return Promise.resolve({statusCode: status}); } body = resp.responseText; try { meta = JSON.parse( resp.getResponseHeader('x-dropbox-metadata') ); } catch(e) { return Promise.reject(e); } mime = meta.mime_type; //resp.getResponseHeader('Content-Type'); rev = meta.rev; self._revCache.set(path, rev); self._shareIfNeeded(path); // The shared link expires every 4 hours // handling binary if (!resp.getResponseHeader('Content-Type') || resp.getResponseHeader('Content-Type').match(/charset=binary/)) { var pending = Promise.defer(); RS.WireClient.readBinaryData(resp.response, mime, function (result) { pending.resolve({ statusCode: status, body: result, contentType: mime, revision: rev }); }); return pending.promise; } // handling json (always try) if (mime && mime.search('application/json') >= 0 || true) { try { body = JSON.parse(body); mime = 'application/json; charset=UTF-8'; } catch(e) { //Failed parsing Json, assume it is something else then } } return Promise.resolve({statusCode: status, body: body, contentType: mime, revision: rev}); }); }, /** * Method: put * * Compatible with <RemoteStorage.WireClient> * * Checks for the path in _revCache and decides based on that if file has * changed. * * Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs. */ put: function (path, body, contentType, options) { var self = this; if (!this.connected) { throw new Error("not connected (path: " + path + ")"); } //check if file has changed and return 412 var savedRev = this._revCache.get(path); if (options && options.ifMatch && savedRev && (savedRev !== options.ifMatch)) { return Promise.resolve({statusCode: 412, revision: savedRev}); } if (options && (options.ifNoneMatch === '*') && savedRev && (savedRev !== 'rev')) { return Promise.resolve({statusCode: 412, revision: savedRev}); } if ((!contentType.match(/charset=/)) && (body instanceof ArrayBuffer || RS.WireClient.isArrayBufferView(body))) { contentType += '; charset=binary'; } if (body.length > 150 * 1024 * 1024) { //https://www.dropbox.com/developers/core/docs#chunked-upload return Promise.reject(new Error("Cannot upload file larger than 150MB")); } var result; var needsMetadata = options && (options.ifMatch || (options.ifNoneMatch === '*')); var uploadParams = { body: body, contentType: contentType, path: path }; if (needsMetadata) { result = this._getMetadata(path).then(function (metadata) { if (options && (options.ifNoneMatch === '*') && metadata) { // if !!metadata === true, the file exists return Promise.resolve({ statusCode: 412, revision: metadata.rev }); } if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) { return Promise.resolve({ statusCode: 412, revision: metadata.rev }); } return self._uploadSimple(uploadParams); }); } else { result = self._uploadSimple(uploadParams); } return result.then(function (ret) { self._shareIfNeeded(path); return ret; }); }, /** * Method: delete * * Compatible with <RemoteStorage.WireClient.delete> * * Checks for the path in _revCache and decides based on that if file has * changed. * * Calls <RemoteStorage.Dropbox.share> afterwards to fill _itemRefs. */ 'delete': function (path, options) { var self = this; if (!this.connected) { throw new Error("not connected (path: " + path + ")"); } //check if file has changed and return 412 var savedRev = this._revCache.get(path); if (options && options.ifMatch && savedRev && (options.ifMatch !== savedRev)) { return Promise.resolve({ statusCode: 412, revision: savedRev }); } if (options && options.ifMatch) { return this._getMetadata(path).then(function (metadata) { if (options && options.ifMatch && metadata && (metadata.rev !== options.ifMatch)) { return Promise.resolve({ statusCode: 412, revision: metadata.rev }); } return self._deleteSimple(path); }); } return self._deleteSimple(path); }, /** * Method: _shareIfNeeded * * Calls share, if the provided path resides in a public folder. */ _shareIfNeeded: function (path) { if (path.match(/^\/public\/.*[^\/]$/) && this._itemRefs[path] === undefined) { this.share(path); } }, /** * Method: share * * Gets a publicly-accessible URL for the path from Dropbox and stores it * in _itemRefs. * * Returns: * * A promise for the URL */ share: function (path) { var self = this; var url = 'https://api.dropbox.com/1/media/auto/' + cleanPath(path); return this._request('POST', url, {}).then(function (response) { if (response.status !== 200) { return Promise.reject(new Error('Invalid Dropbox API response status when sharing "' + path + '":' + response.status)); } try { response = JSON.parse(response.responseText); } catch (e) { return Promise.reject(new Error('Invalid Dropbox API response when sharing "' + path + '": ' + response.responseText)); } self._itemRefs[path] = response.url; if (hasLocalStorage) { localStorage[SETTINGS_KEY + ':shares'] = JSON.stringify(self._itemRefs); } return Promise.resolve(url); }, function (error) { err.message = 'Sharing dropbox file or folder ("' + path + '") failed.' + err.message; return Promise.reject(error); }); }, /** * Method: info * * Fetches the user's info from dropbox and returns a promise for it. * * Returns: * * A promise to the user's info */ info: function () { var url = 'https://api.dropbox.com/1/account/info'; // requesting user info(mainly for userAdress) return this._request('GET', url, {}).then(function (resp){ try { var info = JSON.parse(resp.responseText); return Promise.resolve(info); } catch (e) { return Promise.reject(e); } }); }, /** * Method: _request * * Make a HTTP request. * * Options: * * headers - an object containing the request headers * * Parameters: * * method - the method to use * url - the URL to make the request to * options - see above */ _request: function (method, url, options) { var self = this; if (! options.headers) { options.headers = {}; } options.headers['Authorization'] = 'Bearer ' + this.token; return RS.WireClient.request.call(this, method, url, options).then(function (xhr) { //503 means retry this later if (xhr && xhr.status === 503) { return global.setTimeout(self._request(method, url, options), 3210); } else { return Promise.resolve(xhr); } }); }, /** * Method: fetchDelta * * Fetches the revision of all the files from dropbox API and puts them * into _revCache. These values can then be used to determine if something * has changed. */ fetchDelta: function () { // TODO: Handle `has_more` var args = Array.prototype.slice.call(arguments); var self = this; return self._request('POST', 'https://api.dropbox.com/1/delta', { body: self._deltaCursor ? ('cursor=' + encodeURIComponent(self._deltaCursor)) : '', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(function (response) { // break if status != 200 if (response.status !== 200 ) { if (response.status === 400) { self.rs._emit('error', new RemoteStorage.Unauthorized()); return Promise.resolve(args); } else { return Promise.reject("dropbox.fetchDelta returned "+response.status+response.responseText); } return; } var delta; try { delta = JSON.parse(response.responseText); } catch(error) { RS.log('fetchDeltas can not parse response',error); return Promise.reject("can not parse response of fetchDelta : "+error.message); } // break if no entries found if (!delta.entries) { return Promise.reject('dropbox.fetchDeltas failed, no entries found'); } // Dropbox sends the complete state if (delta.reset) { self._revCache = new LowerCaseCache('rev'); } //saving the cursor for requesting further deltas in relation to the cursor position if (delta.cursor) { self._deltaCursor = delta.cursor; } //updating revCache RemoteStorage.log("Delta : ", delta.entries); delta.entries.forEach(function (entry) { var path = entry[0]; var rev; if (!entry[1]){ rev = null; } else { if (entry[1].is_dir) { return; } rev = entry[1].rev; } self._revCache.set(path, rev); }); return Promise.resolve(args); }, function (err) { this.rs.log('fetchDeltas', err); this.rs._emit('error', new RemoteStorage.SyncError('fetchDeltas failed.' + err)); promise.reject(err); }).then(function () { if (self._revCache) { var args = Array.prototype.slice.call(arguments); self._revCache._activatePropagation(); return Promise.resolve(args); } }); }, /** * Method: _getMetadata * * Gets metadata for a path (can point to either a file or a folder). * * Options: * * list - if path points to a folder, specifies whether to list the * metadata of the folder's children. False by default. * * Parameters: * * path - the path to get metadata for * options - see above * * Returns: * * A promise for the metadata */ _getMetadata: function (path, options) { var self = this; var cached = this._metadataCache[path]; var url = 'https://api.dropbox.com/1/metadata/auto' + cleanPath(path); url += '?list=' + ((options && options.list) ? 'true' : 'false'); if (cached && cached.hash) { url += '&hash=' + encodeURIComponent(cached.hash); } return this._request('GET', url, {}).then(function (resp) { if (resp.status === 304) { return Promise.resolve(cached); } else if (resp.status === 200) { var response = JSON.parse(resp.responseText); self._metadataCache[path] = response; return Promise.resolve(response); } else { // The file doesn't exist return Promise.resolve(); } }); }, /** * Method: _uploadSimple * * Upload a simple file (the size is no more than 150MB). * * Parameters: * * ifMatch - same as for get * path - path of the file * body - contents of the file to upload * contentType - mime type of the file * * Returns: * * statusCode - HTTP status code * revision - revision of the newly-created file, if any */ _uploadSimple: function (params) { var self = this; var url = 'https://api-content.dropbox.com/1/files_put/auto' + cleanPath(params.path) + '?'; if (params && params.ifMatch) { url += "parent_rev=" + encodeURIComponent(params.ifMatch); } return self._request('PUT', url, { body: params.body, headers: { 'Content-Type': params.contentType } }).then(function (resp) { if (resp.status !== 200) { return Promise.resolve({ statusCode: resp.status }); } var response; try { response = JSON.parse(resp.responseText); } catch (e) { return Promise.reject(e); } // Conflict happened. Delete the copy created by dropbox if (response.path !== params.path) { var deleteUrl = 'https://api.dropbox.com/1/fileops/delete?root=auto&path=' + encodeURIComponent(response.path); self._request('POST', deleteUrl, {}); return self._getMetadata(params.path).then(function (metadata) { return Promise.resolve({ statusCode: 412, revision: metadata.rev }); }); } self._revCache.propagateSet(params.path, response.rev); return Promise.resolve({ statusCode: resp.status }); }); }, /** * Method: _deleteSimple * * Deletes a file or a folder. If the folder contains more than 10'000 items * (recursively) then the operation may not complete successfully. If that * is the case, an Error gets thrown. * * Parameters: * * path - the path to delete * * Returns: * * statusCode - HTTP status code */ _deleteSimple: function (path) { var self = this; var url = 'https://api.dropbox.com/1/fileops/delete?root=auto&path=' + encodeURIComponent(path); return self._request('POST', url, {}).then(function (resp) { if (resp.status === 406) { // Too many files would be involved in the operation for it to // complete successfully. // TODO: Handle this somehow return Promise.reject(new Error("Cannot delete '" + path + "': too many files involved")); } if (resp.status === 200) { self._revCache.delete(path); delete self._itemRefs[path]; } return Promise.resolve({ statusCode: resp.status }); }); } }; //hooking and unhooking the sync function hookSync(rs) { if (rs._dropboxOrigSync) { return; } // already hooked rs._dropboxOrigSync = rs.sync.bind(rs); rs.sync = function () { return this.dropbox.fetchDelta.apply(this.dropbox, arguments). then(rs._dropboxOrigSync, function (err) { rs._emit('error', new rs.SyncError(err)); }); }; } function unHookSync(rs) { if (! rs._dropboxOrigSync) { return; } // not hooked rs.sync = rs._dropboxOrigSync; delete rs._dropboxOrigSync; } // hooking and unhooking getItemURL function hookGetItemURL(rs) { if (rs._origBaseClientGetItemURL) { return; } rs._origBaseClientGetItemURL = RS.BaseClient.prototype.getItemURL; RS.BaseClient.prototype.getItemURL = function (path){ var ret = rs.dropbox._itemRefs[path]; return ret ? ret : ''; }; } function unHookGetItemURL(rs){ if (! rs._origBaseClientGetItemURL) { return; } RS.BaseClient.prototype.getItemURL = rs._origBaseClientGetItemURL; delete rs._origBaseClientGetItemURL; } function hookRemote(rs){ if (rs._origRemote) { return; } rs._origRemote = rs.remote; rs.remote = rs.dropbox; } function unHookRemote(rs){ if (rs._origRemote) { rs.remote = rs._origRemote; delete rs._origRemote; } } function hookIt(rs){ hookRemote(rs); if (rs.sync) { hookSync(rs); } hookGetItemURL(rs); } function unHookIt(rs){ unHookRemote(rs); unHookSync(rs); unHookGetItemURL(rs); } RS.Dropbox._rs_init = function (rs) { hasLocalStorage = rs.localStorageAvailable(); if ( rs.apiKeys.dropbox ) { rs.dropbox = new RS.Dropbox(rs); } if (rs.backend === 'dropbox') { hookIt(rs); } }; RS.Dropbox._rs_supported = function () { return true; }; RS.Dropbox._rs_cleanup = function (rs) { unHookIt(rs); if (hasLocalStorage){ delete localStorage[SETTINGS_KEY]; } rs.removeEventListener('error', onErrorCb); rs.setBackend(undefined); }; })(this); return new RemoteStorage(); });
src/containers/verification/joblist/BrowseView.js
shojil/bifapp
/** * Receipe Tabs Screen * - Shows tabs, which contain receipe listings * * React Native Starter App * https://github.com/mcnamee/react-native-starter-app */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { View, StyleSheet, InteractionManager, ScrollView, Image, Dimensions, ListView, AsyncStorage } from 'react-native'; import { TabViewAnimated, TabBar } from 'react-native-tab-view'; // Consts and Libs import { AppColors, AppStyles } from '@theme/'; // Consts and Libs import { AppConfig } from '@constants/'; // Containers import RecipeListing from '@containers/recipes/Listing/ListingContainer'; // Components import { Text } from '@ui/'; import Loading from '@components/general/Loading'; import { Actions } from 'react-native-router-flux'; // Components import { Alerts, DashBadge, Button, Card, Spacer, List, ListItem, FormInput, FormLabel, } from '@components/ui/'; import { Icon, Grid, Col, Row } from 'react-native-elements'; /* Styles ==================================================================== */ const styles = StyleSheet.create({ // Tab Styles tabContainerWrapper: { flex:1 }, tabContainer: { flexDirection: 'row', flex: 1, marginBottom:12 }, tabbar: { backgroundColor: AppColors.brand.primary, }, tabbarIndicator: { backgroundColor: '#FFF', }, tabbarText: { color: '#FFF', }, dashbadbox1:{ width:'35%', marginLeft:'9%', marginRight:'4%' }, dashbadbox2:{ width:'35%', marginLeft:'5%', marginRight:'9%' } }); const dummyData2 = [ { title: 'BCIL-EB-885 - Imran Ahmad Memon', role: '96 Memon MOHALLAH MALL ROAD KHAIRPUR MEMON MOHALLAH KHAIRPUR', phone: '00923224434435', isNew: 'No', bcilno:'BCIL-EB-885', name:'Imran Ahmad Memon', residenceaddress:'96 Memon MOHALLAH MALL ROAD KHAIRPUR MEMON MOHALLAH KHAIRPUR', regid:'0019NPM000058', businessname:'Graint Heights' }, { title: 'BCIL-NB-2102 - Usman Malik', role: 'Office no 23 Street 44 Gulistan-e-Johr Lahore', phone: '00923224434435', isNew: 'Yes', bcilno:'BCIL-NB-2102', name:'Usman Malik', residenceaddress:'Office no 23 Street 44 Gulistan-e-Johr Lahore', regid:'0019NPM000012', businessname:'Wholesale Dailer' }, { title: 'BCIL-NB-2103 - Asad Malik', role: 'Office no 234 Street 44 Gulistan-e-Johr Lahore', phone: '00923224434435', isNew: 'Yes', bcilno:'BCIL-NB-2103', name:'Asad Malik', residenceaddress:'Office no 234 Street 44 Gulistan-e-Johr Lahore', regid:'0019NPM000111', businessname:'Super Store' }, { title: 'BCIL-NB-2104 - Asad Kamran', role: 'Office no 234 Street 44 Gulistan-e-Johr Lahore', phone: '00923224434435', isNew: 'Yes', bcilno:'BCIL-NB-2104', name:'Asad Kamran', residenceaddress:'Office no 234 Street 44 Gulistan-e-Johr Lahore', regid:'0019NPM000013', businessname:'Vegitable Shop' }, { title: 'BCIL-EB-2105 - Aslam Kamran', role: 'Office no 234 Street 44 Gulistan-e-Johr Lahore', phone: '00923224434435', isNew: 'No', bcilno:'BCIL-EB-2105', name:'Aslam Kamran', residenceaddress:'Office no 234 Street 44 Gulistan-e-Johr Lahore', regid:'0019NPM003453', businessname:'Super Store' }, { title: 'BCIL-EB-2106 - Aslam Kamran', role: 'Office no 234 Street 44 Muslim Town Lahore', phone: '00923224434435', isNew: 'No', bcilno:'BCIL-EB-2106', name:'Aslam Kamran', residenceaddress:'Office no 234 Street 44 Muslim Town Lahore', regid:'0019NPM000253', businessname:'Factory' }, { title: 'BCIL-NB-2104 - Usman Saleem', role: 'Office no 234 Street 44 Muslim Town Lahore', phone: '00923224434435', isNew: 'Yes', bcilno:'BCIL-NB-2104', name:'Usman Saleem', residenceaddress:'Office no 234 Street 44 Muslim Town Lahore', regid:'0019NPM000313', businessname:'Juice Shop' }, { title: 'BCIL-NB-2109 - Jim Collins', role: 'Office no 234 Street 44 Muslim Town Lahore', phone: '00923224434435', isNew: 'Yes', bcilno:'BCIL-NB-2109', name:'Jim Collins', residenceaddress:'Office no 234 Street 44 Muslim Town Lahore', regid:'0019NPM000313', businessname:'Boutique' }, { title: 'BCIL-EB-2109 - Jim Collins', role: 'Office no 2 Muslim Town Lahore', phone: '00923224434435', isNew: 'No', bcilno:'BCIL-EB-2109', name:'Jim Collins', residenceaddress:'Office no 2 Muslim Town Lahore', regid:'0019NPM000313', businessname:'Boutique' }, { title: 'BCIL-EB-2110 - Anwar Ali', role: 'Office no 234 Street 44 Muslim Town Lahore', phone: '00923224434435', isNew: 'No', bcilno:'BCIL-EB-2110', name:'Anwar Ali', residenceaddress:'Office no 234 Street 44 Muslim Town Lahore', regid:'0019NPM000113', businessname:'Grammer School' } ]; /* Component ==================================================================== */ let loadingTimeout; class RecipeTabs extends Component { static componentName = 'RecipeTabs'; static propTypes = { meals: PropTypes.arrayOf(PropTypes.object).isRequired, } static defaultProps = { meals: [], } constructor(props) { super(props); const ds2 = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 }); this.state = { loading: true, visitedRoutes: [], dataSource2: ds2.cloneWithRows(dummyData2) }; this.openForm = this.openForm.bind(this) } /** * Wait until any interactions are finished, before setting up tabs */ componentDidMount = () => { InteractionManager.runAfterInteractions(() => { this.setTabs(); }); } componentWillUnmount = () => clearTimeout(loadingTimeout); /** * When meals are ready, populate tabs */ setTabs = () => { const routes = []; let idx = 0; this.props.meals.forEach((meal) => { routes.push({ key: idx.toString(), id: meal.id.toString(), title: meal.title, }); idx += 1; }); this.setState({ navigation: { index: 0, routes, }, }, () => { // Hack to prevent error showing loadingTimeout = setTimeout(() => { this.setState({ loading: false }); }, 100); }); } openForm = () => { console.log("Testing ..... OpenForm clicked....") } /** * On Change Tab */ handleChangeTab = (index) => { this.setState({ navigation: { ...this.state.navigation, index }, }); } /** * Each List Item */ renderRow = (data, sectionID) => ( <View> <Text h5 style={{marginLeft:30}}>{data.title}</Text> <ListItem key={`list-row-${sectionID}`} onPress={()=>Actions.verificationform({data: data})} title={data.phone} subtitle={data.role || null} leftIcon={data.icon ? { name: data.icon } : null} avatar={data.avatar ? { uri: data.avatar } : null} roundAvatar={!!data.avatar} /> </View> ) /** * Header Component */ renderHeader = props => ( <View /> ) /** * Which component to show */ renderScene = ({ route }) => { // For performance, only render if it's this route, or I've visited before if ( parseInt(route.key, 0) !== parseInt(this.state.navigation.index, 0) && this.state.visitedRoutes.indexOf(route.key) < 0 ) { return null; } // And Add this index to visited routes if (this.state.visitedRoutes.indexOf(this.state.navigation.index) < 0) { this.state.visitedRoutes.push(route.key); } // Which component should be loaded? return ( <View style={styles.tabContainer}> <ScrollView automaticallyAdjustContentInsets={false} style={[AppStyles.container]} > <View style={[AppStyles.paddingHorizontal]}> <Spacer size={15} /> <Text h2>List Rows</Text> <Spacer size={-10} /> </View> <List> <ListView renderRow={this.renderRow} dataSource={this.state.dataSource2} /> </List> </ScrollView> </View> ); } /** * Save Form Step to AsyncStorage */ setFormStep = async(setp) => { if(typeof AppConfig.localstoragekeys != 'undefined' && typeof AppConfig.localstoragekeys.fromstep != 'undefined') { await AsyncStorage.setItem(AppConfig.localstoragekeys.fromstep, step); } } render = () => { if (this.state.loading || !this.state.navigation) return <Loading />; this.setFormStep(0) return ( <TabViewAnimated style={[styles.tabContainer]} renderScene={this.renderScene} renderHeader={this.renderHeader} navigationState={this.state.navigation} onRequestChangeTab={this.handleChangeTab} /> ); } } /* Export Component ==================================================================== */ export default RecipeTabs;
options/root.js
voz-living/chrome-extension-react
import React from 'react'; import { render } from 'react-dom'; import OptionPage from './OptionPage'; render(<OptionPage />, document.getElementById('root'));
P/bst/src/components/Title.js
imuntil/React
import React from 'react' function Title({children}) { return ( <div className="col-md-8 col-md-offset-2 col-sm-10 col-sm-offset-1 col-xs-12 col-xs-offset-0"> <div className="title"> {children} </div> </div> ) } export default Title
src/applications/static-pages/contact-chatbot-cta/index.js
department-of-veterans-affairs/vets-website
// Node modules. import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; export default (store, widgetType) => { const root = document.querySelector(`[data-widget-type="${widgetType}"]`); if (root) { import(/* webpackChunkName: "contact-chatbot-cta" */ './components/App').then(module => { const App = module.default; ReactDOM.render( <Provider store={store}> <App /> </Provider>, root, ); }); } };
frontend/src/components/partners/profile/overview/undata/partnerUnData.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import GridColumn from '../../../../common/grid/gridColumn'; import PartnerUnDataOverview from './partnerUnDataOverview'; import PartnerUnDataDetails from './partnerUnDataDetails'; import { ROLES } from '../../../../../helpers/constants'; const PartnerOverview = (props) => { const { partner, role, params: { id } } = props; return (<GridColumn> {role === ROLES.AGENCY ? <PartnerUnDataDetails partnerId={id} /> : null} <PartnerUnDataOverview partner={partner} /> </GridColumn>); }; PartnerOverview.propTypes = { partner: PropTypes.object.isRequired, params: PropTypes.object, role: PropTypes.string, }; const mapStateToProps = (state, ownProps) => ({ partner: state.agencyPartnerProfile.data[ownProps.params.id] || {}, role: state.session.role, }); export default connect(mapStateToProps)(PartnerOverview);
src/svg-icons/action/announcement.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAnnouncement = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 9h-2V5h2v6zm0 4h-2v-2h2v2z"/> </SvgIcon> ); ActionAnnouncement = pure(ActionAnnouncement); ActionAnnouncement.displayName = 'ActionAnnouncement'; ActionAnnouncement.muiName = 'SvgIcon'; export default ActionAnnouncement;
packages/material-ui-icons/src/PictureInPicture.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M19 7h-8v6h8V7zm2-4H3c-1.1 0-2 .9-2 2v14c0 1.1.9 1.98 2 1.98h18c1.1 0 2-.88 2-1.98V5c0-1.1-.9-2-2-2zm0 16.01H3V4.98h18v14.03z" /><path fill="none" d="M0 0h24v24H0z" /></React.Fragment> , 'PictureInPicture');
src/svg-icons/communication/import-contacts.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationImportContacts = (props) => ( <SvgIcon {...props}> <path d="M21 5c-1.11-.35-2.33-.5-3.5-.5-1.95 0-4.05.4-5.5 1.5-1.45-1.1-3.55-1.5-5.5-1.5S2.45 4.9 1 6v14.65c0 .25.25.5.5.5.1 0 .15-.05.25-.05C3.1 20.45 5.05 20 6.5 20c1.95 0 4.05.4 5.5 1.5 1.35-.85 3.8-1.5 5.5-1.5 1.65 0 3.35.3 4.75 1.05.1.05.15.05.25.05.25 0 .5-.25.5-.5V6c-.6-.45-1.25-.75-2-1zm0 13.5c-1.1-.35-2.3-.5-3.5-.5-1.7 0-4.15.65-5.5 1.5V8c1.35-.85 3.8-1.5 5.5-1.5 1.2 0 2.4.15 3.5.5v11.5z"/> </SvgIcon> ); CommunicationImportContacts = pure(CommunicationImportContacts); CommunicationImportContacts.displayName = 'CommunicationImportContacts'; CommunicationImportContacts.muiName = 'SvgIcon'; export default CommunicationImportContacts;
local-cli/templates/HelloWorld/__tests__/index.android.js
ptomasroos/react-native
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
site/pages/ExamplePage.js
tylercollier/react-dnd-demo
import React, { Component } from 'react'; import Header from '../components/Header'; import PageBody from '../components/PageBody'; import SideBar from '../components/SideBar'; import { ExamplePages } from '../Constants'; export default class ExamplesPage extends Component { render() { return ( <div> <Header/> <PageBody hasSidebar> <SideBar groups={ExamplePages} example={this.props.example} /> {this.props.children} </PageBody> </div> ); } }
packages/tessellation/src/renderEffect.spec.js
xaviervia/tessellation
import React from 'react' import {equal, deepEqual} from 'assert' import renderEffect from './renderEffect' describe('renderEffect', () => { it('passes `push` correctly to the component', () => { let receivedPush const targetNode = document.createElement('div') const push = () => {} const state = {} function Example ({push}) { receivedPush = push return <div /> } renderEffect(Example, targetNode)(push)(state) equal(receivedPush, push) }) it('passes state data correctly to the component', () => { let receivedState const targetNode = document.createElement('div') const push = () => {} const state = { complex: { nested: [ 'structure' ] } } function Example ({push, ...state}) { receivedState = state return <div /> } renderEffect(Example, targetNode)(push)(state) deepEqual(receivedState, state) }) it('updates the component when there is new state', () => { const targetNode = document.createElement('div') const push = () => {} function Example ({push, text}) { return <div>{text}</div> } const renderListener = renderEffect(Example, targetNode)(push) renderListener({ text: 'Hello' }) equal(targetNode.children[0].textContent, 'Hello') renderListener({ text: '今日は' }) equal(targetNode.children[0].textContent, '今日は') }) })
examples/official-storybook/components/FlowTypeButton.js
kadirahq/react-storybook
/* eslint-disable react/require-default-props, react/no-unused-prop-types */ // @flow import React from 'react'; const Message = {}; interface PropsType { /** A multi-type prop to be rendered in the button */ label: string; /** Function to be called when the button is clicked */ onClick?: Function; /** Boolean representing whether the button is disabled */ disabled?: boolean; /** A plain object */ obj?: Record<string, any>; /** A complex Object with nested types */ shape: { id: number, func?: Function, arr?: { index: number, }[], shape?: { shape?: { foo?: string, }, }, }; /** An array of numbers */ arrayOf?: number[]; /** A custom type */ msg?: typeof Message; /** `oneOf` as Enum */ enm?: 'News' | 'Photos'; /** `oneOf` A multi-type prop of string or custom Message */ union?: string | typeof Message; } /** FlowTypeButton component description imported from comments inside the component file */ const FlowTypeButton = ({ label, onClick, disabled }: PropsType) => ( <button type="button" onClick={onClick} disabled={disabled}> {label} </button> ); FlowTypeButton.defaultProps = { disabled: false, onClick: () => {}, }; export default FlowTypeButton;
ajax/libs/yui/3.0.0/event-custom/event-custom.js
pombredanne/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var BEFORE = 0, AFTER = 1; Y.Do = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ Y.Do.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype._delete = function (sid) { delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ Y.Do.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case Y.Do.Halt: return ret.retVal; case Y.Do.AlterArgs: args = ret.newArgs; break; case Y.Do.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == Y.Do.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == Y.Do.AlterReturn) { ret = newRet.newRetVal; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ Y.Do.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ Y.Do.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ Y.Do.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ Y.Do.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ Y.Do.Error = Y.Do.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); })(); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param evt {CustomEvent} the custom event * @param sub {Subscriber} the subscriber */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'details', 'emitFacade', 'fireOnce', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { /** * Detaches this subscriber * @method detach */ detach: function() { var evt = this.evt, i; if (evt) { if (Y.Lang.isArray(evt)) { for (i=0; i<evt.length; i++) { evt[i].detach(); } } else { evt._delete(this.sub); } } } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param o configuration object * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber{} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber{} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log("Invalid callback for CE: " + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { Y.later(0, this, Y.bind(this._notify, this, s, this.firedWith)); } if (when == AFTER) { this.afters[s.id] = s; this.hasAfters = true; } else { this.subscribers[s.id] = s; this.hasSubscribers = true; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute * @return {EventHandle|EventTarget} unsubscribe handle or a * chainable event target depending on the 'chain' config. * @deprecated use on */ subscribe: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute * @return {EventHandle|EventTarget} unsubscribe handle or a * chainable event target depending on the 'chain' config. */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute * @return {EventHandle|EventTarget} unsubscribe handle or a * chainable event target depending on the 'chain' config. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int|EventTarget} returns a chainable event target * or the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var found = 0, subs = this.subscribers, i, s; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {boolean|EventTarget} returns a chainable event target * or a boolean for legacy detach support. * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param s {Subscriber} the subscriber * @param args {Array} the arguments array to apply to the listener * @private */ _notify: function(s, args, ef) { this.log(this.type + "->" + "sub: " + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + " cancelled by subscriber"); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param msg {string} message to log * @param cat {string} log category */ log: function(msg, cat) { if (!this.silent) { } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { if (this.hasSubscribers || this.hasAfters) { this._procSubs(Y.merge(this.subscribers, this.afters), args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object * @private */ _delete: function(s) { if (s) { delete s.fn; delete s.context; delete this.subscribers[s.id]; delete this.afters[s.id]; } } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute * @param {Object} context The value of the keyword 'this' in the listener * @param {Array} args* 0..n additional arguments to supply the listener * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ this.events = null; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber * @param ce {CustomEvent} The custom event that sent the notification */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch(e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} context optional 'this' keyword for the listener * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory, menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, broadcast: o.broadcast, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context, x) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent; if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = Y.Array(arguments, 0, true); ret = {}; after = type._after; delete type._after; Y.each(type, function(v, k) { if (v) { f = v.fn || ((Y.Lang.isFunction(v)) ? v : f); c = v.context || c; } args[0] = (after) ? AFTER_PREFIX + k : k; args[1] = f; args[2] = c; ret[k] = this.on.apply(this, args); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) { args = Y.Array(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); return Y.on.apply(Y, args); } type = parts[1]; if (this instanceof YUI) { adapt = Y.Env.evt.plugins[type]; args = Y.Array(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (n instanceof Y.NodeList) { n = Y.NodeList.getDOMNodes(n); } else if (n instanceof Node) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? Y.Array(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, ret, Node = Y.Node, isNode = (this instanceof Node); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { ret = evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return ret; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, handle, adapt, store = Y.Env.evt.handles, cat, args, ce, keyDetacher = function(lcat, ltype) { var handles = lcat[ltype]; if (handles) { while (handles.length) { handle = handles.pop(); handle.detach(); } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; if (cat) { if (type) { keyDetacher(cat, type); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i); } } } return (this._yuievt.chain) ? this : true; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { ret = type.detach(); return (this._yuievt.chain) ? this : ret; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = Y.Array(arguments, 0, true); args[2] = Node.getDOMNode(this); return Y.detach.apply(Y, args); } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (this instanceof YUI) { args = Y.Array(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { return adapt.detach.apply(Y, args); // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; return Y.Event.detach.apply(Y.Event, args); } } ce = evts[type]; if (ce) { ret = ce.detach(fn, context); } return (this._yuievt.chain) ? this : ret; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {Event.Custom} the custom event * */ publish: function(type, opts) { var events, ce, ret, pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = this._yuievt.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.mix(opts, this._yuievt.defaults) : this._yuievt.defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * @method addTarget * @param o {EventTarget} the target to add */ addTarget: function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }, /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove */ removeTarget: function(o) { delete this._yuievt.targets[Y.stamp(o)]; }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {Event.Target} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, a, ret, pre=this._yuievt.config.prefix; t = (pre) ? _getType(t, pre) : t; ce = this.getEvent(t, true); // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { a = (typeIncluded) ? arguments : Y.Array(arguments, 0, true).unshift(t); return this.bubble(null, a, this); } // otherwise there is nothing to be done ret = true; } else { a = Y.Array(arguments, (typeIncluded) ? 1 : 0, true); ret = ce.fire.apply(ce, a); // clear target for next fire() ce.target = null; } return (this._yuievt.chain) ? this : ret; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {Event.Custom} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return (e && type in e) ? e[type] : null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = Y.Array(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle * @deprecated use the on method */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? })(); /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('domready', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param target a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']}); YUI.add('event-custom-complex', function(Y) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ (function() { var FACADE, FACADE_KEYS, CEProto = Y.CustomEvent.prototype; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || {}; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type * @property type * @type string */ this.type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @propery target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; /** * Stops the propagation to the next bubble target * @method stopPropagation */ this.stopPropagation = function() { e.stopPropagation(); }; /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ this.stopImmediatePropagation = function() { e.stopImmediatePropagation(); }; /** * Prevents the event's default behavior * @method preventDefault */ this.preventDefault = function() { e.preventDefault(); }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ this.halt = function(immediate) { e.halt(immediate); }; }; CEProto.fireComplex = function(args) { var es = Y.Env._eventstack, ef, q, queue, ce, ret, events; if (es) { // queue this event if the current item in the queue bubbles if (this.queuable && this.type != es.next.type) { this.log('queue ' + this.type); es.queue.push([this, args]); return true; } } else { Y.Env._eventstack = { // id of the first event in the stack id: this.id, next: this, silent: this.silent, stopped: 0, prevented: 0, queue: [] }; es = Y.Env._eventstack; } this.stopped = 0; this.prevented = 0; this.target = this.target || this.host; events = new Y.EventTarget({ fireOnce: true, context: this.host }); this.events = events; if (this.preventedFn) { events.on('prevented', this.preventedFn); } if (this.stoppedFn) { events.on('stopped', this.stoppedFn); } this.currentTarget = this.host || this.currentTarget; this.details = args.slice(); // original arguments in the details // this.log("Firing " + this + ", " + "args: " + args); this.log("Firing " + this.type); this._facade = null; // kill facade to eliminate stale properties ef = this._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } if (this.hasSubscribers) { this._procSubs(Y.merge(this.subscribers), args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (this.bubbles && this.host && this.host.bubble && !this.stopped) { es.stopped = 0; es.prevented = 0; ret = this.host.bubble(this); this.stopped = Math.max(this.stopped, es.stopped); this.prevented = Math.max(this.prevented, es.prevented); } // execute the default behavior if not prevented if (this.defaultFn && !this.prevented) { this.defaultFn.apply(this.host || this, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. this._broadcast(args); // process after listeners. If the default behavior was // prevented, the after events don't fire. if (this.hasAfters && !this.prevented && this.stopped < 2) { this._procSubs(Y.merge(this.afters), args, ef); } if (es.id === this.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; es.stopped = 0; es.prevented = 0; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); } Y.Env._eventstack = null; } return this.stopped ? false : true; }; CEProto._getFacade = function() { var ef = this._facade, o, o2, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { o2 = {}; // protect the event facade properties Y.mix(o2, ef, true, FACADE_KEYS); // mix the data Y.mix(ef, o, true); // restore ef Y.mix(ef, o2, true, FACADE_KEYS); } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; ef.target = this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; Y.Env._eventstack.stopped = 1; this.events.fire('stopped', this); }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; Y.Env._eventstack.stopped = 2; this.events.fire('stopped', this); }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; Y.Env._eventstack.prevented = 1; this.events.fire('prevented', this); } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {Event.Custom} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ Y.EventTarget.prototype.bubble = function(evt, args, target) { var targs = this._yuievt.targets, ret = true, t, type, ce, i, bc; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; type = evt && evt.type; ce = t.getEvent(type, true); // if this event was not published on the bubble target, // publish it with sensible default properties if (!ce) { if (t._yuievt.hasTargets) { t.bubble.call(t, evt, args, target); } } else { ce.target = target || (evt && evt.target) || this; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; ret = ret && ce.fire.apply(ce, args || evt.details); ce.broadcast = bc; // stopPropagation() was called if (ce.stopped) { break; } } } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = Y.Object.keys(FACADE); })(); }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('event-custom', function(Y){}, '@VERSION@' ,{use:['event-custom-base', 'event-custom-complex']});
src/routes/error/index.js
mikeyshing88/MUN
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import App from '../../components/App'; import ErrorPage from './ErrorPage'; export default { path: '/error', action({ render, context, error }) { return render( <App context={context} error={error}> <ErrorPage error={error} /> </App>, error.status || 500 ); }, };
Glossary/Scripts/jquery-1.5.1.min.js
evjan/Glossary
/*! * Note: While Microsoft is not the author of this file, Microsoft is * offering you a license subject to the terms of the Microsoft Software * License Terms for Microsoft ASP.NET Model View Controller 3. * Microsoft reserves all other rights. The notices below are provided * for informational purposes only and are not the license terms under * which Microsoft distributed this file. * * jQuery JavaScript Library v1.5.1 * http://jquery.com/ * Copyright 2011, John Resig * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * * Date: Thu Nov 11 19:04:53 2010 -0500 */ (function(a,b){function cg(a){return d.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cd(a){if(!bZ[a]){var b=d("<"+a+">").appendTo("body"),c=b.css("display");b.remove();if(c==="none"||c==="")c="block";bZ[a]=c}return bZ[a]}function cc(a,b){var c={};d.each(cb.concat.apply([],cb.slice(0,b)),function(){c[this]=a});return c}function bY(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function bX(){try{return new a.XMLHttpRequest}catch(b){}}function bW(){d(a).unload(function(){for(var a in bU)bU[a](0,1)})}function bQ(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var e=a.dataTypes,f={},g,h,i=e.length,j,k=e[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h==="string"&&(f[h.toLowerCase()]=a.converters[h]);l=k,k=e[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=f[m]||f["* "+k];if(!n){p=b;for(o in f){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=f[j[1]+" "+k];if(p){o=f[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&d.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bP(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bO(a,b,c,e){if(d.isArray(b)&&b.length)d.each(b,function(b,f){c||bq.test(a)?e(a,f):bO(a+"["+(typeof f==="object"||d.isArray(f)?b:"")+"]",f,c,e)});else if(c||b==null||typeof b!=="object")e(a,b);else if(d.isArray(b)||d.isEmptyObject(b))e(a,"");else for(var f in b)bO(a+"["+f+"]",b[f],c,e)}function bN(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bH,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l==="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bN(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bN(a,c,d,e,"*",g));return l}function bM(a){return function(b,c){typeof b!=="string"&&(c=b,b="*");if(d.isFunction(c)){var e=b.toLowerCase().split(bB),f=0,g=e.length,h,i,j;for(;f<g;f++)h=e[f],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bo(a,b,c){var e=b==="width"?bi:bj,f=b==="width"?a.offsetWidth:a.offsetHeight;if(c==="border")return f;d.each(e,function(){c||(f-=parseFloat(d.css(a,"padding"+this))||0),c==="margin"?f+=parseFloat(d.css(a,"margin"+this))||0:f-=parseFloat(d.css(a,"border"+this+"Width"))||0});return f}function ba(a,b){b.src?d.ajax({url:b.src,async:!1,dataType:"script"}):d.globalEval(b.text||b.textContent||b.innerHTML||""),b.parentNode&&b.parentNode.removeChild(b)}function _(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function $(a,b){if(b.nodeType===1){var c=b.nodeName.toLowerCase();b.clearAttributes(),b.mergeAttributes(a);if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(d.expando)}}function Z(a,b){if(b.nodeType===1&&d.hasData(a)){var c=d.expando,e=d.data(a),f=d.data(b,e);if(e=e[c]){var g=e.events;f=f[c]=d.extend({},e);if(g){delete f.handle,f.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)d.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function Y(a,b){return d.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function O(a,b,c){if(d.isFunction(b))return d.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return d.grep(a,function(a,d){return a===b===c});if(typeof b==="string"){var e=d.grep(a,function(a){return a.nodeType===1});if(J.test(b))return d.filter(b,e,!c);b=d.filter(b,e)}return d.grep(a,function(a,e){return d.inArray(a,b)>=0===c})}function N(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function F(a,b){return(a&&a!=="*"?a+".":"")+b.replace(r,"`").replace(s,"&")}function E(a){var b,c,e,f,g,h,i,j,k,l,m,n,o,q=[],r=[],s=d._data(this,"events");if(a.liveFired!==this&&s&&s.live&&!a.target.disabled&&(!a.button||a.type!=="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var t=s.live.slice(0);for(i=0;i<t.length;i++)g=t[i],g.origType.replace(p,"")===a.type?r.push(g.selector):t.splice(i--,1);f=d(a.target).closest(r,a.currentTarget);for(j=0,k=f.length;j<k;j++){m=f[j];for(i=0;i<t.length;i++){g=t[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,e=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,e=d(a.relatedTarget).closest(g.selector)[0];(!e||e!==h)&&q.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=q.length;j<k;j++){f=q[j];if(c&&f.level>c)break;a.currentTarget=f.elem,a.data=f.handleObj.data,a.handleObj=f.handleObj,o=f.handleObj.origHandler.apply(f.elem,arguments);if(o===!1||a.isPropagationStopped()){c=f.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function C(a,c,e){var f=d.extend({},e[0]);f.type=a,f.originalEvent={},f.liveFired=b,d.event.handle.call(c,f),f.isDefaultPrevented()&&e[0].preventDefault()}function w(){return!0}function v(){return!1}function g(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function f(a,c,f){if(f===b&&a.nodeType===1){f=a.getAttribute("data-"+c);if(typeof f==="string"){try{f=f==="true"?!0:f==="false"?!1:f==="null"?null:d.isNaN(f)?e.test(f)?d.parseJSON(f):f:parseFloat(f)}catch(g){}d.data(a,c,f)}else f=b}return f}var c=a.document,d=function(){function I(){if(!d.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(I,1);return}d.ready()}}var d=function(a,b){return new d.fn.init(a,b,g)},e=a.jQuery,f=a.$,g,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,i=/\S/,j=/^\s+/,k=/\s+$/,l=/\d/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=navigator.userAgent,w,x=!1,y,z="then done fail isResolved isRejected promise".split(" "),A,B=Object.prototype.toString,C=Object.prototype.hasOwnProperty,D=Array.prototype.push,E=Array.prototype.slice,F=String.prototype.trim,G=Array.prototype.indexOf,H={};d.fn=d.prototype={constructor:d,init:function(a,e,f){var g,i,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!e&&c.body){this.context=c,this[0]=c.body,this.selector="body",this.length=1;return this}if(typeof a==="string"){g=h.exec(a);if(!g||!g[1]&&e)return!e||e.jquery?(e||f).find(a):this.constructor(e).find(a);if(g[1]){e=e instanceof d?e[0]:e,k=e?e.ownerDocument||e:c,j=m.exec(a),j?d.isPlainObject(e)?(a=[c.createElement(j[1])],d.fn.attr.call(a,e,!0)):a=[k.createElement(j[1])]:(j=d.buildFragment([g[1]],[k]),a=(j.cacheable?d.clone(j.fragment):j.fragment).childNodes);return d.merge(this,a)}i=c.getElementById(g[2]);if(i&&i.parentNode){if(i.id!==g[2])return f.find(a);this.length=1,this[0]=i}this.context=c,this.selector=a;return this}if(d.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return d.makeArray(a,this)},selector:"",jquery:"1.5.1",length:0,size:function(){return this.length},toArray:function(){return E.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var e=this.constructor();d.isArray(a)?D.apply(e,a):d.merge(e,a),e.prevObject=this,e.context=this.context,b==="find"?e.selector=this.selector+(this.selector?" ":"")+c:b&&(e.selector=this.selector+"."+b+"("+c+")");return e},each:function(a,b){return d.each(this,a,b)},ready:function(a){d.bindReady(),y.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(E.apply(this,arguments),"slice",E.call(arguments).join(","))},map:function(a){return this.pushStack(d.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:D,sort:[].sort,splice:[].splice},d.fn.init.prototype=d.fn,d.extend=d.fn.extend=function(){var a,c,e,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i==="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!=="object"&&!d.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){e=i[c],f=a[c];if(i===f)continue;l&&f&&(d.isPlainObject(f)||(g=d.isArray(f)))?(g?(g=!1,h=e&&d.isArray(e)?e:[]):h=e&&d.isPlainObject(e)?e:{},i[c]=d.extend(l,h,f)):f!==b&&(i[c]=f)}return i},d.extend({noConflict:function(b){a.$=f,b&&(a.jQuery=e);return d},isReady:!1,readyWait:1,ready:function(a){a===!0&&d.readyWait--;if(!d.readyWait||a!==!0&&!d.isReady){if(!c.body)return setTimeout(d.ready,1);d.isReady=!0;if(a!==!0&&--d.readyWait>0)return;y.resolveWith(c,[d]),d.fn.trigger&&d(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!x){x=!0;if(c.readyState==="complete")return setTimeout(d.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",A,!1),a.addEventListener("load",d.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",A),a.attachEvent("onload",d.ready);var b=!1;try{b=a.frameElement==null}catch(e){}c.documentElement.doScroll&&b&&I()}}},isFunction:function(a){return d.type(a)==="function"},isArray:Array.isArray||function(a){return d.type(a)==="array"},isWindow:function(a){return a&&typeof a==="object"&&"setInterval"in a},isNaN:function(a){return a==null||!l.test(a)||isNaN(a)},type:function(a){return a==null?String(a):H[B.call(a)]||"object"},isPlainObject:function(a){if(!a||d.type(a)!=="object"||a.nodeType||d.isWindow(a))return!1;if(a.constructor&&!C.call(a,"constructor")&&!C.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a){}return c===b||C.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!=="string"||!b)return null;b=d.trim(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return a.JSON&&a.JSON.parse?a.JSON.parse(b):(new Function("return "+b))();d.error("Invalid JSON: "+b)},parseXML:function(b,c,e){a.DOMParser?(e=new DOMParser,c=e.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),e=c.documentElement,(!e||!e.nodeName||e.nodeName==="parsererror")&&d.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(a){if(a&&i.test(a)){var b=c.head||c.getElementsByTagName("head")[0]||c.documentElement,e=c.createElement("script");d.support.scriptEval()?e.appendChild(c.createTextNode(a)):e.text=a,b.insertBefore(e,b.firstChild),b.removeChild(e)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,e){var f,g=0,h=a.length,i=h===b||d.isFunction(a);if(e){if(i){for(f in a)if(c.apply(a[f],e)===!1)break}else for(;g<h;)if(c.apply(a[g++],e)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(var j=a[0];g<h&&c.call(j,g,j)!==!1;j=a[++g]){}return a},trim:F?function(a){return a==null?"":F.call(a)}:function(a){return a==null?"":(a+"").replace(j,"").replace(k,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var e=d.type(a);a.length==null||e==="string"||e==="function"||e==="regexp"||d.isWindow(a)?D.call(c,a):d.merge(c,a)}return c},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length==="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,b,c){var d=[],e;for(var f=0,g=a.length;f<g;f++)e=b(a[f],f,c),e!=null&&(d[d.length]=e);return d.concat.apply([],d)},guid:1,proxy:function(a,c,e){arguments.length===2&&(typeof c==="string"?(e=a,a=e[c],c=b):c&&!d.isFunction(c)&&(e=c,c=b)),!c&&a&&(c=function(){return a.apply(e||this,arguments)}),a&&(c.guid=a.guid=a.guid||c.guid||d.guid++);return c},access:function(a,c,e,f,g,h){var i=a.length;if(typeof c==="object"){for(var j in c)d.access(a,j,c[j],f,g,e);return a}if(e!==b){f=!h&&f&&d.isFunction(e);for(var k=0;k<i;k++)g(a[k],c,f?e.call(a[k],k,g(a[k],c)):e,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},_Deferred:function(){var a=[],b,c,e,f={done:function(){if(!e){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=d.type(i),j==="array"?f.done.apply(f,i):j==="function"&&a.push(i);k&&f.resolveWith(k[0],k[1])}return this},resolveWith:function(d,f){if(!e&&!b&&!c){c=1;try{while(a[0])a.shift().apply(d,f)}catch(g){throw g}finally{b=[d,f],c=0}}return this},resolve:function(){f.resolveWith(d.isFunction(this.promise)?this.promise():this,arguments);return this},isResolved:function(){return c||b},cancel:function(){e=1,a=[];return this}};return f},Deferred:function(a){var b=d._Deferred(),c=d._Deferred(),e;d.extend(b,{then:function(a,c){b.done(a).fail(c);return this},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,promise:function(a){if(a==null){if(e)return e;e=a={}}var c=z.length;while(c--)a[z[c]]=b[z[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){var b=arguments.length,c=b<=1&&a&&d.isFunction(a.promise)?a:d.Deferred(),e=c.promise();if(b>1){var f=E.call(arguments,0),g=b,h=function(a){return function(b){f[a]=arguments.length>1?E.call(arguments,0):b,--g||c.resolveWith(e,f)}};while(b--)a=f[b],a&&d.isFunction(a.promise)?a.promise().then(h(b),c.reject):--g;g||c.resolveWith(e,f)}else c!==a&&c.resolve(a);return e},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}d.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.subclass=this.subclass,a.fn.init=function b(b,c){c&&c instanceof d&&!(c instanceof a)&&(c=a(c));return d.fn.init.call(this,b,c,e)},a.fn.init.prototype=a.fn;var e=a(c);return a},browser:{}}),y=d._Deferred(),d.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){H["[object "+b+"]"]=b.toLowerCase()}),w=d.uaMatch(v),w.browser&&(d.browser[w.browser]=!0,d.browser.version=w.version),d.browser.webkit&&(d.browser.safari=!0),G&&(d.inArray=function(a,b){return G.call(b,a)}),i.test(" ")&&(j=/^[\s\xA0]+/,k=/[\s\xA0]+$/),g=d(c),c.addEventListener?A=function(){c.removeEventListener("DOMContentLoaded",A,!1),d.ready()}:c.attachEvent&&(A=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",A),d.ready())});return d}();(function(){d.support={};var b=c.createElement("div");b.style.display="none",b.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var e=b.getElementsByTagName("*"),f=b.getElementsByTagName("a")[0],g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=b.getElementsByTagName("input")[0];if(e&&e.length&&f){d.support={leadingWhitespace:b.firstChild.nodeType===3,tbody:!b.getElementsByTagName("tbody").length,htmlSerialize:!!b.getElementsByTagName("link").length,style:/red/.test(f.getAttribute("style")),hrefNormalized:f.getAttribute("href")==="/a",opacity:/^0.55$/.test(f.style.opacity),cssFloat:!!f.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,deleteExpando:!0,optDisabled:!1,checkClone:!1,noCloneEvent:!0,noCloneChecked:!0,boxModel:null,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableHiddenOffsets:!0},i.checked=!0,d.support.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,d.support.optDisabled=!h.disabled;var j=null;d.support.scriptEval=function(){if(j===null){var b=c.documentElement,e=c.createElement("script"),f="script"+d.now();try{e.appendChild(c.createTextNode("window."+f+"=1;"))}catch(g){}b.insertBefore(e,b.firstChild),a[f]?(j=!0,delete a[f]):j=!1,b.removeChild(e),b=e=f=null}return j};try{delete b.test}catch(k){d.support.deleteExpando=!1}!b.addEventListener&&b.attachEvent&&b.fireEvent&&(b.attachEvent("onclick",function l(){d.support.noCloneEvent=!1,b.detachEvent("onclick",l)}),b.cloneNode(!0).fireEvent("onclick")),b=c.createElement("div"),b.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";var m=c.createDocumentFragment();m.appendChild(b.firstChild),d.support.checkClone=m.cloneNode(!0).cloneNode(!0).lastChild.checked,d(function(){var a=c.createElement("div"),b=c.getElementsByTagName("body")[0];if(b){a.style.width=a.style.paddingLeft="1px",b.appendChild(a),d.boxModel=d.support.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,d.support.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",d.support.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";var e=a.getElementsByTagName("td");d.support.reliableHiddenOffsets=e[0].offsetHeight===0,e[0].style.display="",e[1].style.display="none",d.support.reliableHiddenOffsets=d.support.reliableHiddenOffsets&&e[0].offsetHeight===0,a.innerHTML="",b.removeChild(a).style.display="none",a=e=null}});var n=function(a){var b=c.createElement("div");a="on"+a;if(!b.attachEvent)return!0;var d=a in b;d||(b.setAttribute(a,"return;"),d=typeof b[a]==="function"),b=null;return d};d.support.submitBubbles=n("submit"),d.support.changeBubbles=n("change"),b=e=f=null}})();var e=/^(?:\{.*\}|\[.*\])$/;d.extend({cache:{},uuid:0,expando:"jQuery"+(d.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?d.cache[a[d.expando]]:a[d.expando];return!!a&&!g(a)},data:function(a,c,e,f){if(d.acceptData(a)){var g=d.expando,h=typeof c==="string",i,j=a.nodeType,k=j?d.cache:a,l=j?a[d.expando]:a[d.expando]&&d.expando;if((!l||f&&l&&!k[l][g])&&h&&e===b)return;l||(j?a[d.expando]=l=++d.uuid:l=d.expando),k[l]||(k[l]={},j||(k[l].toJSON=d.noop));if(typeof c==="object"||typeof c==="function")f?k[l][g]=d.extend(k[l][g],c):k[l]=d.extend(k[l],c);i=k[l],f&&(i[g]||(i[g]={}),i=i[g]),e!==b&&(i[c]=e);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[c]:i}},removeData:function(b,c,e){if(d.acceptData(b)){var f=d.expando,h=b.nodeType,i=h?d.cache:b,j=h?b[d.expando]:d.expando;if(!i[j])return;if(c){var k=e?i[j][f]:i[j];if(k){delete k[c];if(!g(k))return}}if(e){delete i[j][f];if(!g(i[j]))return}var l=i[j][f];d.support.deleteExpando||i!=a?delete i[j]:i[j]=null,l?(i[j]={},h||(i[j].toJSON=d.noop),i[j][f]=l):h&&(d.support.deleteExpando?delete b[d.expando]:b.removeAttribute?b.removeAttribute(d.expando):b[d.expando]=null)}},_data:function(a,b,c){return d.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=d.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),d.fn.extend({data:function(a,c){var e=null;if(typeof a==="undefined"){if(this.length){e=d.data(this[0]);if(this[0].nodeType===1){var g=this[0].attributes,h;for(var i=0,j=g.length;i<j;i++)h=g[i].name,h.indexOf("data-")===0&&(h=h.substr(5),f(this[0],h,e[h]))}}return e}if(typeof a==="object")return this.each(function(){d.data(this,a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(c===b){e=this.triggerHandler("getData"+k[1]+"!",[k[0]]),e===b&&this.length&&(e=d.data(this[0],a),e=f(this[0],a,e));return e===b&&k[1]?this.data(k[0]):e}return this.each(function(){var b=d(this),e=[k[0],c];b.triggerHandler("setData"+k[1]+"!",e),d.data(this,a,c),b.triggerHandler("changeData"+k[1]+"!",e)})},removeData:function(a){return this.each(function(){d.removeData(this,a)})}}),d.extend({queue:function(a,b,c){if(a){b=(b||"fx")+"queue";var e=d._data(a,b);if(!c)return e||[];!e||d.isArray(c)?e=d._data(a,b,d.makeArray(c)):e.push(c);return e}},dequeue:function(a,b){b=b||"fx";var c=d.queue(a,b),e=c.shift();e==="inprogress"&&(e=c.shift()),e&&(b==="fx"&&c.unshift("inprogress"),e.call(a,function(){d.dequeue(a,b)})),c.length||d.removeData(a,b+"queue",!0)}}),d.fn.extend({queue:function(a,c){typeof a!=="string"&&(c=a,a="fx");if(c===b)return d.queue(this[0],a);return this.each(function(b){var e=d.queue(this,a,c);a==="fx"&&e[0]!=="inprogress"&&d.dequeue(this,a)})},dequeue:function(a){return this.each(function(){d.dequeue(this,a)})},delay:function(a,b){a=d.fx?d.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){d.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var h=/[\n\t\r]/g,i=/\s+/,j=/\r/g,k=/^(?:href|src|style)$/,l=/^(?:button|input)$/i,m=/^(?:button|input|object|select|textarea)$/i,n=/^a(?:rea)?$/i,o=/^(?:radio|checkbox)$/i;d.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"},d.fn.extend({attr:function(a,b){return d.access(this,a,b,!0,d.attr)},removeAttr:function(a,b){return this.each(function(){d.attr(this,a,""),this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.addClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"){var b=(a||"").split(i);for(var c=0,e=this.length;c<e;c++){var f=this[c];if(f.nodeType===1)if(f.className){var g=" "+f.className+" ",h=f.className;for(var j=0,k=b.length;j<k;j++)g.indexOf(" "+b[j]+" ")<0&&(h+=" "+b[j]);f.className=d.trim(h)}else f.className=a}}return this},removeClass:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.removeClass(a.call(this,b,c.attr("class")))});if(a&&typeof a==="string"||a===b){var c=(a||"").split(i);for(var e=0,f=this.length;e<f;e++){var g=this[e];if(g.nodeType===1&&g.className)if(a){var j=(" "+g.className+" ").replace(h," ");for(var k=0,l=c.length;k<l;k++)j=j.replace(" "+c[k]+" "," ");g.className=d.trim(j)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,e=typeof b==="boolean";if(d.isFunction(a))return this.each(function(c){var e=d(this);e.toggleClass(a.call(this,c,e.attr("class"),b),b)});return this.each(function(){if(c==="string"){var f,g=0,h=d(this),j=b,k=a.split(i);while(f=k[g++])j=e?j:!h.hasClass(f),h[j?"addClass":"removeClass"](f)}else if(c==="undefined"||c==="boolean")this.className&&d._data(this,"__className__",this.className),this.className=this.className||a===!1?"":d._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(h," ").indexOf(b)>-1)return!0;return!1},val:function(a){if(!arguments.length){var c=this[0];if(c){if(d.nodeName(c,"option")){var e=c.attributes.value;return!e||e.specified?c.value:c.text}if(d.nodeName(c,"select")){var f=c.selectedIndex,g=[],h=c.options,i=c.type==="select-one";if(f<0)return null;for(var k=i?f:0,l=i?f+1:h.length;k<l;k++){var m=h[k];if(m.selected&&(d.support.optDisabled?!m.disabled:m.getAttribute("disabled")===null)&&(!m.parentNode.disabled||!d.nodeName(m.parentNode,"optgroup"))){a=d(m).val();if(i)return a;g.push(a)}}if(i&&!g.length&&h.length)return d(h[f]).val();return g}if(o.test(c.type)&&!d.support.checkOn)return c.getAttribute("value")===null?"on":c.value;return(c.value||"").replace(j,"")}return b}var n=d.isFunction(a);return this.each(function(b){var c=d(this),e=a;if(this.nodeType===1){n&&(e=a.call(this,b,c.val())),e==null?e="":typeof e==="number"?e+="":d.isArray(e)&&(e=d.map(e,function(a){return a==null?"":a+""}));if(d.isArray(e)&&o.test(this.type))this.checked=d.inArray(c.val(),e)>=0;else if(d.nodeName(this,"select")){var f=d.makeArray(e);d("option",this).each(function(){this.selected=d.inArray(d(this).val(),f)>=0}),f.length||(this.selectedIndex=-1)}else this.value=e}})}}),d.extend({attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,e,f){if(!a||a.nodeType===3||a.nodeType===8||a.nodeType===2)return b;if(f&&c in d.attrFn)return d(a)[c](e);var g=a.nodeType!==1||!d.isXMLDoc(a),h=e!==b;c=g&&d.props[c]||c;if(a.nodeType===1){var i=k.test(c);if(c==="selected"&&!d.support.optSelected){var j=a.parentNode;j&&(j.selectedIndex,j.parentNode&&j.parentNode.selectedIndex)}if((c in a||a[c]!==b)&&g&&!i){h&&(c==="type"&&l.test(a.nodeName)&&a.parentNode&&d.error("type property can't be changed"),e===null?a.nodeType===1&&a.removeAttribute(c):a[c]=e);if(d.nodeName(a,"form")&&a.getAttributeNode(c))return a.getAttributeNode(c).nodeValue;if(c==="tabIndex"){var o=a.getAttributeNode("tabIndex");return o&&o.specified?o.value:m.test(a.nodeName)||n.test(a.nodeName)&&a.href?0:b}return a[c]}if(!d.support.style&&g&&c==="style"){h&&(a.style.cssText=""+e);return a.style.cssText}h&&a.setAttribute(c,""+e);if(!a.attributes[c]&&(a.hasAttribute&&!a.hasAttribute(c)))return b;var p=!d.support.hrefNormalized&&g&&i?a.getAttribute(c,2):a.getAttribute(c);return p===null?b:p}h&&(a[c]=e);return a[c]}});var p=/\.(.*)$/,q=/^(?:textarea|input|select)$/i,r=/\./g,s=/ /g,t=/[^\w\s.|`]/g,u=function(a){return a.replace(t,"\\$&")};d.event={add:function(c,e,f,g){if(c.nodeType!==3&&c.nodeType!==8){try{d.isWindow(c)&&(c!==a&&!c.frameElement)&&(c=a)}catch(h){}if(f===!1)f=v;else if(!f)return;var i,j;f.handler&&(i=f,f=i.handler),f.guid||(f.guid=d.guid++);var k=d._data(c);if(!k)return;var l=k.events,m=k.handle;l||(k.events=l={}),m||(k.handle=m=function(){return typeof d!=="undefined"&&!d.event.triggered?d.event.handle.apply(m.elem,arguments):b}),m.elem=c,e=e.split(" ");var n,o=0,p;while(n=e[o++]){j=i?d.extend({},i):{handler:f,data:g},n.indexOf(".")>-1?(p=n.split("."),n=p.shift(),j.namespace=p.slice(0).sort().join(".")):(p=[],j.namespace=""),j.type=n,j.guid||(j.guid=f.guid);var q=l[n],r=d.event.special[n]||{};if(!q){q=l[n]=[];if(!r.setup||r.setup.call(c,g,p,m)===!1)c.addEventListener?c.addEventListener(n,m,!1):c.attachEvent&&c.attachEvent("on"+n,m)}r.add&&(r.add.call(c,j),j.handler.guid||(j.handler.guid=f.guid)),q.push(j),d.event.global[n]=!0}c=null}},global:{},remove:function(a,c,e,f){if(a.nodeType!==3&&a.nodeType!==8){e===!1&&(e=v);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=d.hasData(a)&&d._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(e=c.handler,c=c.type);if(!c||typeof c==="string"&&c.charAt(0)==="."){c=c||"";for(h in t)d.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+d.map(m.slice(0).sort(),u).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!e){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))d.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=d.event.special[h]||{};for(j=f||0;j<p.length;j++){q=p[j];if(e.guid===q.guid){if(l||n.test(q.namespace))f==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(f!=null)break}}if(p.length===0||f!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&d.removeEvent(a,h,s.handle),g=null,delete t[h]}if(d.isEmptyObject(t)){var w=s.handle;w&&(w.elem=null),delete s.events,delete s.handle,d.isEmptyObject(s)&&d.removeData(a,b,!0)}}},trigger:function(a,c,e){var f=a.type||a,g=arguments[3];if(!g){a=typeof a==="object"?a[d.expando]?a:d.extend(d.Event(f),a):d.Event(f),f.indexOf("!")>=0&&(a.type=f=f.slice(0,-1),a.exclusive=!0),e||(a.stopPropagation(),d.event.global[f]&&d.each(d.cache,function(){var b=d.expando,e=this[b];e&&e.events&&e.events[f]&&d.event.trigger(a,c,e.handle.elem)}));if(!e||e.nodeType===3||e.nodeType===8)return b;a.result=b,a.target=e,c=d.makeArray(c),c.unshift(a)}a.currentTarget=e;var h=d._data(e,"handle");h&&h.apply(e,c);var i=e.parentNode||e.ownerDocument;try{e&&e.nodeName&&d.noData[e.nodeName.toLowerCase()]||e["on"+f]&&e["on"+f].apply(e,c)===!1&&(a.result=!1,a.preventDefault())}catch(j){}if(!a.isPropagationStopped()&&i)d.event.trigger(a,c,i,!0);else if(!a.isDefaultPrevented()){var k,l=a.target,m=f.replace(p,""),n=d.nodeName(l,"a")&&m==="click",o=d.event.special[m]||{};if((!o._default||o._default.call(e,a)===!1)&&!n&&!(l&&l.nodeName&&d.noData[l.nodeName.toLowerCase()])){try{l[m]&&(k=l["on"+m],k&&(l["on"+m]=null),d.event.triggered=!0,l[m]())}catch(q){}k&&(l["on"+m]=k),d.event.triggered=!1}}},handle:function(c){var e,f,g,h,i,j=[],k=d.makeArray(arguments);c=k[0]=d.event.fix(c||a.event),c.currentTarget=this,e=c.type.indexOf(".")<0&&!c.exclusive,e||(g=c.type.split("."),c.type=g.shift(),j=g.slice(0).sort(),h=new RegExp("(^|\\.)"+j.join("\\.(?:.*\\.)?")+"(\\.|$)")),c.namespace=c.namespace||j.join("."),i=d._data(this,"events"),f=(i||{})[c.type];if(i&&f){f=f.slice(0);for(var l=0,m=f.length;l<m;l++){var n=f[l];if(e||h.test(n.namespace)){c.handler=n.handler,c.data=n.data,c.handleObj=n;var o=n.handler.apply(this,k);o!==b&&(c.result=o,o===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[d.expando])return a;var e=a;a=d.Event(e);for(var f=this.props.length,g;f;)g=this.props[--f],a[g]=e[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=c.documentElement,i=c.body;a.pageX=a.clientX+(h&&h.scrollLeft||i&&i.scrollLeft||0)-(h&&h.clientLeft||i&&i.clientLeft||0),a.pageY=a.clientY+(h&&h.scrollTop||i&&i.scrollTop||0)-(h&&h.clientTop||i&&i.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:d.proxy,special:{ready:{setup:d.bindReady,teardown:d.noop},live:{add:function(a){d.event.add(this,F(a.origType,a.selector),d.extend({},a,{handler:E,guid:a.handler.guid}))},remove:function(a){d.event.remove(this,F(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){d.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},d.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},d.Event=function(a){if(!this.preventDefault)return new d.Event(a);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?w:v):this.type=a,this.timeStamp=d.now(),this[d.expando]=!0},d.Event.prototype={preventDefault:function(){this.isDefaultPrevented=w;var a=this.originalEvent;a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=w;var a=this.originalEvent;a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=w,this.stopPropagation()},isDefaultPrevented:v,isPropagationStopped:v,isImmediatePropagationStopped:v};var x=function(a){var b=a.relatedTarget;try{if(b!==c&&!b.parentNode)return;while(b&&b!==this)b=b.parentNode;b!==this&&(a.type=a.data,d.event.handle.apply(this,arguments))}catch(e){}},y=function(a){a.type=a.data,d.event.handle.apply(this,arguments)};d.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){d.event.special[a]={setup:function(c){d.event.add(this,b,c&&c.selector?y:x,a)},teardown:function(a){d.event.remove(this,b,a&&a.selector?y:x)}}}),d.support.submitBubbles||(d.event.special.submit={setup:function(a,b){if(this.nodeName&&this.nodeName.toLowerCase()!=="form")d.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&d(b).closest("form").length&&C("submit",this,arguments)}),d.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&d(b).closest("form").length&&a.keyCode===13&&C("submit",this,arguments)});else return!1},teardown:function(a){d.event.remove(this,".specialSubmit")}});if(!d.support.changeBubbles){var z,A=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?d.map(a.options,function(a){return a.selected}).join("-"):"":a.nodeName.toLowerCase()==="select"&&(c=a.selectedIndex);return c},B=function B(a){var c=a.target,e,f;if(q.test(c.nodeName)&&!c.readOnly){e=d._data(c,"_change_data"),f=A(c),(a.type!=="focusout"||c.type!=="radio")&&d._data(c,"_change_data",f);if(e===b||f===e)return;if(e!=null||f)a.type="change",a.liveFired=b,d.event.trigger(a,arguments[1],c)}};d.event.special.change={filters:{focusout:B,beforedeactivate:B,click:function(a){var b=a.target,c=b.type;(c==="radio"||c==="checkbox"||b.nodeName.toLowerCase()==="select")&&B.call(this,a)},keydown:function(a){var b=a.target,c=b.type;(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&B.call(this,a)},beforeactivate:function(a){var b=a.target;d._data(b,"_change_data",A(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in z)d.event.add(this,c+".specialChange",z[c]);return q.test(this.nodeName)},teardown:function(a){d.event.remove(this,".specialChange");return q.test(this.nodeName)}},z=d.event.special.change.filters,z.focus=z.beforeactivate}c.addEventListener&&d.each({focus:"focusin",blur:"focusout"},function(a,b){function c(a){a=d.event.fix(a),a.type=b;return d.event.handle.call(this,a)}d.event.special[b]={setup:function(){this.addEventListener(a,c,!0)},teardown:function(){this.removeEventListener(a,c,!0)}}}),d.each(["bind","one"],function(a,c){d.fn[c]=function(a,e,f){if(typeof a==="object"){for(var g in a)this[c](g,e,a[g],f);return this}if(d.isFunction(e)||e===!1)f=e,e=b;var h=c==="one"?d.proxy(f,function(a){d(this).unbind(a,h);return f.apply(this,arguments)}):f;if(a==="unload"&&c!=="one")this.one(a,e,f);else for(var i=0,j=this.length;i<j;i++)d.event.add(this[i],a,h,e);return this}}),d.fn.extend({unbind:function(a,b){if(typeof a!=="object"||a.preventDefault)for(var e=0,f=this.length;e<f;e++)d.event.remove(this[e],a,b);else for(var c in a)this.unbind(c,a[c]);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){d.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var c=d.Event(a);c.preventDefault(),c.stopPropagation(),d.event.trigger(c,b,this[0]);return c.result}},toggle:function(a){var b=arguments,c=1;while(c<b.length)d.proxy(a,b[c++]);return this.click(d.proxy(a,function(e){var f=(d._data(this,"lastToggle"+a.guid)||0)%c;d._data(this,"lastToggle"+a.guid,f+1),e.preventDefault();return b[f].apply(this,arguments)||!1}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var D={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};d.each(["live","die"],function(a,c){d.fn[c]=function(a,e,f,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:d(this.context);if(typeof a==="object"&&!a.preventDefault){for(var o in a)n[c](o,e,a[o],m);return this}d.isFunction(e)&&(f=e,e=b),a=(a||"").split(" ");while((h=a[i++])!=null){j=p.exec(h),k="",j&&(k=j[0],h=h.replace(p,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,h==="focus"||h==="blur"?(a.push(D[h]+k),h=h+k):h=(D[h]||h)+k;if(c==="live")for(var q=0,r=n.length;q<r;q++)d.event.add(n[q],"live."+F(h,m),{data:e,selector:m,handler:f,origType:h,origHandler:f,preType:l});else n.unbind("live."+F(h,m),f)}return this}}),d.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){d.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},d.attrFn&&(d.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!=="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,e,g){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!=="string")return e;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(f.call(n)==="[object Array]")if(u)if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&e.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&e.push(j[t]);else e.push.apply(e,n);else p(n,e);o&&(k(o,h,e,g),k.uniqueSort(e));return e};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!=="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(f){if(f===!0)continue}else g=o=!0}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b==="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1){}a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b==="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=u;typeof b==="string"&&!j.test(b)&&(b=b.toLowerCase(),d=b,g=t),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!=="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!=="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!=="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){return"text"===a.getAttribute("type")},radio:function(a){return"radio"===a.type},checkbox:function(a){return"checkbox"===a.type},file:function(a){return"file"===a.type},password:function(a){return"password"===a.type},submit:function(a){return"submit"===a.type},image:function(a){return"image"===a.type},reset:function(a){return"reset"===a.type},button:function(a){return"button"===a.type||a.nodeName.toLowerCase()==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(f.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length==="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(a===b){g=!0;return 0}if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!=="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!=="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!=="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!=="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector,d=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(e){d=!0}b&&(k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(d||!l.match.PSEUDO.test(c)&&!/!=/.test(c))return b.call(a,c)}catch(e){}return k(c,null,null,[a]).length>0})}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!=="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};d.find=k,d.expr=k.selectors,d.expr[":"]=d.expr.filters,d.unique=k.uniqueSort,d.text=k.getText,d.isXMLDoc=k.isXML,d.contains=k.contains}();var G=/Until$/,H=/^(?:parents|prevUntil|prevAll)/,I=/,/,J=/^.[^:#\[\.,]*$/,K=Array.prototype.slice,L=d.expr.match.POS,M={children:!0,contents:!0,next:!0,prev:!0};d.fn.extend({find:function(a){var b=this.pushStack("","find",a),c=0;for(var e=0,f=this.length;e<f;e++){c=b.length,d.find(a,this[e],b);if(e>0)for(var g=c;g<b.length;g++)for(var h=0;h<c;h++)if(b[h]===b[g]){b.splice(g--,1);break}}return b},has:function(a){var b=d(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(d.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(O(this,a,!1),"not",a)},filter:function(a){return this.pushStack(O(this,a,!0),"filter",a)},is:function(a){return!!a&&d.filter(a,this).length>0},closest:function(a,b){var c=[],e,f,g=this[0];if(d.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(e=0,f=a.length;e<f;e++)i=a[e],j[i]||(j[i]=d.expr.match.POS.test(i)?d(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:d(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=L.test(a)?d(a,b||this.context):null;for(e=0,f=this.length;e<f;e++){g=this[e];while(g){if(l?l.index(g)>-1:d.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b)break}}c=c.length>1?d.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a==="string")return d.inArray(this[0],a?d(a):this.parent().children());return d.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a==="string"?d(a,b):d.makeArray(a),e=d.merge(this.get(),c);return this.pushStack(N(c[0])||N(e[0])?e:d.unique(e))},andSelf:function(){return this.add(this.prevObject)}}),d.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return d.dir(a,"parentNode")},parentsUntil:function(a,b,c){return d.dir(a,"parentNode",c)},next:function(a){return d.nth(a,2,"nextSibling")},prev:function(a){return d.nth(a,2,"previousSibling")},nextAll:function(a){return d.dir(a,"nextSibling")},prevAll:function(a){return d.dir(a,"previousSibling")},nextUntil:function(a,b,c){return d.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return d.dir(a,"previousSibling",c)},siblings:function(a){return d.sibling(a.parentNode.firstChild,a)},children:function(a){return d.sibling(a.firstChild)},contents:function(a){return d.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:d.makeArray(a.childNodes)}},function(a,b){d.fn[a]=function(c,e){var f=d.map(this,b,c),g=K.call(arguments);G.test(a)||(e=c),e&&typeof e==="string"&&(f=d.filter(e,f)),f=this.length>1&&!M[a]?d.unique(f):f,(this.length>1||I.test(e))&&H.test(a)&&(f=f.reverse());return this.pushStack(f,a,g.join(","))}}),d.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?d.find.matchesSelector(b[0],a)?[b[0]]:[]:d.find.matches(a,b)},dir:function(a,c,e){var f=[],g=a[c];while(g&&g.nodeType!==9&&(e===b||g.nodeType!==1||!d(g).is(e)))g.nodeType===1&&f.push(g),g=g[c];return f},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var P=/ jQuery\d+="(?:\d+|null)"/g,Q=/^\s+/,R=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,S=/<([\w:]+)/,T=/<tbody/i,U=/<|&#?\w+;/,V=/<(?:script|object|embed|option|style)/i,W=/checked\s*(?:[^=]|=\s*.checked.)/i,X={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};X.optgroup=X.option,X.tbody=X.tfoot=X.colgroup=X.caption=X.thead,X.th=X.td,d.support.htmlSerialize||(X._default=[1,"div<div>","</div>"]),d.fn.extend({text:function(a){if(d.isFunction(a))return this.each(function(b){var c=d(this);c.text(a.call(this,b,c.text()))});if(typeof a!=="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return d.text(this)},wrapAll:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapAll(a.call(this,b))});if(this[0]){var b=d(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(d.isFunction(a))return this.each(function(b){d(this).wrapInner(a.call(this,b))});return this.each(function(){var b=d(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){d(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){d.nodeName(this,"body")||d(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=d(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,d(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,e;(e=this[c])!=null;c++)if(!a||d.filter(a,[e]).length)!b&&e.nodeType===1&&(d.cleanData(e.getElementsByTagName("*")),d.cleanData([e])),e.parentNode&&e.parentNode.removeChild(e);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&d.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return d.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(P,""):null;if(typeof a!=="string"||V.test(a)||!d.support.leadingWhitespace&&Q.test(a)||X[(S.exec(a)||["",""])[1].toLowerCase()])d.isFunction(a)?this.each(function(b){var c=d(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);else{a=a.replace(R,"<$1></$2>");try{for(var c=0,e=this.length;c<e;c++)this[c].nodeType===1&&(d.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(f){this.empty().append(a)}}return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(d.isFunction(a))return this.each(function(b){var c=d(this),e=c.html();c.replaceWith(a.call(this,b,e))});typeof a!=="string"&&(a=d(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;d(this).remove(),b?d(b).before(a):d(c).append(a)})}return this.pushStack(d(d.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,e){var f,g,h,i,j=a[0],k=[];if(!d.support.checkClone&&arguments.length===3&&typeof j==="string"&&W.test(j))return this.each(function(){d(this).domManip(a,c,e,!0)});if(d.isFunction(j))return this.each(function(f){var g=d(this);a[0]=j.call(this,f,c?g.html():b),g.domManip(a,c,e)});if(this[0]){i=j&&j.parentNode,d.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?f={fragment:i}:f=d.buildFragment(a,this,k),h=f.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&d.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)e.call(c?Y(this[l],g):this[l],f.cacheable||m>1&&l<n?d.clone(h,!0,!0):h)}k.length&&d.each(k,ba)}return this}}),d.buildFragment=function(a,b,e){var f,g,h,i=b&&b[0]?b[0].ownerDocument||b[0]:c;a.length===1&&typeof a[0]==="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!V.test(a[0])&&(d.support.checkClone||!W.test(a[0]))&&(g=!0,h=d.fragments[a[0]],h&&(h!==1&&(f=h))),f||(f=i.createDocumentFragment(),d.clean(a,i,f,e)),g&&(d.fragments[a[0]]=h?f:1);return{fragment:f,cacheable:g}},d.fragments={},d.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){d.fn[a]=function(c){var e=[],f=d(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&f.length===1){f[b](this[0]);return this}for(var h=0,i=f.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();d(f[h])[b](j),e=e.concat(j)}return this.pushStack(e,a,f.selector)}}),d.extend({clone:function(a,b,c){var e=a.cloneNode(!0),f,g,h;if((!d.support.noCloneEvent||!d.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!d.isXMLDoc(a)){$(a,e),f=_(a),g=_(e);for(h=0;f[h];++h)$(f[h],g[h])}if(b){Z(a,e);if(c){f=_(a),g=_(e);for(h=0;f[h];++h)Z(f[h],g[h])}}return e},clean:function(a,b,e,f){b=b||c,typeof b.createElement==="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var g=[];for(var h=0,i;(i=a[h])!=null;h++){typeof i==="number"&&(i+="");if(!i)continue;if(typeof i!=="string"||U.test(i)){if(typeof i==="string"){i=i.replace(R,"<$1></$2>");var j=(S.exec(i)||["",""])[1].toLowerCase(),k=X[j]||X._default,l=k[0],m=b.createElement("div");m.innerHTML=k[1]+i+k[2];while(l--)m=m.lastChild;if(!d.support.tbody){var n=T.test(i),o=j==="table"&&!n?m.firstChild&&m.firstChild.childNodes:k[1]==="<table>"&&!n?m.childNodes:[];for(var p=o.length-1;p>=0;--p)d.nodeName(o[p],"tbody")&&!o[p].childNodes.length&&o[p].parentNode.removeChild(o[p])}!d.support.leadingWhitespace&&Q.test(i)&&m.insertBefore(b.createTextNode(Q.exec(i)[0]),m.firstChild),i=m.childNodes}}else i=b.createTextNode(i);i.nodeType?g.push(i):g=d.merge(g,i)}if(e)for(h=0;g[h];h++)!f||!d.nodeName(g[h],"script")||g[h].type&&g[h].type.toLowerCase()!=="text/javascript"?(g[h].nodeType===1&&g.splice.apply(g,[h+1,0].concat(d.makeArray(g[h].getElementsByTagName("script")))),e.appendChild(g[h])):f.push(g[h].parentNode?g[h].parentNode.removeChild(g[h]):g[h]);return g},cleanData:function(a){var b,c,e=d.cache,f=d.expando,g=d.event.special,h=d.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&d.noData[j.nodeName.toLowerCase()])continue;c=j[d.expando];if(c){b=e[c]&&e[c][f];if(b&&b.events){for(var k in b.events)g[k]?d.event.remove(j,k):d.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[d.expando]:j.removeAttribute&&j.removeAttribute(d.expando),delete e[c]}}}});var bb=/alpha\([^)]*\)/i,bc=/opacity=([^)]*)/,bd=/-([a-z])/ig,be=/([A-Z])/g,bf=/^-?\d+(?:px)?$/i,bg=/^-?\d/,bh={position:"absolute",visibility:"hidden",display:"block"},bi=["Left","Right"],bj=["Top","Bottom"],bk,bl,bm,bn=function(a,b){return b.toUpperCase()};d.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return d.access(this,a,c,!0,function(a,c,e){return e!==b?d.style(a,c,e):d.css(a,c)})},d.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bk(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{zIndex:!0,fontWeight:!0,opacity:!0,zoom:!0,lineHeight:!0},cssProps:{"float":d.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,e,f){if(a&&a.nodeType!==3&&a.nodeType!==8&&a.style){var g,h=d.camelCase(c),i=a.style,j=d.cssHooks[h];c=d.cssProps[h]||h;if(e===b){if(j&&"get"in j&&(g=j.get(a,!1,f))!==b)return g;return i[c]}if(typeof e==="number"&&isNaN(e)||e==null)return;typeof e==="number"&&!d.cssNumber[h]&&(e+="px");if(!j||!("set"in j)||(e=j.set(a,e))!==b)try{i[c]=e}catch(k){}}},css:function(a,c,e){var f,g=d.camelCase(c),h=d.cssHooks[g];c=d.cssProps[g]||g;if(h&&"get"in h&&(f=h.get(a,!0,e))!==b)return f;if(bk)return bk(a,c,g)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]},camelCase:function(a){return a.replace(bd,bn)}}),d.curCSS=d.css,d.each(["height","width"],function(a,b){d.cssHooks[b]={get:function(a,c,e){var f;if(c){a.offsetWidth!==0?f=bo(a,b,e):d.swap(a,bh,function(){f=bo(a,b,e)});if(f<=0){f=bk(a,b,b),f==="0px"&&bm&&(f=bm(a,b,b));if(f!=null)return f===""||f==="auto"?"0px":f}if(f<0||f==null){f=a.style[b];return f===""||f==="auto"?"0px":f}return typeof f==="string"?f:f+"px"}},set:function(a,b){if(!bf.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),d.support.opacity||(d.cssHooks.opacity={get:function(a,b){return bc.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style;c.zoom=1;var e=d.isNaN(b)?"":"alpha(opacity="+b*100+")",f=c.filter||"";c.filter=bb.test(f)?f.replace(bb,e):c.filter+" "+e}}),c.defaultView&&c.defaultView.getComputedStyle&&(bl=function(a,c,e){var f,g,h;e=e.replace(be,"-$1").toLowerCase();if(!(g=a.ownerDocument.defaultView))return b;if(h=g.getComputedStyle(a,null))f=h.getPropertyValue(e),f===""&&!d.contains(a.ownerDocument.documentElement,a)&&(f=d.style(a,e));return f}),c.documentElement.currentStyle&&(bm=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bf.test(d)&&bg.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bk=bl||bm,d.expr&&d.expr.filters&&(d.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!d.support.reliableHiddenOffsets&&(a.style.display||d.css(a,"display"))==="none"},d.expr.filters.visible=function(a){return!d.expr.filters.hidden(a)});var bp=/%20/g,bq=/\[\]$/,br=/\r?\n/g,bs=/#.*$/,bt=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bu=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bv=/(?:^file|^widget|\-extension):$/,bw=/^(?:GET|HEAD)$/,bx=/^\/\//,by=/\?/,bz=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bA=/^(?:select|textarea)/i,bB=/\s+/,bC=/([?&])_=[^&]*/,bD=/(^|\-)([a-z])/g,bE=function(a,b,c){return b+c.toUpperCase()},bF=/^([\w\+\.\-]+:)\/\/([^\/?#:]*)(?::(\d+))?/,bG=d.fn.load,bH={},bI={},bJ,bK;try{bJ=c.location.href}catch(bL){bJ=c.createElement("a"),bJ.href="",bJ=bJ.href}bK=bF.exec(bJ.toLowerCase()),d.fn.extend({load:function(a,c,e){if(typeof a!=="string"&&bG)return bG.apply(this,arguments);if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var g=a.slice(f,a.length);a=a.slice(0,f)}var h="GET";c&&(d.isFunction(c)?(e=c,c=b):typeof c==="object"&&(c=d.param(c,d.ajaxSettings.traditional),h="POST"));var i=this;d.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?d("<div>").append(c.replace(bz,"")).find(g):c)),e&&i.each(e,[c,b,a])}});return this},serialize:function(){return d.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?d.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bA.test(this.nodeName)||bu.test(this.type))}).map(function(a,b){var c=d(this).val();return c==null?null:d.isArray(c)?d.map(c,function(a,c){return{name:b.name,value:a.replace(br,"\r\n")}}):{name:b.name,value:c.replace(br,"\r\n")}}).get()}}),d.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){d.fn[b]=function(a){return this.bind(b,a)}}),d.each(["get","post"],function(a,c){d[c]=function(a,e,f,g){d.isFunction(e)&&(g=g||f,f=e,e=b);return d.ajax({type:c,url:a,data:e,success:f,dataType:g})}}),d.extend({getScript:function(a,c){return d.get(a,b,c,"script")},getJSON:function(a,b,c){return d.get(a,b,c,"json")},ajaxSetup:function(a,b){b?d.extend(!0,a,d.ajaxSettings,b):(b=a,a=d.extend(!0,d.ajaxSettings,b));for(var c in {context:1,url:1})c in b?a[c]=b[c]:c in d.ajaxSettings&&(a[c]=d.ajaxSettings[c]);return a},ajaxSettings:{url:bJ,isLocal:bv.test(bK[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":d.parseJSON,"text xml":d.parseXML}},ajaxPrefilter:bM(bH),ajaxTransport:bM(bI),ajax:function(a,c){function v(a,c,l,n){if(r!==2){r=2,p&&clearTimeout(p),o=b,m=n||"",u.readyState=a?4:0;var q,t,v,w=l?bP(e,u,l):b,x,y;if(a>=200&&a<300||a===304){if(e.ifModified){if(x=u.getResponseHeader("Last-Modified"))d.lastModified[k]=x;if(y=u.getResponseHeader("Etag"))d.etag[k]=y}if(a===304)c="notmodified",q=!0;else try{t=bQ(e,w),c="success",q=!0}catch(z){c="parsererror",v=z}}else{v=c;if(!c||a)c="error",a<0&&(a=0)}u.status=a,u.statusText=c,q?h.resolveWith(f,[t,c,u]):h.rejectWith(f,[u,c,v]),u.statusCode(j),j=b,s&&g.trigger("ajax"+(q?"Success":"Error"),[u,e,q?t:v]),i.resolveWith(f,[u,c]),s&&(g.trigger("ajaxComplete",[u,e]),--d.active||d.event.trigger("ajaxStop"))}}typeof a==="object"&&(c=a,a=b),c=c||{};var e=d.ajaxSetup({},c),f=e.context||e,g=f!==e&&(f.nodeType||f instanceof d)?d(f):d.event,h=d.Deferred(),i=d._Deferred(),j=e.statusCode||{},k,l={},m,n,o,p,q,r=0,s,t,u={readyState:0,setRequestHeader:function(a,b){r||(l[a.toLowerCase().replace(bD,bE)]=b);return this},getAllResponseHeaders:function(){return r===2?m:null},getResponseHeader:function(a){var c;if(r===2){if(!n){n={};while(c=bt.exec(m))n[c[1].toLowerCase()]=c[2]}c=n[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){r||(e.mimeType=a);return this},abort:function(a){a=a||"abort",o&&o.abort(a),v(0,a);return this}};h.promise(u),u.success=u.done,u.error=u.fail,u.complete=i.done,u.statusCode=function(a){if(a){var b;if(r<2)for(b in a)j[b]=[j[b],a[b]];else b=a[u.status],u.then(b,b)}return this},e.url=((a||e.url)+"").replace(bs,"").replace(bx,bK[1]+"//"),e.dataTypes=d.trim(e.dataType||"*").toLowerCase().split(bB),e.crossDomain||(q=bF.exec(e.url.toLowerCase()),e.crossDomain=q&&(q[1]!=bK[1]||q[2]!=bK[2]||(q[3]||(q[1]==="http:"?80:443))!=(bK[3]||(bK[1]==="http:"?80:443)))),e.data&&e.processData&&typeof e.data!=="string"&&(e.data=d.param(e.data,e.traditional)),bN(bH,e,c,u);if(r===2)return!1;s=e.global,e.type=e.type.toUpperCase(),e.hasContent=!bw.test(e.type),s&&d.active++===0&&d.event.trigger("ajaxStart");if(!e.hasContent){e.data&&(e.url+=(by.test(e.url)?"&":"?")+e.data),k=e.url;if(e.cache===!1){var w=d.now(),x=e.url.replace(bC,"$1_="+w);e.url=x+(x===e.url?(by.test(e.url)?"&":"?")+"_="+w:"")}}if(e.data&&e.hasContent&&e.contentType!==!1||c.contentType)l["Content-Type"]=e.contentType;e.ifModified&&(k=k||e.url,d.lastModified[k]&&(l["If-Modified-Since"]=d.lastModified[k]),d.etag[k]&&(l["If-None-Match"]=d.etag[k])),l.Accept=e.dataTypes[0]&&e.accepts[e.dataTypes[0]]?e.accepts[e.dataTypes[0]]+(e.dataTypes[0]!=="*"?", */*; q=0.01":""):e.accepts["*"];for(t in e.headers)u.setRequestHeader(t,e.headers[t]);if(e.beforeSend&&(e.beforeSend.call(f,u,e)===!1||r===2)){u.abort();return!1}for(t in {success:1,error:1,complete:1})u[t](e[t]);o=bN(bI,e,c,u);if(o){u.readyState=1,s&&g.trigger("ajaxSend",[u,e]),e.async&&e.timeout>0&&(p=setTimeout(function(){u.abort("timeout")},e.timeout));try{r=1,o.send(l,v)}catch(y){status<2?v(-1,y):d.error(y)}}else v(-1,"No Transport");return u},param:function(a,c){var e=[],f=function(a,b){b=d.isFunction(b)?b():b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=d.ajaxSettings.traditional);if(d.isArray(a)||a.jquery&&!d.isPlainObject(a))d.each(a,function(){f(this.name,this.value)});else for(var g in a)bO(g,a[g],c,f);return e.join("&").replace(bp,"+")}}),d.extend({active:0,lastModified:{},etag:{}});var bR=d.now(),bS=/(\=)\?(&|$)|()\?\?()/i;d.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return d.expando+"_"+bR++}}),d.ajaxPrefilter("json jsonp",function(b,c,e){var f=typeof b.data==="string";if(b.dataTypes[0]==="jsonp"||c.jsonpCallback||c.jsonp!=null||b.jsonp!==!1&&(bS.test(b.url)||f&&bS.test(b.data))){var g,h=b.jsonpCallback=d.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2",m=function(){a[h]=i,g&&d.isFunction(i)&&a[h](g[0])};b.jsonp!==!1&&(j=j.replace(bS,l),b.url===j&&(f&&(k=k.replace(bS,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},e.then(m,m),b.converters["script json"]=function(){g||d.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),d.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){d.globalEval(a);return a}}}),d.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),d.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var bT=d.now(),bU,bV;d.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&bX()||bY()}:bX,bV=d.ajaxSettings.xhr(),d.support.ajax=!!bV,d.support.cors=bV&&"withCredentials"in bV,bV=b,d.support.ajax&&d.ajaxTransport(function(a){if(!a.crossDomain||d.support.cors){var c;return{send:function(e,f){var g=a.xhr(),h,i;a.username?g.open(a.type,a.url,a.async,a.username,a.password):g.open(a.type,a.url,a.async);if(a.xhrFields)for(i in a.xhrFields)g[i]=a.xhrFields[i];a.mimeType&&g.overrideMimeType&&g.overrideMimeType(a.mimeType),(!a.crossDomain||a.hasContent)&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(i in e)g.setRequestHeader(i,e[i])}catch(j){}g.send(a.hasContent&&a.data||null),c=function(e,i){var j,k,l,m,n;try{if(c&&(i||g.readyState===4)){c=b,h&&(g.onreadystatechange=d.noop,delete bU[h]);if(i)g.readyState!==4&&g.abort();else{j=g.status,l=g.getAllResponseHeaders(),m={},n=g.responseXML,n&&n.documentElement&&(m.xml=n),m.text=g.responseText;try{k=g.statusText}catch(o){k=""}j||!a.isLocal||a.crossDomain?j===1223&&(j=204):j=m.text?200:404}}}catch(p){i||f(-1,p)}m&&f(j,k,m,l)},a.async&&g.readyState!==4?(bU||(bU={},bW()),h=bT++,g.onreadystatechange=bU[h]=c):c()},abort:function(){c&&c(0,1)}}}});var bZ={},b$=/^(?:toggle|show|hide)$/,b_=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,ca,cb=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];d.fn.extend({show:function(a,b,c){var e,f;if(a||a===0)return this.animate(cc("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)e=this[g],f=e.style.display,!d._data(e,"olddisplay")&&f==="none"&&(f=e.style.display=""),f===""&&d.css(e,"display")==="none"&&d._data(e,"olddisplay",cd(e.nodeName));for(g=0;g<h;g++){e=this[g],f=e.style.display;if(f===""||f==="none")e.style.display=d._data(e,"olddisplay")||""}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cc("hide",3),a,b,c);for(var e=0,f=this.length;e<f;e++){var g=d.css(this[e],"display");g!=="none"&&!d._data(this[e],"olddisplay")&&d._data(this[e],"olddisplay",g)}for(e=0;e<f;e++)this[e].style.display="none";return this},_toggle:d.fn.toggle,toggle:function(a,b,c){var e=typeof a==="boolean";d.isFunction(a)&&d.isFunction(b)?this._toggle.apply(this,arguments):a==null||e?this.each(function(){var b=e?a:d(this).is(":hidden");d(this)[b?"show":"hide"]()}):this.animate(cc("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,e){var f=d.speed(b,c,e);if(d.isEmptyObject(a))return this.each(f.complete);return this[f.queue===!1?"each":"queue"](function(){var b=d.extend({},f),c,e=this.nodeType===1,g=e&&d(this).is(":hidden"),h=this;for(c in a){var i=d.camelCase(c);c!==i&&(a[i]=a[c],delete a[c],c=i);if(a[c]==="hide"&&g||a[c]==="show"&&!g)return b.complete.call(this);if(e&&(c==="height"||c==="width")){b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(d.css(this,"display")==="inline"&&d.css(this,"float")==="none")if(d.support.inlineBlockNeedsLayout){var j=cd(this.nodeName);j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)}else this.style.display="inline-block"}d.isArray(a[c])&&((b.specialEasing=b.specialEasing||{})[c]=a[c][1],a[c]=a[c][0])}b.overflow!=null&&(this.style.overflow="hidden"),b.curAnim=d.extend({},a),d.each(a,function(c,e){var f=new d.fx(h,b,c);if(b$.test(e))f[e==="toggle"?g?"show":"hide":e](a);else{var i=b_.exec(e),j=f.cur();if(i){var k=parseFloat(i[2]),l=i[3]||(d.cssNumber[c]?"":"px");l!=="px"&&(d.style(h,c,(k||1)+l),j=(k||1)/f.cur()*j,d.style(h,c,j+l)),i[1]&&(k=(i[1]==="-="?-1:1)*k+j),f.custom(j,k,l)}else f.custom(j,e,"")}});return!0})},stop:function(a,b){var c=d.timers;a&&this.queue([]),this.each(function(){for(var a=c.length-1;a>=0;a--)c[a].elem===this&&(b&&c[a](!0),c.splice(a,1))}),b||this.dequeue();return this}}),d.each({slideDown:cc("show",1),slideUp:cc("hide",1),slideToggle:cc("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){d.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),d.extend({speed:function(a,b,c){var e=a&&typeof a==="object"?d.extend({},a):{complete:c||!c&&b||d.isFunction(a)&&a,duration:a,easing:c&&b||b&&!d.isFunction(b)&&b};e.duration=d.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in d.fx.speeds?d.fx.speeds[e.duration]:d.fx.speeds._default,e.old=e.complete,e.complete=function(){e.queue!==!1&&d(this).dequeue(),d.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig||(b.orig={})}}),d.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(d.fx.step[this.prop]||d.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=d.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function g(a){return e.step(a)}var e=this,f=d.fx;this.startTime=d.now(),this.start=a,this.end=b,this.unit=c||this.unit||(d.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,g.elem=this.elem,g()&&d.timers.push(g)&&!ca&&(ca=setInterval(f.tick,f.interval))},show:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),d(this.elem).show()},hide:function(){this.options.orig[this.prop]=d.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=d.now(),c=!0;if(a||b>=this.options.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),this.options.curAnim[this.prop]=!0;for(var e in this.options.curAnim)this.options.curAnim[e]!==!0&&(c=!1);if(c){if(this.options.overflow!=null&&!d.support.shrinkWrapBlocks){var f=this.elem,g=this.options;d.each(["","X","Y"],function(a,b){f.style["overflow"+b]=g.overflow[a]})}this.options.hide&&d(this.elem).hide();if(this.options.hide||this.options.show)for(var h in this.options.curAnim)d.style(this.elem,h,this.options.orig[h]);this.options.complete.call(this.elem)}return!1}var i=b-this.startTime;this.state=i/this.options.duration;var j=this.options.specialEasing&&this.options.specialEasing[this.prop],k=this.options.easing||(d.easing.swing?"swing":"linear");this.pos=d.easing[j||k](this.state,i,0,1,this.options.duration),this.now=this.start+(this.end-this.start)*this.pos,this.update();return!0}},d.extend(d.fx,{tick:function(){var a=d.timers;for(var b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||d.fx.stop()},interval:13,stop:function(){clearInterval(ca),ca=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){d.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),d.expr&&d.expr.filters&&(d.expr.filters.animated=function(a){return d.grep(d.timers,function(b){return a===b.elem}).length});var ce=/^t(?:able|d|h)$/i,cf=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?d.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,g=f.documentElement;if(!c||!d.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=f.body,i=cg(f),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||d.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||d.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:d.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){d.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return d.offset.bodyOffset(b);d.offset.initialize();var c,e=b.offsetParent,f=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(d.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===e&&(l+=b.offsetTop,m+=b.offsetLeft,d.offset.doesNotAddBorder&&(!d.offset.doesAddBorderForTableAndCells||!ce.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),f=e,e=b.offsetParent),d.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;d.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},d.offset={initialize:function(){var a=c.body,b=c.createElement("div"),e,f,g,h,i=parseFloat(d.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";d.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),e=b.firstChild,f=e.firstChild,h=e.nextSibling.firstChild.firstChild,this.doesNotAddBorder=f.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,f.style.position="fixed",f.style.top="20px",this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15,f.style.position=f.style.top="",e.style.overflow="hidden",e.style.position="relative",this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),a=b=e=f=g=h=null,d.offset.initialize=d.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;d.offset.initialize(),d.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(d.css(a,"marginTop"))||0,c+=parseFloat(d.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var e=d.css(a,"position");e==="static"&&(a.style.position="relative");var f=d(a),g=f.offset(),h=d.css(a,"top"),i=d.css(a,"left"),j=e==="absolute"&&d.inArray("auto",[h,i])>-1,k={},l={},m,n;j&&(l=f.position()),m=j?l.top:parseInt(h,10)||0,n=j?l.left:parseInt(i,10)||0,d.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):f.css(k)}},d.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),e=cf.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(d.css(a,"marginTop"))||0,c.left-=parseFloat(d.css(a,"marginLeft"))||0,e.top+=parseFloat(d.css(b[0],"borderTopWidth"))||0,e.left+=parseFloat(d.css(b[0],"borderLeftWidth"))||0;return{top:c.top-e.top,left:c.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&(!cf.test(a.nodeName)&&d.css(a,"position")==="static"))a=a.offsetParent;return a})}}),d.each(["Left","Top"],function(a,c){var e="scroll"+c;d.fn[e]=function(c){var f=this[0],g;if(!f)return null;if(c!==b)return this.each(function(){g=cg(this),g?g.scrollTo(a?d(g).scrollLeft():c,a?c:d(g).scrollTop()):this[e]=c});g=cg(f);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:d.support.boxModel&&g.document.documentElement[e]||g.document.body[e]:f[e]}}),d.each(["Height","Width"],function(a,c){var e=c.toLowerCase();d.fn["inner"+c]=function(){return this[0]?parseFloat(d.css(this[0],e,"padding")):null},d.fn["outer"+c]=function(a){return this[0]?parseFloat(d.css(this[0],e,a?"margin":"border")):null},d.fn[e]=function(a){var f=this[0];if(!f)return a==null?null:this;if(d.isFunction(a))return this.each(function(b){var c=d(this);c[e](a.call(this,b,c[e]()))});if(d.isWindow(f)){var g=f.document.documentElement["client"+c];return f.document.compatMode==="CSS1Compat"&&g||f.document.body["client"+c]||g}if(f.nodeType===9)return Math.max(f.documentElement["client"+c],f.body["scroll"+c],f.documentElement["scroll"+c],f.body["offset"+c],f.documentElement["offset"+c]);if(a===b){var h=d.css(f,e),i=parseFloat(h);return d.isNaN(i)?h:i}return this.css(e,typeof a==="string"?a:a+"px")}}),a.jQuery=a.$=d})(window);
assets/javascripts/components/list_manager/ListManager.js
walshyb/DoTab
import React, { Component } from 'react'; import CategoryList from '../category_list/CategoryList'; import AddTaskBar from '../add_task_bar/AddTaskBar'; import { connect } from 'react-redux'; import { list_manager_actions } from '../../redux/list_manager/list_manager' import { util } from '../../utils'; export class ListManager extends Component { render() { return ( <div> <h1> { util.getCurrentDate() } </h1> <CategoryList categories={this.props.categories} archiveTask={this.props.archiveTask} removeCategory={this.props.removeCategory} renameCategory={this.props.renameCategory} /> <AddTaskBar addCategory={this.props.addCategory} addTask={this.props.addTask} categories={this.props.categories} /> </div> ); }; } export default connect( // map state to props function( state ) { return { categories: state.list_manager.categories, }; }, // map dispatch actions to props list_manager_actions )( ListManager );
packages/material-ui-icons/src/VoicemailSharp.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M18.5 6C15.46 6 13 8.46 13 11.5c0 1.33.47 2.55 1.26 3.5H9.74c.79-.95 1.26-2.17 1.26-3.5C11 8.46 8.54 6 5.5 6S0 8.46 0 11.5 2.46 17 5.5 17h13c3.04 0 5.5-2.46 5.5-5.5S21.54 6 18.5 6zm-13 9C3.57 15 2 13.43 2 11.5S3.57 8 5.5 8 9 9.57 9 11.5 7.43 15 5.5 15zm13 0c-1.93 0-3.5-1.57-3.5-3.5S16.57 8 18.5 8 22 9.57 22 11.5 20.43 15 18.5 15z" /></g></React.Fragment> , 'VoicemailSharp');