path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
packages/react-scripts/fixtures/kitchensink/src/features/webpack/NoExtInclusion.js
Place1/create-react-app-typescript
/** * 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. */ import React from 'react'; import aFileWithoutExt from './assets/aFileWithoutExt'; const text = aFileWithoutExt.includes('base64') ? atob(aFileWithoutExt.split('base64,')[1]).trim() : aFileWithoutExt; export default () => ( <a id="feature-no-ext-inclusion" href={text}>aFileWithoutExt</a> );
packages/material-ui-icons/src/RecordVoiceOverTwoTone.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g opacity=".3"><circle cx="9" cy="9" r="2" /><path d="M9 17c-2.69 0-5.77 1.28-6 2h12c-.2-.71-3.3-2-6-2z" /></g><path d="M9 13c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0-6c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zM9 15c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4zm-6 4c.22-.72 3.31-2 6-2 2.7 0 5.8 1.29 6 2H3zM16.76 5.36l-1.68 1.69c.84 1.18.84 2.71 0 3.89l1.68 1.69c2.02-2.02 2.02-5.07 0-7.27z" /><path d="M20.07 2l-1.63 1.63c2.77 3.02 2.77 7.56 0 10.74L20.07 16c3.9-3.89 3.91-9.95 0-14z" /></React.Fragment> , 'RecordVoiceOverTwoTone');
packages/mineral-ui-icons/src/IconFiberPin.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconFiberPin(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <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"/> </g> </Icon> ); } IconFiberPin.displayName = 'IconFiberPin'; IconFiberPin.category = 'av';
ajax/libs/video.js/4.10.2/video.dev.js
Ryuno-Ki/cdnjs
/** * @fileoverview Main function src. */ // HTML5 Shiv. Must be in <head> to support older browsers. document.createElement('video'); document.createElement('audio'); document.createElement('track'); /** * Doubles as the main function for users to create a player instance and also * the main library object. * * **ALIASES** videojs, _V_ (deprecated) * * The `vjs` function can be used to initialize or retrieve a player. * * var myPlayer = vjs('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 {vjs.Player} A player instance * @namespace */ var vjs = function(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 (vjs.players[id]) { return vjs.players[id]; // Otherwise get element for ID } else { tag = vjs.el(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 vjs.Player(tag, options, ready); }; // Extended name, also available externally, window.videojs var videojs = window['videojs'] = vjs; // CDN Version. Used to target right flash swf. vjs.CDN_VERSION = '4.10'; vjs.ACCESS_PROTOCOL = ('https:' == document.location.protocol ? 'https://' : 'http://'); /** * Global Player instance options, surfaced from vjs.Player.prototype.options_ * vjs.options = vjs.Player.prototype.options_ * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} */ vjs.options = { // Default order of fallback technology 'techOrder': ['html5','flash'], // techOrder: ['flash','html5'], 'html5': {}, 'flash': {}, // Default of web browser is 300x150. Should rely on source width/height. 'width': 300, 'height': 150, // defaultVolume: 0.85, 'defaultVolume': 0.00, // The freakin seaguls are driving me crazy! // default playback rates 'playbackRates': [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // default inactivity timeout 'inactivityTimeout': 2000, // Included control sets 'children': { 'mediaLoader': {}, 'posterImage': {}, 'textTrackDisplay': {}, 'loadingSpinner': {}, 'bigPlayButton': {}, 'controlBar': {}, 'errorDisplay': {} }, 'language': document.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.' }; // Set CDN Version of swf // The added (+) blocks the replace from changing this 4.10 string if (vjs.CDN_VERSION !== 'GENERATED'+'_CDN_VSN') { videojs.options['flash']['swf'] = vjs.ACCESS_PROTOCOL + 'vjs.zencdn.net/'+vjs.CDN_VERSION+'/video-js.swf'; } /** * Utility function for adding languages to the default options. Useful for * amending multiple language support at runtime. * * Example: vjs.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 global languages dictionary object */ vjs.addLanguage = function(code, data){ if(vjs.options['languages'][code] !== undefined) { vjs.options['languages'][code] = vjs.util.mergeOptions(vjs.options['languages'][code], data); } else { vjs.options['languages'][code] = data; } return vjs.options['languages']; }; /** * Global player list * @type {Object} */ vjs.players = {}; /*! * 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([], 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; } /** * Core Object/Class for objects that use inheritance + contstructors * * To create a class that can be subclassed itself, extend the CoreObject class. * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * The constructor can be defined through the init property of an object argument. * * var Animal = CoreObject.extend({ * init: function(name, sound){ * this.name = name; * } * }); * * Other methods and properties can be added the same way, or directly to the * prototype. * * var Animal = CoreObject.extend({ * init: function(name){ * this.name = name; * }, * getName: function(){ * return this.name; * }, * sound: '...' * }); * * Animal.prototype.makeSound = function(){ * alert(this.sound); * }; * * To create an instance of a class, use the create method. * * var fluffy = Animal.create('Fluffy'); * fluffy.getName(); // -> Fluffy * * Methods and properties can be overridden in subclasses. * * var Horse = Animal.extend({ * sound: 'Neighhhhh!' * }); * * var horsey = Horse.create('Horsey'); * horsey.getName(); // -> Horsey * horsey.makeSound(); // -> Alert: Neighhhhh! * * @class * @constructor */ vjs.CoreObject = vjs['CoreObject'] = function(){}; // Manually exporting vjs['CoreObject'] here for Closure Compiler // because of the use of the extend/create class methods // If we didn't do this, those functions would get flattend to something like // `a = ...` and `this.prototype` would refer to the global object instead of // CoreObject /** * Create a new object that inherits from this Object * * var Animal = CoreObject.extend(); * var Horse = Animal.extend(); * * @param {Object} props Functions and properties to be applied to the * new object's prototype * @return {vjs.CoreObject} An object that inherits from CoreObject * @this {*} */ vjs.CoreObject.extend = function(props){ var init, subObj; props = props || {}; // 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 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 constuctor because the `this` in `this.init` // would still refer to the Child and cause an inifinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, argumnents);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. subObj = function(){ init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = vjs.obj.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 = vjs.CoreObject.extend; // Make a function for creating instances subObj.create = vjs.CoreObject.create; // Extend subObj's prototype with functions and other properties from props for (var name in props) { if (props.hasOwnProperty(name)) { subObj.prototype[name] = props[name]; } } return subObj; }; /** * Create a new instace of this Object class * * var myAnimal = Animal.create(); * * @return {vjs.CoreObject} An instance of a CoreObject subclass * @this {*} */ vjs.CoreObject.create = function(){ // Create a new object that inherits from this object's prototype var inst = vjs.obj.create(this.prototype); // Apply this constructor function to the new object this.apply(inst, arguments); // Return the new object return inst; }; /** * @fileoverview 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. */ /** * 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. * @private */ vjs.on = function(elem, type, fn){ if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.on, elem, type, fn); } var data = vjs.getData(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 = vjs.guid++; data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event){ if (data.disabled) return; event = vjs.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); } } } }; } 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. * @private */ vjs.off = function(elem, type, fn) { // Don't want to add a cache object through getData if not needed if (!vjs.hasData(elem)) return; var data = vjs.getData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.off, elem, type, fn); } // Utility function var removeType = function(t){ data.handlers[t] = []; vjs.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); } } } vjs.cleanUpEvents(elem, type); }; /** * 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 */ vjs.cleanUpEvents = function(elem, type) { var data = vjs.getData(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 (vjs.isEmpty(data.handlers)) { delete data.handlers; delete data.dispatcher; delete data.disabled; // data.handlers = null; // data.dispatcher = null; // data.disabled = null; } // Finally remove the expando if there is no data left if (vjs.isEmpty(data)) { vjs.removeData(elem); } }; /** * Fix a native event to have standard property values * @param {Object} event Event object to fix * @return {Object} * @private */ vjs.fixEvent = function(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 || window.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 if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') { // 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 || document; } // Handle which other element the event is related to 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; event.isDefaultPrevented = returnTrue; event.defaultPrevented = true; }; event.isDefaultPrevented = returnFalse; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.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 = document.documentElement, body = document.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; }; /** * 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 * @private */ vjs.trigger = function(elem, event) { // 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 hasData first. var elemData = (vjs.hasData(elem)) ? vjs.getData(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 = vjs.fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event); } // 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 !== false) { vjs.trigger(parent, event); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = vjs.getData(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; /* Original version of js ninja events wasn't complete. * We've since updated to the latest version, but keeping this around * for now just in case. */ // // Added in attion to book. Book code was broke. // event = typeof event === 'object' ? // event[vjs.expando] ? // event : // new vjs.Event(type, event) : // new vjs.Event(type); // event.type = type; // if (handler) { // handler.call(elem, event); // } // // Clean up the event in case it is being reused // event.result = undefined; // event.target = elem; }; /** * Trigger a listener only once for an event * @param {Element|Object} elem Element or object to * @param {String|Array} type * @param {Function} fn * @private */ vjs.one = function(elem, type, fn) { if (vjs.obj.isArray(type)) { return _handleMultipleEvents(vjs.one, elem, type, fn); } var func = function(){ vjs.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 || vjs.guid++; vjs.on(elem, type, func); }; /** * 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(fn, elem, type, callback) { vjs.arr.forEach(type, function(type) { fn(elem, type, callback); //Call the event method for each one of the types }); } var hasOwnProp = Object.prototype.hasOwnProperty; /** * 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} * @private */ vjs.createEl = function(tagName, properties){ var el; tagName = tagName || 'div'; properties = properties || {}; el = document.createElement(tagName); vjs.obj.each(properties, function(propName, val){ // 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') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; }; /** * Uppercase the first letter of a string * @param {String} string String to be uppercased * @return {String} * @private */ vjs.capitalize = function(string){ return string.charAt(0).toUpperCase() + string.slice(1); }; /** * Object functions container * @type {Object} * @private */ vjs.obj = {}; /** * Object.create shim for prototypal inheritance * * https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create * * @function * @param {Object} obj Object to use as prototype * @private */ vjs.obj.create = Object.create || function(obj){ //Create a new function called 'F' which is just an empty object. function F() {} //the prototype of the 'F' function should point to the //parameter of the anonymous function. F.prototype = obj; //create a new constructor function based off of the 'F' function. return new F(); }; /** * Loop through each property in an object and call a function * whose arguments are (key,value) * @param {Object} obj Object of properties * @param {Function} fn Function to be called on each property. * @this {*} * @private */ vjs.obj.each = function(obj, fn, context){ for (var key in obj) { if (hasOwnProp.call(obj, key)) { fn.call(context || this, key, obj[key]); } } }; /** * Merge two objects together and return the original. * @param {Object} obj1 * @param {Object} obj2 * @return {Object} * @private */ vjs.obj.merge = function(obj1, obj2){ if (!obj2) { return obj1; } for (var key in obj2){ if (hasOwnProp.call(obj2, key)) { obj1[key] = obj2[key]; } } return obj1; }; /** * Merge two objects, and merge any properties that are objects * instead of just overwriting one. Uses to merge options hashes * where deeper default settings are important. * @param {Object} obj1 Object to override * @param {Object} obj2 Overriding object * @return {Object} New object. Obj1 and Obj2 will be untouched. * @private */ vjs.obj.deepMerge = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not ovewriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (hasOwnProp.call(obj2, key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.obj.deepMerge(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; }; /** * Make a copy of the supplied object * @param {Object} obj Object to copy * @return {Object} Copy of object * @private */ vjs.obj.copy = function(obj){ return vjs.obj.merge({}, obj); }; /** * Check if an object is plain, and not a dom node or any object sub-instance * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isPlain = function(obj){ return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; }; /** * Check if an object is Array * Since instanceof Array will not work on arrays created in another frame we need to use Array.isArray, but since IE8 does not support Array.isArray we need this shim * @param {Object} obj Object to check * @return {Boolean} True if plain, false otherwise * @private */ vjs.obj.isArray = Array.isArray || function(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; }; /** * Check to see whether the input is NaN or not. * NaN is the only JavaScript construct that isn't equal to itself * @param {Number} num Number to check * @return {Boolean} True if NaN, false otherwise * @private */ vjs.isNaN = function(num) { return num !== num; }; /** * 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 */ vjs.bind = function(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = vjs.guid++; } // Create the new function that changes the context var ret = function() { 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; }; /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listneres are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * @type {Object} * @private */ vjs.cache = {}; /** * Unique ID for an element or function * @type {Number} * @private */ vjs.guid = 1; /** * Unique attribute name to store an element's guid in * @type {String} * @constant * @private */ vjs.expando = '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} * @private */ vjs.getData = function(el){ var id = el[vjs.expando]; if (!id) { id = el[vjs.expando] = vjs.guid++; vjs.cache[id] = {}; } return vjs.cache[id]; }; /** * Returns the cache object where data for an element is stored * @param {Element} el Element to store data for. * @return {Object} * @private */ vjs.hasData = function(el){ var id = el[vjs.expando]; return !(!id || vjs.isEmpty(vjs.cache[id])); }; /** * Delete data for the element from the cache and the guid attr from getElementById * @param {Element} el Remove data for an element * @private */ vjs.removeData = function(el){ var id = el[vjs.expando]; if (!id) { return; } // Remove all stored data // Changed to = null // http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/ // vjs.cache[id] = null; delete vjs.cache[id]; // Remove the expando property from the DOM node try { delete el[vjs.expando]; } catch(e) { if (el.removeAttribute) { el.removeAttribute(vjs.expando); } else { // IE doesn't appear to support removeAttribute on the document element el[vjs.expando] = null; } } }; /** * Check if an object is empty * @param {Object} obj The object to check for emptiness * @return {Boolean} * @private */ vjs.isEmpty = function(obj) { for (var prop in obj) { // Inlude null properties as empty. if (obj[prop] !== null) { return false; } } return true; }; /** * Check if an element has a CSS class * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @private */ vjs.hasClass = function(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 * @private */ vjs.addClass = function(element, classToAdd){ if (!vjs.hasClass(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} classToAdd Classname to remove * @private */ vjs.removeClass = function(element, classToRemove){ var classNames, i; if (!vjs.hasClass(element, classToRemove)) {return;} classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i,1); } } element.className = classNames.join(' '); }; /** * Element for testing browser HTML5 video capabilities * @type {Element} * @constant * @private */ vjs.TEST_VID = vjs.createEl('video'); /** * Useragent for browser testing. * @type {String} * @constant * @private */ vjs.USER_AGENT = navigator.userAgent; /** * Device is an iPhone * @type {Boolean} * @constant * @private */ vjs.IS_IPHONE = (/iPhone/i).test(vjs.USER_AGENT); vjs.IS_IPAD = (/iPad/i).test(vjs.USER_AGENT); vjs.IS_IPOD = (/iPod/i).test(vjs.USER_AGENT); vjs.IS_IOS = vjs.IS_IPHONE || vjs.IS_IPAD || vjs.IS_IPOD; vjs.IOS_VERSION = (function(){ var match = vjs.USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); vjs.IS_ANDROID = (/Android/i).test(vjs.USER_AGENT); vjs.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 = vjs.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; } })(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser vjs.IS_OLD_ANDROID = vjs.IS_ANDROID && (/webkit/i).test(vjs.USER_AGENT) && vjs.ANDROID_VERSION < 2.3; vjs.IS_FIREFOX = (/Firefox/i).test(vjs.USER_AGENT); vjs.IS_CHROME = (/Chrome/i).test(vjs.USER_AGENT); vjs.TOUCH_ENABLED = !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch); vjs.BACKGROUND_SIZE_SUPPORTED = 'backgroundSize' in vjs.TEST_VID.style; /** * Apply attributes to an HTML element. * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private */ vjs.setElementAttributes = function(el, attributes){ vjs.obj.each(attributes, function(attrName, attrValue) { 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 * Attributs 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 */ vjs.getElementAttributes = function(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; }; /** * Get the computed style value for an element * From http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ * @param {Element} el Element to get style value for * @param {String} strCssRule Style name * @return {String} Style value * @private */ vjs.getComputedDimension = function(el, strCssRule){ var strValue = ''; if(document.defaultView && document.defaultView.getComputedStyle){ strValue = document.defaultView.getComputedStyle(el, '').getPropertyValue(strCssRule); } else if(el.currentStyle){ // IE8 Width/Height support strValue = el['client'+strCssRule.substr(0,1).toUpperCase() + strCssRule.substr(1)] + 'px'; } return strValue; }; /** * Insert an element as the first child node of another * @param {Element} child Element to insert * @param {[type]} parent Element to insert child into * @private */ vjs.insertFirst = function(child, parent){ if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } }; /** * Object to hold browser support information * @type {Object} * @private */ vjs.browser = {}; /** * 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 * @private */ vjs.el = function(id){ if (id.indexOf('#') === 0) { id = id.slice(1); } return document.getElementById(id); }; /** * 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 */ vjs.formatTime = function(seconds, guide) { // Default to using seconds as guide guide = guide || seconds; var s = Math.floor(seconds % 60), m = Math.floor(seconds / 60 % 60), h = Math.floor(seconds / 3600), gm = Math.floor(guide / 60 % 60), 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; }; // Attempt to block the ability to select text while dragging controls vjs.blockTextSelection = function(){ document.body.focus(); document.onselectstart = function () { return false; }; }; // Turn off text selection blocking vjs.unblockTextSelection = function(){ document.onselectstart = function () { return true; }; }; /** * Trim whitespace from the ends of a string. * @param {String} string String to trim * @return {String} Trimmed string * @private */ vjs.trim = function(str){ return (str+'').replace(/^\s+|\s+$/g, ''); }; /** * Should round off a number to a decimal place * @param {Number} num Number to round * @param {Number} dec Number of decimal places to round to * @return {Number} Rounded number * @private */ vjs.round = function(num, dec) { if (!dec) { dec = 0; } return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); }; /** * 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 */ vjs.createTimeRange = function(start, end){ return { length: 1, start: function() { return start; }, end: function() { return end; } }; }; /** * Simple http request for retrieving external files (e.g. text tracks) * @param {String} url URL of resource * @param {Function} onSuccess Success callback * @param {Function=} onError Error callback * @param {Boolean=} withCredentials Flag which allow credentials * @private */ vjs.get = function(url, onSuccess, onError, withCredentials){ var fileUrl, request, urlInfo, winLoc, crossOrigin; onError = onError || function(){}; if (typeof XMLHttpRequest === 'undefined') { // Shim XMLHttpRequest for older IEs window.XMLHttpRequest = function () { try { return new window.ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new window.ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } request = new XMLHttpRequest(); urlInfo = vjs.parseUrl(url); winLoc = window.location; // check if url is for another domain/origin // ie8 doesn't know location.origin, so we won't rely on it here crossOrigin = (urlInfo.protocol + urlInfo.host) !== (winLoc.protocol + winLoc.host); // Use XDomainRequest 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 && window.XDomainRequest && !('withCredentials' in request)) { request = new window.XDomainRequest(); request.onload = function() { onSuccess(request.responseText); }; request.onerror = onError; // 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 = onError; // XMLHTTPRequest } else { fileUrl = (urlInfo.protocol == 'file:' || winLoc.protocol == 'file:'); request.onreadystatechange = function() { if (request.readyState === 4) { if (request.status === 200 || fileUrl && request.status === 0) { onSuccess(request.responseText); } else { onError(request.responseText); } } }; } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open('GET', url, true); // withCredentials only supported by XMLHttpRequest2 if(withCredentials) { request.withCredentials = true; } } catch(e) { onError(e); return; } // send the request try { request.send(); } catch(e) { onError(e); } }; /** * Add to local storage (may removeable) * @private */ vjs.setLocalStorage = function(key, value){ try { // IE was throwing errors referencing the var anywhere without this var localStorage = window.localStorage || false; if (!localStorage) { return; } localStorage[key] = value; } catch(e) { if (e.code == 22 || e.code == 1014) { // Webkit == 22 / Firefox == 1014 vjs.log('LocalStorage Full (VideoJS)', e); } else { if (e.code == 18) { vjs.log('LocalStorage not allowed (VideoJS)', e); } else { vjs.log('LocalStorage Error (VideoJS)', e); } } } }; /** * Get abosolute 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 */ vjs.getAbsoluteURL = function(url){ // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. url = vjs.createEl('div', { innerHTML: '<a href="'+url+'">x</a>' }).firstChild.href; } return url; }; /** * Resolve and parse the elements of a URL * @param {String} url The url to parse * @return {Object} An object of url details */ vjs.parseUrl = function(url) { var div, a, addToBody, props, details; props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL a = vjs.createEl('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 addToBody = (a.host === '' && a.protocol !== 'file:'); if (addToBody) { div = vjs.createEl('div'); div.innerHTML = '<a href="'+url+'"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); document.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 details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } if (addToBody) { document.body.removeChild(div); } return details; }; /** * Log messags to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {[type]} args The args to be passed to the log * @private */ function _logType(type, args){ var argsArray, noop, console; // convert args to an array to get array functions argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in vjs.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 noop = function(){}; console = window['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 vjs.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(' ')); } } /** * Log plain debug messages */ vjs.log = function(){ _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ vjs.log.history = []; /** * Log error messages */ vjs.log.error = function(){ _logType('error', arguments); }; /** * Log warning messages */ vjs.log.warn = function(){ _logType('warn', arguments); }; // Offset Left // getBoundingClientRect technique from John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ vjs.findPosition = function(el) { var box, docEl, body, clientLeft, scrollLeft, left, clientTop, scrollTop, top; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } docEl = document.documentElement; body = document.body; clientLeft = docEl.clientLeft || body.clientLeft || 0; scrollLeft = window.pageXOffset || body.scrollLeft; left = box.left + scrollLeft - clientLeft; clientTop = docEl.clientTop || body.clientTop || 0; scrollTop = window.pageYOffset || body.scrollTop; top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: vjs.round(left), top: vjs.round(top) }; }; /** * Array functions container * @type {Object} * @private */ vjs.arr = {}; /* * Loops through an array and runs a function for each item inside it. * @param {Array} array The array * @param {Function} callback The function to be run for each item * @param {*} thisArg The `this` binding of callback * @returns {Array} The array * @private */ vjs.arr.forEach = function(array, callback, thisArg) { if (vjs.obj.isArray(array) && callback instanceof Function) { for (var i = 0, len = array.length; i < len; ++i) { callback.call(thisArg || vjs, array[i], i, array); } } return array; }; /** * Utility functions namespace * @namespace * @type {Object} */ vjs.util = {}; /** * Merge two options objects, recursively merging any plain object properties as * well. Previously `deepMerge` * * @param {Object} obj1 Object to override values in * @param {Object} obj2 Overriding object * @return {Object} New object -- obj1 and obj2 will be untouched */ vjs.util.mergeOptions = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (obj2.hasOwnProperty(key)) { val1 = obj1[key]; val2 = obj2[key]; // Check if both properties are pure objects and do a deep merge if so if (vjs.obj.isPlain(val1) && vjs.obj.isPlain(val2)) { obj1[key] = vjs.util.mergeOptions(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; };/** * @fileoverview Player Component - Base class for all UI objects * */ /** * 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. * * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * * Components are also event emitters. * * button.on('click', function(){ * console.log('Button Clicked!'); * }); * * button.trigger('customevent'); * * @param {Object} player Main Player * @param {Object=} options * @class * @constructor * @extends vjs.CoreObject */ vjs.Component = vjs.CoreObject.extend({ /** * the constructor function for the class * * @constructor */ init: function(player, options, ready){ this.player_ = player; // Make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // Updated options with supplied options options = 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 this.id_ = ((player.id && player.id()) || 'no_player') + '_component_' + vjs.guid++; } this.name_ = options['name'] || null; // Create element if one wasn't provided in options this.el_ = options['el'] || this.createEl(); this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options 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 */ vjs.Component.prototype.dispose = function(){ 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_); } vjs.removeData(this.el_); this.el_ = null; }; /** * Reference to main player instance * * @type {vjs.Player} * @private */ vjs.Component.prototype.player_ = true; /** * Return the component's player * * @return {vjs.Player} */ vjs.Component.prototype.player = function(){ return this.player_; }; /** * The component's options object * * @type {Object} * @private */ vjs.Component.prototype.options_; /** * Deep merge of options objects * * Whenever a property is an object on both options objects * the two properties will be merged using vjs.obj.deepMerge. * * 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. * * 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 * * { * 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 */ vjs.Component.prototype.options = function(obj){ if (obj === undefined) return this.options_; return this.options_ = vjs.util.mergeOptions(this.options_, obj); }; /** * The DOM element for the component * * @type {Element} * @private */ vjs.Component.prototype.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} */ vjs.Component.prototype.createEl = function(tagName, attributes){ return vjs.createEl(tagName, attributes); }; vjs.Component.prototype.localize = function(string){ var lang = this.player_.language(), languages = this.player_.languages(); if (languages && languages[lang] && languages[lang][string]) { return languages[lang][string]; } return string; }; /** * Get the component's DOM element * * var domEl = myComponent.el(); * * @return {Element} */ vjs.Component.prototype.el = function(){ return this.el_; }; /** * An optional element where, if defined, children will be inserted instead of * directly in `el_` * * @type {Element} * @private */ vjs.Component.prototype.contentEl_; /** * Return the component's DOM element for embedding content. * Will either be el_ or a new element defined in createEl. * * @return {Element} */ vjs.Component.prototype.contentEl = function(){ return this.contentEl_ || this.el_; }; /** * The ID for the component * * @type {String} * @private */ vjs.Component.prototype.id_; /** * Get the component's ID * * var id = myComponent.id(); * * @return {String} */ vjs.Component.prototype.id = function(){ return this.id_; }; /** * The name for the component. Often used to reference the component. * * @type {String} * @private */ vjs.Component.prototype.name_; /** * Get the component's name. The name is often used to reference the component. * * var name = myComponent.name(); * * @return {String} */ vjs.Component.prototype.name = function(){ return this.name_; }; /** * Array of child components * * @type {Array} * @private */ vjs.Component.prototype.children_; /** * Get an array of all child components * * var kids = myComponent.children(); * * @return {Array} The children */ vjs.Component.prototype.children = function(){ return this.children_; }; /** * Object of child components by ID * * @type {Object} * @private */ vjs.Component.prototype.childIndex_; /** * Returns a child component with the provided ID * * @return {vjs.Component} */ vjs.Component.prototype.getChildById = function(id){ return this.childIndex_[id]; }; /** * Object of child components by name * * @type {Object} * @private */ vjs.Component.prototype.childNameIndex_; /** * Returns a child component with the provided name * * @return {vjs.Component} */ vjs.Component.prototype.getChild = function(name){ return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * * myComponent.el(); * // -> <div class='my-component'></div> * myComonent.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 * * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * * @param {String|vjs.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 {vjs.Component} The child component (created by this process if a string was used) * @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility} */ vjs.Component.prototype.addChild = function(child, options){ var component, componentClass, componentName; // If child is a string, create new component with options if (typeof child === 'string') { componentName = child; // Make sure options is at least an empty object to protect against errors options = options || {}; // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) componentClass = options['componentClass'] || vjs.capitalize(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 // Closure Compiler throws an 'incomplete alias' warning if we use the vjs variable directly. // Every class should be exported, so this should never be a problem here. component = new window['videojs'][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 {vjs.Component} component Component to remove */ vjs.Component.prototype.removeChild = function(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 * * // 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 * 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). * * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * */ vjs.Component.prototype.initChildren = function(){ var parent, parentOptions, children, child, name, opts, handleAdd; parent = this; parentOptions = parent.options(); children = parentOptions['children']; if (children) { handleAdd = function(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. vjs.options['children']['posterImage'] = false if (opts === false) return; // 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 parent[name] = parent.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (vjs.obj.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; if (typeof child == 'string') { // ['myComponent'] name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] name = child.name; opts = child; } handleAdd(name, opts); } } else { vjs.obj.each(children, handleAdd); } } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name */ vjs.Component.prototype.buildCSSClass = function(){ // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /* Events ============================================================================= */ /** * Add an event listener to this component's element * * 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. * * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * * The benefit of using this over `vjs.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is diposed. * 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 `vjs.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|vjs.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 {vjs.Component} self */ vjs.Component.prototype.on = function(first, second, third){ var target, type, fn, removeOnDispose, cleanRemover, thisComponent; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.on(this.el_, first, vjs.bind(this, second)); // Targeting another component or element } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; // When this component is disposed, remove the listener from the other component removeOnDispose = function(){ thisComponent.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; this.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. cleanRemover = function(){ thisComponent.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 vjs.on(target, type, fn); vjs.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof vjs.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 * * 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. * * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * * @param {String=|vjs.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 {vjs.Component} */ vjs.Component.prototype.off = function(first, second, third){ var target, otherComponent, type, fn, otherEl; if (!first || typeof first === 'string' || vjs.obj.isArray(first)) { vjs.off(this.el_, first, second); } else { target = first; type = second; // Ensure there's at least a guid, even if the function hasn't been used fn = vjs.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 vjs.off(target, type, fn); // Remove the listener for cleaning the dispose listener vjs.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 * * myComponent.one('eventName', myFunc); * * Alternatively you can add a listener to another element or component * that will be triggered only once. * * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * * @param {String|vjs.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 {vjs.Component} */ vjs.Component.prototype.one = function(first, second, third) { var target, type, fn, thisComponent, newFunc; if (typeof first === 'string' || vjs.obj.isArray(first)) { vjs.one(this.el_, first, vjs.bind(this, second)); } else { target = first; type = second; fn = vjs.bind(this, third); thisComponent = this; newFunc = function(){ thisComponent.off(target, type, newFunc); fn.apply(this, arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; this.on(target, type, newFunc); } return this; }; /** * Trigger an event on an element * * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @return {vjs.Component} self */ vjs.Component.prototype.trigger = function(event){ vjs.trigger(this.el_, event); return this; }; /* Ready ================================================================================ */ /** * Is the component loaded * This can mean different things depending on the component. * * @private * @type {Boolean} */ vjs.Component.prototype.isReady_; /** * Trigger ready as soon as initialization is finished * * Allows for delaying ready. Override on a sub class prototype. * If you set this.isReadyOnInitFinish_ it will affect all components. * Specially used when waiting for the Flash player to asynchrnously load. * * @type {Boolean} * @private */ vjs.Component.prototype.isReadyOnInitFinish_ = true; /** * List of ready listeners * * @type {Array} * @private */ vjs.Component.prototype.readyQueue_; /** * Bind a listener to the component's ready state * * Different from event listeners in that if the ready event has already happend * it will trigger the function immediately. * * @param {Function} fn Ready listener * @return {vjs.Component} */ vjs.Component.prototype.ready = function(fn){ if (fn) { if (this.isReady_) { fn.call(this); } else { if (this.readyQueue_ === undefined) { this.readyQueue_ = []; } this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {vjs.Component} */ vjs.Component.prototype.triggerReady = function(){ this.isReady_ = true; var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { for (var i = 0, j = readyQueue.length; i < j; i++) { readyQueue[i].call(this); } // Reset Ready Queue this.readyQueue_ = []; // Allow for using event listeners also, in case you want to do something everytime a source is ready. this.trigger('ready'); } }; /* Display ============================================================================= */ /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {vjs.Component} */ vjs.Component.prototype.hasClass = function(classToCheck){ return vjs.hasClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {vjs.Component} */ vjs.Component.prototype.addClass = function(classToAdd){ vjs.addClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {vjs.Component} */ vjs.Component.prototype.removeClass = function(classToRemove){ vjs.removeClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {vjs.Component} */ vjs.Component.prototype.show = function(){ this.el_.style.display = 'block'; return this; }; /** * Hide the component element if currently showing * * @return {vjs.Component} */ vjs.Component.prototype.hide = function(){ this.el_.style.display = 'none'; return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.lockShowing = function(){ this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {vjs.Component} * @private */ vjs.Component.prototype.unlockShowing = function(){ this.removeClass('vjs-lock-showing'); return this; }; /** * Disable component by making it unshowable * * Currently private because we're movign towards more css-based states. * @private */ vjs.Component.prototype.disable = function(){ this.hide(); this.show = function(){}; }; /** * 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 {vjs.Component} This component, when setting the width * @return {Number|String} The width, when getting */ vjs.Component.prototype.width = function(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 {vjs.Component} This component, when setting the height * @return {Number|String} The height, when getting */ vjs.Component.prototype.height = function(num, skipListeners){ return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width * @param {Number|String} height * @return {vjs.Component} The component */ vjs.Component.prototype.dimensions = function(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 {vjs.Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private */ vjs.Component.prototype.dimension = function(widthOrHeight, num, skipListeners){ if (num !== undefined) { if (num === null || vjs.isNaN(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 } else { return parseInt(this.el_['offset'+vjs.capitalize(widthOrHeight)], 10); // ComputedStyle version. // Only difference is if the element is hidden it will return // the percent value (e.g. '100%'') // instead of zero like offsetWidth returns. // var val = vjs.getComputedStyleValue(this.el_, widthOrHeight); // var pxIndex = val.indexOf('px'); // if (pxIndex !== -1) { // return val.slice(0, pxIndex); // } else { // return val; // } } }; /** * Fired when the width and/or height of the component changes * @event resize */ vjs.Component.prototype.onResize; /** * Emit 'tap' events when touch events are supported * * This is used to support toggling the controls through a tap on the video. * * We're requireing them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * @private */ vjs.Component.prototype.emitTapEvents = function(){ var touchStart, firstTouch, touchTime, couldBeTap, noTap, xdiff, ydiff, touchDistance, tapMovementThreshold; // Track the start time so we can determine how long the touch lasted touchStart = 0; firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap tapMovementThreshold = 22; this.on('touchstart', function(event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { firstTouch = 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 xdiff = event.touches[0].pageX - firstTouch.pageX; ydiff = event.touches[0].pageY - firstTouch.pageY; touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); noTap = function(){ 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 touchTime = new Date().getTime() - touchStart; // The touch needs to be quick in order to consider it a tap if (touchTime < 250) { event.preventDefault(); // Don't let browser turn this into a click 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 // vjs.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. */ vjs.Component.prototype.enableTouchActivity = function() { var report, touchHolding, touchEnd; // Don't continue if the root player doesn't support reporting user activity if (!this.player().reportUserActivity) { return; } // listener for reporting that the user is active report = vjs.bind(this.player(), this.player().reportUserActivity); 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 clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = setInterval(report, 250); }); touchEnd = function(event) { report(); // stop the interval that maintains activity if the touch is holding clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /* Button - Base class for all buttons ================================================================================ */ /** * Base class for all buttons * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Button = vjs.Component.extend({ /** * @constructor * @inheritDoc */ init: function(player, options){ vjs.Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.onClick); this.on('click', this.onClick); this.on('focus', this.onFocus); this.on('blur', this.onBlur); } }); vjs.Button.prototype.createEl = function(type, props){ var el; // Add standard Aria and Tabindex info props = vjs.obj.merge({ className: this.buildCSSClass(), 'role': 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); el = vjs.Component.prototype.createEl.call(this, type, props); // if innerHTML hasn't been overridden (bigPlayButton), add content elements if (!props.innerHTML) { this.contentEl_ = vjs.createEl('div', { className: 'vjs-control-content' }); this.controlText_ = vjs.createEl('span', { className: 'vjs-control-text', innerHTML: this.localize(this.buttonText) || 'Need Text' }); this.contentEl_.appendChild(this.controlText_); el.appendChild(this.contentEl_); } return el; }; vjs.Button.prototype.buildCSSClass = function(){ // TODO: Change vjs-control to vjs-button? return 'vjs-control ' + vjs.Component.prototype.buildCSSClass.call(this); }; // Click - Override with specific functionality for button vjs.Button.prototype.onClick = function(){}; // Focus - Add keyboard functionality to element vjs.Button.prototype.onFocus = function(){ vjs.on(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; // KeyPress (document level) - Trigger click when keys are pressed vjs.Button.prototype.onKeyPress = function(event){ // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { event.preventDefault(); this.onClick(); } }; // Blur - Remove keyboard triggers vjs.Button.prototype.onBlur = function(){ vjs.off(document, 'keydown', vjs.bind(this, this.onKeyPress)); }; /* Slider ================================================================================ */ /** * The base functionality for sliders like the volume bar and seek bar * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.Slider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Set property names to bar and handle to match with the child Slider class is looking for this.bar = this.getChild(this.options_['barName']); this.handle = this.getChild(this.options_['handleName']); this.on('mousedown', this.onMouseDown); this.on('touchstart', this.onMouseDown); this.on('focus', this.onFocus); this.on('blur', this.onBlur); this.on('click', this.onClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); this.boundEvents = {}; this.boundEvents.move = vjs.bind(this, this.onMouseMove); this.boundEvents.end = vjs.bind(this, this.onMouseUp); } }); vjs.Slider.prototype.dispose = function() { vjs.off(document, 'mousemove', this.boundEvents.move, false); vjs.off(document, 'mouseup', this.boundEvents.end, false); vjs.off(document, 'touchmove', this.boundEvents.move, false); vjs.off(document, 'touchend', this.boundEvents.end, false); vjs.off(document, 'keyup', vjs.bind(this, this.onKeyPress)); vjs.Component.prototype.dispose.call(this); }; vjs.Slider.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = vjs.obj.merge({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return vjs.Component.prototype.createEl.call(this, type, props); }; vjs.Slider.prototype.onMouseDown = function(event){ event.preventDefault(); vjs.blockTextSelection(); this.addClass('vjs-sliding'); vjs.on(document, 'mousemove', this.boundEvents.move); vjs.on(document, 'mouseup', this.boundEvents.end); vjs.on(document, 'touchmove', this.boundEvents.move); vjs.on(document, 'touchend', this.boundEvents.end); this.onMouseMove(event); }; // To be overridden by a subclass vjs.Slider.prototype.onMouseMove = function(){}; vjs.Slider.prototype.onMouseUp = function() { vjs.unblockTextSelection(); this.removeClass('vjs-sliding'); vjs.off(document, 'mousemove', this.boundEvents.move, false); vjs.off(document, 'mouseup', this.boundEvents.end, false); vjs.off(document, 'touchmove', this.boundEvents.move, false); vjs.off(document, 'touchend', this.boundEvents.end, false); this.update(); }; vjs.Slider.prototype.update = function(){ // 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 barProgress, progress = this.getPercent(), handle = this.handle, bar = this.bar; // Protect against no duration and other division issues if (isNaN(progress)) { progress = 0; } barProgress = progress; // If there is a handle, we need to account for the handle in our calculation for progress bar // so that it doesn't fall short of or extend past the handle. if (handle) { var box = this.el_, boxWidth = box.offsetWidth, handleWidth = handle.el().offsetWidth, // The width of the handle in percent of the containing box // In IE, widths may not be ready yet causing NaN handlePercent = (handleWidth) ? handleWidth / boxWidth : 0, // Get the adjusted size of the box, considering that the handle's center never touches the left or right side. // There is a margin of half the handle's width on both sides. boxAdjustedPercent = 1 - handlePercent, // Adjust the progress that we'll use to set widths to the new adjusted box width adjustedProgress = progress * boxAdjustedPercent; // The bar does reach the left side, so we need to account for this in the bar's width barProgress = adjustedProgress + (handlePercent / 2); // Move the handle from the left based on the adjected progress handle.el().style.left = vjs.round(adjustedProgress * 100, 2) + '%'; } // Set the new bar width if (bar) { bar.el().style.width = vjs.round(barProgress * 100, 2) + '%'; } }; vjs.Slider.prototype.calculateDistance = function(event){ var el, box, boxX, boxY, boxW, boxH, handle, pageX, pageY; el = this.el_; box = vjs.findPosition(el); boxW = boxH = el.offsetWidth; handle = this.handle; if (this.options()['vertical']) { boxY = box.top; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } if (handle) { var handleH = handle.el().offsetHeight; // Adjusted X and Width, so handle doesn't go outside the bar boxY = boxY + (handleH / 2); boxH = boxH - handleH; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, ((boxY - pageY) + boxH) / boxH)); } else { boxX = box.left; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } if (handle) { var handleW = handle.el().offsetWidth; // Adjusted X and Width, so handle doesn't go outside the bar boxX = boxX + (handleW / 2); boxW = boxW - handleW; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; vjs.Slider.prototype.onFocus = function(){ vjs.on(document, 'keyup', vjs.bind(this, this.onKeyPress)); }; vjs.Slider.prototype.onKeyPress = function(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(); } }; vjs.Slider.prototype.onBlur = function(){ vjs.off(document, 'keyup', vjs.bind(this, this.onKeyPress)); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * @param {Object} event Event object */ vjs.Slider.prototype.onClick = function(event){ event.stopImmediatePropagation(); event.preventDefault(); }; /** * SeekBar Behavior includes play progress bar, and seek handle * Needed so it can determine seek position based on handle position/size * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SliderHandle = vjs.Component.extend(); /** * Default value of the slider * * @type {Number} * @private */ vjs.SliderHandle.prototype.defaultValue = 0; /** @inheritDoc */ vjs.SliderHandle.prototype.createEl = function(type, props) { props = props || {}; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider-handle'; props = vjs.obj.merge({ innerHTML: '<span class="vjs-control-text">'+this.defaultValue+'</span>' }, props); return vjs.Component.prototype.createEl.call(this, 'div', props); }; /* Menu ================================================================================ */ /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.Menu = vjs.Component.extend(); /** * Add a menu item to the menu * @param {Object|String} component Component or component type to add */ vjs.Menu.prototype.addItem = function(component){ this.addChild(component); component.on('click', vjs.bind(this, function(){ this.unlockShowing(); })); }; /** @inheritDoc */ vjs.Menu.prototype.createEl = function(){ var contentElType = this.options().contentElType || 'ul'; this.contentEl_ = vjs.createEl(contentElType, { className: 'vjs-menu-content' }); var el = vjs.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 vjs.on(el, 'click', function(event){ event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; /** * The component for a menu item. `<li>` * * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.MenuItem = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.selected(options['selected']); } }); /** @inheritDoc */ vjs.MenuItem.prototype.createEl = function(type, props){ return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']) }, props)); }; /** * Handle a click on the menu item, and set it to selected */ vjs.MenuItem.prototype.onClick = function(){ this.selected(true); }; /** * Set this menu item as selected or not * @param {Boolean} selected */ vjs.MenuItem.prototype.selected = function(selected){ if (selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected',true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected',false); } }; /** * A button class with a popup menu * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MenuButton = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.menu = this.createMenu(); // Add list to element this.addChild(this.menu); // Automatically hide empty menu buttons if (this.items && this.items.length === 0) { this.hide(); } this.on('keyup', this.onKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } }); /** * Track the state of the menu button * @type {Boolean} * @private */ vjs.MenuButton.prototype.buttonPressed_ = false; vjs.MenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_); // Add a title list item to the top if (this.options().title) { menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(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. */ vjs.MenuButton.prototype.createItems = function(){}; /** @inheritDoc */ vjs.MenuButton.prototype.buildCSSClass = function(){ return this.className + ' vjs-menu-button ' + vjs.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. vjs.MenuButton.prototype.onFocus = function(){}; // Can't turn off list display that we turned on with focus, because list would go away. vjs.MenuButton.prototype.onBlur = function(){}; vjs.MenuButton.prototype.onClick = function(){ // 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. this.one('mouseout', vjs.bind(this, function(){ this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } }; vjs.MenuButton.prototype.onKeyPress = function(event){ event.preventDefault(); // Check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { if (this.buttonPressed_){ this.unpressButton(); } else { this.pressButton(); } // Check for escape (27) key } else if (event.which == 27){ if (this.buttonPressed_){ this.unpressButton(); } } }; vjs.MenuButton.prototype.pressButton = function(){ 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 } }; vjs.MenuButton.prototype.unpressButton = function(){ this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; /** * Custom MediaError to mimic the HTML5 MediaError * @param {Number} code The media error code */ vjs.MediaError = function(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 vjs.obj.merge(this, code); } if (!this.message) { this.message = vjs.MediaError.defaultMessages[this.code] || ''; } }; /** * The error code that refers two one of the defined * MediaError types * @type {Number} */ vjs.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} */ vjs.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 {[type]} */ vjs.MediaError.prototype.status = null; vjs.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 ]; vjs.MediaError.defaultMessages = { 1: 'You aborted the video playback', 2: 'A network error caused the video download to fail part-way.', 3: 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support.', 4: 'The video could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The video 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 < vjs.MediaError.errorTypes.length; errNum++) { vjs.MediaError[vjs.MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance vjs.MediaError.prototype[vjs.MediaError.errorTypes[errNum]] = errNum; } (function(){ var apiMap, specApi, browserApi, i; /** * Store the browser-specifc methods for the fullscreen API * @type {Object|undefined} * @private */ vjs.browser.fullscreenAPI; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js 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' ] ]; specApi = apiMap[0]; // determine the supported set of functions for (i=0; i<apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in document) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names // or leave vjs.browser.fullscreenAPI undefined if (browserApi) { vjs.browser.fullscreenAPI = {}; for (i=0; i<browserApi.length; i++) { vjs.browser.fullscreenAPI[specApi[i]] = browserApi[i]; } } })(); /** * An instance of the `vjs.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')`. * * @class * @extends vjs.Component */ vjs.Player = vjs.Component.extend({ /** * 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 */ init: function(tag, options, ready){ this.tag = tag; // Store the original tag used to set options // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // Store the tag attributes used to restore html5 element this.tagAttributes = tag && vjs.getElementAttributes(tag); // 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 = vjs.obj.merge(this.getTagSettings(tag), options); // Update Current Language this.language_ = options['language'] || vjs.options['language']; // Update Supported Languages this.languages_ = options['languages'] || vjs.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; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Set isAudio based on whether or not an audio tag was used this.isAudio(this.tag.nodeName.toLowerCase() === 'audio'); // Run base component initializing with new options. // Builds the element through createEl() // Inits and embeds any child components in opts vjs.Component.call(this, this, options, ready); // 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'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenForUserActivity(); } }); /** * The players's stored language code * * @type {String} * @private */ vjs.Player.prototype.language_; /** * The player's language code * @param {String} languageCode The locale string * @return {String} The locale string when getting * @return {vjs.Player} self, when setting */ vjs.Player.prototype.language = function (languageCode) { if (languageCode === undefined) { return this.language_; } this.language_ = languageCode; return this; }; /** * The players's stored language dictionary * * @type {Object} * @private */ vjs.Player.prototype.languages_; vjs.Player.prototype.languages = function(){ return this.languages_; }; /** * Player instance options, surfaced using vjs.options * vjs.options = vjs.Player.prototype.options_ * Make changes in vjs.options, not here. * All options should use string keys so they avoid * renaming by closure compiler * @type {Object} * @private */ vjs.Player.prototype.options_ = vjs.options; /** * Destroys the video player and does any necessary cleanup * * myPlayer.dispose(); * * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. */ vjs.Player.prototype.dispose = function(){ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // Kill reference to this player vjs.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 dispose vjs.Component.prototype.dispose.call(this); }; vjs.Player.prototype.getTagSettings = function(tag){ var tagOptions, dataSetup, options = { 'sources': [], 'tracks': [] }; tagOptions = vjs.getElementAttributes(tag); dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null){ // Parse options JSON // If empty string, make it a parsable json object. vjs.obj.merge(tagOptions, vjs.JSON.parse(dataSetup || '{}')); } vjs.obj.merge(options, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children, child, childName, i, j; children = tag.childNodes; for (i=0,j=children.length; i<j; i++) { child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ childName = child.nodeName.toLowerCase(); if (childName === 'source') { options['sources'].push(vjs.getElementAttributes(child)); } else if (childName === 'track') { options['tracks'].push(vjs.getElementAttributes(child)); } } } return options; }; vjs.Player.prototype.createEl = function(){ var el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div'), tag = this.tag, attrs; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // 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 if (tag.hasChildNodes()) { var nodes, nodesLength, i, node, nodeName, removeNodes; nodes = tag.childNodes; nodesLength = nodes.length; removeNodes = []; while (nodesLength--) { node = nodes[nodesLength]; nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { removeNodes.push(node); } } for (i=0; i<removeNodes.length; i++) { tag.removeChild(removeNodes[i]); } } // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag attrs = vjs.getElementAttributes(tag); vjs.obj.each(attrs, 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'); // Make box use width/height of tag, or rely on default implementation // Enforce with CSS since width/height attrs don't work on divs this.width(this.options_['width'], true); // (true) Skip resize listener on load this.height(this.options_['height'], true); // vjs.insertFirst 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); } vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. // The event listeners need to be added before the children are added // in the component init because the tech (loaded with mediaLoader) may // fire events, like loadstart, that these events need to capture. // Long term it might be better to expose a way to do this in component.init // like component.initEventListeners() that runs between el creation and // adding children this.el_ = el; this.on('loadstart', this.onLoadStart); this.on('waiting', this.onWaiting); this.on(['canplay', 'canplaythrough', 'playing', 'ended'], this.onWaitEnd); this.on('seeking', this.onSeeking); this.on('seeked', this.onSeeked); this.on('ended', this.onEnded); this.on('play', this.onPlay); this.on('firstplay', this.onFirstPlay); this.on('pause', this.onPause); this.on('progress', this.onProgress); this.on('durationchange', this.onDurationChange); this.on('fullscreenchange', this.onFullscreenChange); return el; }; // /* Media Technology (tech) // ================================================================================ */ // Load/Create an instance of playback technlogy including element and API methods // And append playback element in player div. vjs.Player.prototype.loadTech = function(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) { vjs.Html5.disposeMediaElement(this.tag); 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 = function(){ this.player_.triggerReady(); }; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]); 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 this.tech = new window['videojs'][techName](this, techOptions); this.tech.ready(techReady); }; vjs.Player.prototype.unloadTech = function(){ this.isReady_ = false; this.tech.dispose(); this.tech = false; }; // There's many issues around changing the size of a Flash (or other plugin) object. // First is a plugin reload issue in Firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268 // Then with the new fullscreen API, Mozilla and webkit browsers will reload the flash object after going to fullscreen. // To get around this, we're unloading the tech, caching source and currentTime values, and reloading the tech once the plugin is resized. // reloadTech: function(betweenFn){ // vjs.log('unloadingTech') // this.unloadTech(); // vjs.log('unloadedTech') // if (betweenFn) { betweenFn.call(); } // vjs.log('LoadingTech') // this.loadTech(this.techName, { src: this.cache_.src }) // vjs.log('loadedTech') // }, // /* Player event handlers (how the player reacts to certain events) // ================================================================================ */ /** * Fired when the user agent begins looking for media data * @event loadstart */ vjs.Player.prototype.onLoadStart = function() { // TODO: Update to use `emptied` event instead. See #1277. // 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('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.one('play', function(){ this.hasStarted(true); }); } }; vjs.Player.prototype.hasStarted_ = false; vjs.Player.prototype.hasStarted = function(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 when the player has initial duration and dimension information * @event loadedmetadata */ vjs.Player.prototype.onLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * @event loadeddata */ vjs.Player.prototype.onLoadedData; /** * Fired when the player has finished downloading the source data * @event loadedalldata */ vjs.Player.prototype.onLoadedAllData; /** * Fired whenever the media begins or resumes playback * @event play */ vjs.Player.prototype.onPlay = function(){ this.removeClass('vjs-paused'); this.addClass('vjs-playing'); }; /** * Fired whenever the media begins wating * @event waiting */ vjs.Player.prototype.onWaiting = function(){ this.addClass('vjs-waiting'); }; /** * A handler for events that signal that waiting has eneded * which is not consistent between browsers. See #1351 * @private */ vjs.Player.prototype.onWaitEnd = function(){ this.removeClass('vjs-waiting'); }; /** * Fired whenever the player is jumping to a new time * @event seeking */ vjs.Player.prototype.onSeeking = function(){ this.addClass('vjs-seeking'); }; /** * Fired when the player has finished jumping to a new time * @event seeked */ vjs.Player.prototype.onSeeked = function(){ this.removeClass('vjs-seeking'); }; /** * 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 */ vjs.Player.prototype.onFirstPlay = function(){ //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'); }; /** * Fired whenever the media has been paused * @event pause */ vjs.Player.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); }; /** * 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 */ vjs.Player.prototype.onTimeUpdate; /** * Fired while the user agent is downloading media data * @event progress */ vjs.Player.prototype.onProgress = function(){ // 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 */ vjs.Player.prototype.onEnded = function(){ if (this.options_['loop']) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } }; /** * Fired when the duration of the media resource is first known or changed * @event durationchange */ vjs.Player.prototype.onDurationChange = function(){ // Allows for cacheing value instead of asking player each time. // We need to get the techGet response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techGet('duration'); if (duration) { if (duration < 0) { duration = Infinity; } this.duration(duration); // Determine if the stream is live and propagate styles down to UI. if (duration === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } } }; /** * Fired when the volume changes * @event volumechange */ vjs.Player.prototype.onVolumeChange; /** * Fired when the player switches in or out of fullscreen mode * @event fullscreenchange */ vjs.Player.prototype.onFullscreenChange = function() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; // /* Player API // ================================================================================ */ /** * Object for cached values. * @private */ vjs.Player.prototype.cache_; vjs.Player.prototype.getCache = function(){ return this.cache_; }; // Pass values to the playback tech vjs.Player.prototype.techCall = function(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); }); // Otherwise call method now } else { try { this.tech[method](arg); } catch(e) { vjs.log(e); throw e; } } }; // Get calls can't wait for the tech, and sometimes don't need to. vjs.Player.prototype.techGet = function(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) { vjs.log('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') { vjs.log('Video.js: ' + method + ' unavailable on '+this.techName+' playback technology element.', e); this.tech.isReady_ = false; } else { vjs.log(e); } } throw e; } } return; }; /** * start media playback * * myPlayer.play(); * * @return {vjs.Player} self */ vjs.Player.prototype.play = function(){ this.techCall('play'); return this; }; /** * Pause the video playback * * myPlayer.pause(); * * @return {vjs.Player} self */ vjs.Player.prototype.pause = function(){ this.techCall('pause'); return this; }; /** * Check if the player is paused * * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * * @return {Boolean} false if the media is currently playing, or true otherwise */ vjs.Player.prototype.paused = function(){ // The initial state of paused should be true (in Safari it's actually false) return (this.techGet('paused') === false) ? false : true; }; /** * Get or set the current time (in seconds) * * // 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 {vjs.Player} self, when the current time is set */ vjs.Player.prototype.currentTime = function(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 performace 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 * * 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. * * @return {Number} The duration of the video in seconds */ vjs.Player.prototype.duration = function(seconds){ if (seconds !== undefined) { // cache the last set value for optimiized scrubbing (esp. Flash) this.cache_.duration = parseFloat(seconds); return this; } if (this.cache_.duration === undefined) { this.onDurationChange(); } return this.cache_.duration || 0; }; /** * Calculates how much time is left. * * var timeLeft = myPlayer.remainingTime(); * * Not a native video element function, but useful * @return {Number} The time remaining in seconds */ vjs.Player.prototype.remainingTime = function(){ 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. * * // 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) */ vjs.Player.prototype.buffered = function(){ var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = vjs.createTimeRange(0,0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * * 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 */ vjs.Player.prototype.bufferedPercent = function(){ var duration = this.duration(), buffered = this.buffered(), bufferedDuration = 0, start, end; if (!duration) { return 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; }; /** * 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 */ vjs.Player.prototype.bufferedEnd = function(){ 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 * * // 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 {vjs.Player} self, when setting */ vjs.Player.prototype.volume = function(percentAsDecimal){ var vol; 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); vjs.setLocalStorage('volume', 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 * * // 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 {vjs.Player} self, when setting mute */ vjs.Player.prototype.muted = function(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 lik iOS, so not our flash swf) vjs.Player.prototype.supportsFullScreen = function(){ return this.techGet('supportsFullScreen') || false; }; /** * is the player in fullscreen * @type {Boolean} * @private */ vjs.Player.prototype.isFullscreen_ = false; /** * Check if the player is in fullscreen mode * * // 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 * @return {vjs.Player} self, when setting */ vjs.Player.prototype.isFullscreen = function(isFS){ if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return this.isFullscreen_; }; /** * Old naming for isFullscreen() * @deprecated for lowercase 's' version */ vjs.Player.prototype.isFullScreen = function(isFS){ vjs.log.warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")'); return this.isFullscreen(isFS); }; /** * Increase the size of the video to full screen * * 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 {vjs.Player} self */ vjs.Player.prototype.requestFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(true); if (fsApi) { // 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 cancelling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events vjs.on(document, fsApi['fullscreenchange'], vjs.bind(this, function(e){ this.isFullscreen(document[fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { vjs.off(document, fsApi['fullscreenchange'], arguments.callee); } 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; }; /** * Old naming for requestFullscreen * @deprecated for lower case 's' version */ vjs.Player.prototype.requestFullScreen = function(){ vjs.log.warn('player.requestFullScreen() has been deprecated, use player.requestFullscreen() with a lowercase "s")'); return this.requestFullscreen(); }; /** * Return the video to its normal size after having been in full screen mode * * myPlayer.exitFullscreen(); * * @return {vjs.Player} self */ vjs.Player.prototype.exitFullscreen = function(){ var fsApi = vjs.browser.fullscreenAPI; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi) { document[fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Old naming for exitFullscreen * @deprecated for exitFullscreen */ vjs.Player.prototype.cancelFullScreen = function(){ vjs.log.warn('player.cancelFullScreen() has been deprecated, use player.exitFullscreen()'); return this.exitFullscreen(); }; // When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. vjs.Player.prototype.enterFullWindow = function(){ this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = document.documentElement.style.overflow; // Add listener for esc key to exit fullscreen vjs.on(document, 'keydown', vjs.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars document.documentElement.style.overflow = 'hidden'; // Apply fullscreen styles vjs.addClass(document.body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; vjs.Player.prototype.fullWindowOnEscKey = function(event){ if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; vjs.Player.prototype.exitFullWindow = function(){ this.isFullWindow = false; vjs.off(document, 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. document.documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles vjs.removeClass(document.body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; vjs.Player.prototype.selectSource = function(sources){ // Loop through each playback technology in the options order for (var i=0,j=this.options_['techOrder'];i<j.length;i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][techName]; // Check if the current tech is defined before continuing if (!tech) { vjs.log.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. * * 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. * * 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. * * 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 */ vjs.Player.prototype.src = function(source){ if (source === undefined) { return this.techGet('src'); } // case: Array of source objects to choose from and pick the best to play if (vjs.obj.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 && !window['videojs'][this.techName]['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(){ this.techCall('src', source.src); if (this.options_['preload'] == 'auto') { this.load(); } if (this.options_['autoplay']) { this.play(); } }); } } return this; }; /** * Handle an array of source objects * @param {[type]} sources Array of source objects * @private */ vjs.Player.prototype.sourceList_ = function(sources){ var sourceTech = this.selectSource(sources), errorTimeout; 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 errorTimeout = setTimeout(vjs.bind(this, 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(); this.on('dispose', function() { clearTimeout(errorTimeout); }); } }; /** * Begin loading the src data. * @return {vjs.Player} Returns the player */ vjs.Player.prototype.load = function(){ 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 */ vjs.Player.prototype.currentSrc = function(){ 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 */ vjs.Player.prototype.currentType = function(){ return this.currentType_ || ''; }; /** * Get or set the preload attribute. * @return {String} The preload attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.preload = function(value){ if (value !== undefined) { this.techCall('setPreload', value); this.options_['preload'] = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * @return {String} The autoplay attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.autoplay = function(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. * @return {String} The loop attribute value when getting * @return {vjs.Player} Returns the player when setting */ vjs.Player.prototype.loop = function(value){ if (value !== undefined) { this.techCall('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet('loop'); }; /** * the url of the poster image source * @type {String} * @private */ vjs.Player.prototype.poster_; /** * get or set the poster image source url * * ##### EXAMPLE: * * // getting * var currentPoster = myPlayer.poster(); * * // setting * myPlayer.poster('http://example.com/myImage.jpg'); * * @param {String=} [src] Poster image source URL * @return {String} poster URL when getting * @return {vjs.Player} self when setting */ vjs.Player.prototype.poster = function(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; }; /** * Whether or not the controls are showing * @type {Boolean} * @private */ vjs.Player.prototype.controls_; /** * Get or set whether or not the controls are showing. * @param {Boolean} controls Set controls to showing or not * @return {Boolean} Controls are showing */ vjs.Player.prototype.controls = function(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 (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); } } return this; } return this.controls_; }; vjs.Player.prototype.usingNativeControls_; /** * 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 {vjs.Player} Returns the player * @private */ vjs.Player.prototype.usingNativeControls = function(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 vjs.Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof vjs.Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return this.usingNativeControls_; }; /** * Store the current media error * @type {Object} * @private */ vjs.Player.prototype.error_ = null; /** * Set or get the current MediaError * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {vjs.MediaError|null} when getting * @return {vjs.Player} when setting */ vjs.Player.prototype.error = function(err){ if (err === undefined) { return this.error_; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof vjs.MediaError) { this.error_ = err; } else { this.error_ = new vjs.MediaError(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 vjs.log.error('(CODE:'+this.error_.code+' '+vjs.MediaError.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. */ vjs.Player.prototype.ended = function(){ 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. */ vjs.Player.prototype.seeking = function(){ return this.techGet('seeking'); }; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed vjs.Player.prototype.userActivity_ = true; vjs.Player.prototype.reportUserActivity = function(event){ this.userActivity_ = true; }; vjs.Player.prototype.userActive_ = true; vjs.Player.prototype.userActive = function(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_; }; vjs.Player.prototype.listenForUserActivity = function(){ var onActivity, onMouseMove, onMouseDown, mouseInProgress, onMouseUp, activityCheck, inactivityTimeout, lastMoveX, lastMoveY; onActivity = vjs.bind(this, this.reportUserActivity); onMouseMove = function(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; onActivity(); } }; onMouseDown = function() { onActivity(); // 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 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 = setInterval(onActivity, 250); }; onMouseUp = function(event) { onActivity(); // Stop the interval that maintains activity if the mouse/touch is down clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', onMouseDown); this.on('mousemove', onMouseMove); this.on('mouseup', onMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', onActivity); this.on('keyup', onActivity); // 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/ activityCheck = setInterval(vjs.bind(this, 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 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 = setTimeout(vjs.bind(this, 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); // Clean up the intervals when we kill the player this.on('dispose', function(){ clearInterval(activityCheck); clearTimeout(inactivityTimeout); }); }; /** * Gets or sets the current playback rate. * @param {Boolean} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting */ vjs.Player.prototype.playbackRate = function(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech['featuresPlaybackRate']) { return this.techGet('playbackRate'); } else { return 1.0; } }; /** * Store the current audio state * @type {Boolean} * @private */ vjs.Player.prototype.isAudio_ = false; /** * 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 {vjs.Player} Returns the player if setting * @private */ vjs.Player.prototype.isAudio = function(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return this.isAudio_; }; // Methods to add support for // networkState: function(){ return this.techCall('networkState'); }, // readyState: function(){ return this.techCall('readyState'); }, // 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'); }, // videoWidth: function(){ return this.techCall('videoWidth'); }, // videoHeight: function(){ return this.techCall('videoHeight'); }, // 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 /** * Container of main controls * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor * @extends vjs.Component */ vjs.ControlBar = vjs.Component.extend(); vjs.ControlBar.prototype.options_ = { loadEvent: 'play', children: { 'playToggle': {}, 'currentTimeDisplay': {}, 'timeDivider': {}, 'durationDisplay': {}, 'remainingTimeDisplay': {}, 'liveDisplay': {}, 'progressControl': {}, 'fullscreenToggle': {}, 'volumeControl': {}, 'muteToggle': {}, // 'volumeMenuButton': {}, 'playbackRateMenuButton': {} } }; vjs.ControlBar.prototype.createEl = function(){ return vjs.createEl('div', { className: 'vjs-control-bar' }); }; /** * Displays the live indicator * TODO - Future make it click to snap to live * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LiveDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.LiveDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-controls vjs-control' }); this.contentEl_ = vjs.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; }; /** * Button to toggle between play and pause * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.PlayToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.on(player, 'play', this.onPlay); this.on(player, 'pause', this.onPause); } }); vjs.PlayToggle.prototype.buttonText = 'Play'; vjs.PlayToggle.prototype.buildCSSClass = function(){ return 'vjs-play-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; // OnClick - Toggle between play and pause vjs.PlayToggle.prototype.onClick = function(){ if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; // OnPlay - Add the vjs-playing class to the element so it can change appearance vjs.PlayToggle.prototype.onPlay = function(){ this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.el_.children[0].children[0].innerHTML = this.localize('Pause'); // change the button text to "Pause" }; // OnPause - Add the vjs-paused class to the element so it can change appearance vjs.PlayToggle.prototype.onPause = function(){ this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.el_.children[0].children[0].innerHTML = this.localize('Play'); // change the button text to "Play" }; /** * Displays the current time * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.CurrentTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.CurrentTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.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; }; vjs.CurrentTimeDisplay.prototype.updateContent = function(){ // 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 = '<span class="vjs-control-text">' + this.localize('Current Time') + '</span> ' + vjs.formatTime(time, this.player_.duration()); }; /** * Displays the duration * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.DurationDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.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); } }); vjs.DurationDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-controls vjs-control' }); this.contentEl_ = vjs.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; }; vjs.DurationDisplay.prototype.updateContent = function(){ var duration = this.player_.duration(); if (duration) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> ' + vjs.formatTime(duration); // label the duration time for screen reader users } }; /** * The separator between the current time and duration * * Can be hidden if it's not needed in the design. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TimeDivider = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.TimeDivider.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; /** * Displays the time left in the video * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.RemainingTimeDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); vjs.RemainingTimeDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-controls vjs-control' }); this.contentEl_ = vjs.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; }; vjs.RemainingTimeDisplay.prototype.updateContent = function(){ if (this.player_.duration()) { this.contentEl_.innerHTML = '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> ' + '-'+ vjs.formatTime(this.player_.remainingTime()); } // 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()); }; /** * Toggle fullscreen video * @param {vjs.Player|Object} player * @param {Object=} options * @class * @extends vjs.Button */ vjs.FullscreenToggle = vjs.Button.extend({ /** * @constructor * @memberof vjs.FullscreenToggle * @instance */ init: function(player, options){ vjs.Button.call(this, player, options); } }); vjs.FullscreenToggle.prototype.buttonText = 'Fullscreen'; vjs.FullscreenToggle.prototype.buildCSSClass = function(){ return 'vjs-fullscreen-control ' + vjs.Button.prototype.buildCSSClass.call(this); }; vjs.FullscreenToggle.prototype.onClick = function(){ if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText_.innerHTML = this.localize('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText_.innerHTML = this.localize('Fullscreen'); } }; /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ProgressControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.ProgressControl.prototype.options_ = { children: { 'seekBar': {} } }; vjs.ProgressControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; /** * Seek Bar and holder for the progress bars * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.SeekBar.prototype.options_ = { children: { 'loadProgressBar': {}, 'playProgressBar': {}, 'seekHandle': {} }, 'barName': 'playProgressBar', 'handleName': 'seekHandle' }; vjs.SeekBar.prototype.playerEvent = 'timeupdate'; vjs.SeekBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; vjs.SeekBar.prototype.updateARIAAttributes = function(){ // 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',vjs.round(this.getPercent()*100, 2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext',vjs.formatTime(time, this.player_.duration())); // human readable value of progress bar (time complete) }; vjs.SeekBar.prototype.getPercent = function(){ return this.player_.currentTime() / this.player_.duration(); }; vjs.SeekBar.prototype.onMouseDown = function(event){ vjs.Slider.prototype.onMouseDown.call(this, event); this.player_.scrubbing = true; this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; vjs.SeekBar.prototype.onMouseMove = function(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); }; vjs.SeekBar.prototype.onMouseUp = function(event){ vjs.Slider.prototype.onMouseUp.call(this, event); this.player_.scrubbing = false; if (this.videoWasPlaying) { this.player_.play(); } }; vjs.SeekBar.prototype.stepForward = function(){ this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; vjs.SeekBar.prototype.stepBack = function(){ this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; /** * Shows load progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.LoadProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); this.on(player, 'progress', this.update); } }); vjs.LoadProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; vjs.LoadProgressBar.prototype.update = function(){ var i, start, end, part, buffered = this.player_.buffered(), duration = this.player_.duration(), bufferedEnd = this.player_.bufferedEnd(), children = this.el_.children, // get the percent width of a time compared to the total end percentify = function (time, end){ var percent = (time / end) || 0; // no NaN return (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 (i = 0; i < buffered.length; i++) { start = buffered.start(i), end = buffered.end(i), part = children[i]; if (!part) { part = this.el_.appendChild(vjs.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 (i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i-1]); } }; /** * Shows play progress * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlayProgressBar = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.PlayProgressBar.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; /** * The Seek Handle shows the current position of the playhead during playback, * and can be dragged to adjust the playhead. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.SeekHandle = vjs.SliderHandle.extend({ init: function(player, options) { vjs.SliderHandle.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } }); /** * The default value for the handle content, which may be read by screen readers * * @type {String} * @private */ vjs.SeekHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.SeekHandle.prototype.createEl = function() { return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-seek-handle', 'aria-live': 'off' }); }; vjs.SeekHandle.prototype.updateContent = function() { var time = (this.player_.scrubbing) ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.innerHTML = '<span class="vjs-control-text">' + vjs.formatTime(time, this.player_.duration()) + '</span>'; }; /** * The component for controlling the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeControl = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.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'); } }); } }); vjs.VolumeControl.prototype.options_ = { children: { 'volumeBar': {} } }; vjs.VolumeControl.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeBar = vjs.Slider.extend({ /** @constructor */ init: function(player, options){ vjs.Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(vjs.bind(this, this.updateARIAAttributes)); } }); vjs.VolumeBar.prototype.updateARIAAttributes = function(){ // Current value of volume bar as a percentage this.el_.setAttribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2)); this.el_.setAttribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%'); }; vjs.VolumeBar.prototype.options_ = { children: { 'volumeLevel': {}, 'volumeHandle': {} }, 'barName': 'volumeLevel', 'handleName': 'volumeHandle' }; vjs.VolumeBar.prototype.playerEvent = 'volumechange'; vjs.VolumeBar.prototype.createEl = function(){ return vjs.Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; vjs.VolumeBar.prototype.onMouseMove = function(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; vjs.VolumeBar.prototype.getPercent = function(){ if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; vjs.VolumeBar.prototype.stepForward = function(){ this.player_.volume(this.player_.volume() + 0.1); }; vjs.VolumeBar.prototype.stepBack = function(){ this.player_.volume(this.player_.volume() - 0.1); }; /** * Shows volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeLevel = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); } }); vjs.VolumeLevel.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; /** * The volume handle can be dragged to adjust the volume level * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.VolumeHandle = vjs.SliderHandle.extend(); vjs.VolumeHandle.prototype.defaultValue = '00:00'; /** @inheritDoc */ vjs.VolumeHandle.prototype.createEl = function(){ return vjs.SliderHandle.prototype.createEl.call(this, 'div', { className: 'vjs-volume-handle' }); }; /** * A button component for muting the audio * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.MuteToggle = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.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(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } }); vjs.MuteToggle.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-mute-control vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.MuteToggle.prototype.onClick = function(){ this.player_.muted( this.player_.muted() ? false : true ); }; vjs.MuteToggle.prototype.update = function(){ 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. if(this.player_.muted()){ if(this.el_.children[0].children[0].innerHTML!=this.localize('Unmute')){ this.el_.children[0].children[0].innerHTML = this.localize('Unmute'); // change the button text to "Unmute" } } else { if(this.el_.children[0].children[0].innerHTML!=this.localize('Mute')){ this.el_.children[0].children[0].innerHTML = this.localize('Mute'); // change the button text to "Mute" } } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { vjs.removeClass(this.el_, 'vjs-vol-'+i); } vjs.addClass(this.el_, 'vjs-vol-'+level); }; /** * Menu button with a popup for showing the volume slider. * @constructor */ vjs.VolumeMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); // Same listeners as MuteToggle 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(){ if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); this.addClass('vjs-menu-button'); } }); vjs.VolumeMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player_, { contentElType: 'div' }); var vc = new vjs.VolumeBar(this.player_, this.options_['volumeBar']); vc.on('focus', function() { menu.lockShowing(); }); vc.on('blur', function() { menu.unlockShowing(); }); menu.addChild(vc); return menu; }; vjs.VolumeMenuButton.prototype.onClick = function(){ vjs.MuteToggle.prototype.onClick.call(this); vjs.MenuButton.prototype.onClick.call(this); }; vjs.VolumeMenuButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-volume-menu-button vjs-menu-button vjs-control', innerHTML: '<div><span class="vjs-control-text">' + this.localize('Mute') + '</span></div>' }); }; vjs.VolumeMenuButton.prototype.update = vjs.MuteToggle.prototype.update; /** * The component for controlling the playback rate * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PlaybackRateMenuButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } }); vjs.PlaybackRateMenuButton.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-playback-rate vjs-menu-button vjs-control', innerHTML: '<div class="vjs-control-content"><span class="vjs-control-text">' + this.localize('Playback Rate') + '</span></div>' }); this.labelEl_ = vjs.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; // Menu creation vjs.PlaybackRateMenuButton.prototype.createMenu = function(){ var menu = new vjs.Menu(this.player()); var rates = this.player().options()['playbackRates']; if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild( new vjs.PlaybackRateMenuItem(this.player(), { 'rate': rates[i] + 'x'}) ); }; } return menu; }; vjs.PlaybackRateMenuButton.prototype.updateARIAAttributes = function(){ // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; vjs.PlaybackRateMenuButton.prototype.onClick = function(){ // select next rate option var currentRate = this.player().playbackRate(); var rates = this.player().options()['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); }; vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function(){ return this.player().tech && this.player().tech['featuresPlaybackRate'] && this.player().options()['playbackRates'] && this.player().options()['playbackRates'].length > 0 ; }; /** * Hide playback rate controls when they're no playback rate options to select */ vjs.PlaybackRateMenuButton.prototype.updateVisibility = function(){ if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed */ vjs.PlaybackRateMenuButton.prototype.updateLabel = function(){ if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; /** * The specific menu item type for selecting a playback rate * * @constructor */ vjs.PlaybackRateMenuItem = vjs.MenuItem.extend({ contentElType: 'button', /** @constructor */ init: function(player, options){ var label = this.label = options['rate']; var rate = this.rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; vjs.MenuItem.call(this, player, options); this.on(player, 'ratechange', this.update); } }); vjs.PlaybackRateMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player().playbackRate(this.rate); }; vjs.PlaybackRateMenuItem.prototype.update = function(){ this.selected(this.player().playbackRate() == this.rate); }; /* Poster Image ================================================================================ */ /** * The component that handles showing the poster image. * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.PosterImage = vjs.Button.extend({ /** @constructor */ init: function(player, options){ vjs.Button.call(this, player, options); this.update(); player.on('posterchange', vjs.bind(this, this.update)); } }); /** * Clean up the poster image */ vjs.PosterImage.prototype.dispose = function(){ this.player().off('posterchange', this.update); vjs.Button.prototype.dispose.call(this); }; /** * Create the poster image element * @return {Element} */ vjs.PosterImage.prototype.createEl = function(){ var el = vjs.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 (!vjs.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = vjs.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source */ vjs.PosterImage.prototype.update = function(){ 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) { // Remove the display style property that hide() adds // as opposed to show() which sets display to block // In the future it might be worth creating an `unhide` component method this.el_.style.display = ''; } else { this.hide(); } }; /** * Set the poster source depending on the display method */ vjs.PosterImage.prototype.setSrc = function(url){ var backgroundImage; if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { 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 */ vjs.PosterImage.prototype.onClick = function(){ // 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 this.player_.play(); }; /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.LoadingSpinner = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // MOVING DISPLAY HANDLING TO CSS // player.on('canplay', vjs.bind(this, this.hide)); // player.on('canplaythrough', vjs.bind(this, this.hide)); // player.on('playing', vjs.bind(this, this.hide)); // player.on('seeking', vjs.bind(this, this.show)); // in some browsers seeking does not trigger the 'playing' event, // so we also need to trap 'seeked' if we are going to set a // 'seeking' event // player.on('seeked', vjs.bind(this, this.hide)); // player.on('ended', vjs.bind(this, this.hide)); // Not showing spinner on stalled any more. Browsers may stall and then not trigger any events that would remove the spinner. // Checked in Chrome 16 and Safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing // player.on('stalled', vjs.bind(this, this.show)); // player.on('waiting', vjs.bind(this, this.show)); } }); vjs.LoadingSpinner.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; /* Big Play Button ================================================================================ */ /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * @param {vjs.Player|Object} player * @param {Object=} options * @class * @constructor */ vjs.BigPlayButton = vjs.Button.extend(); vjs.BigPlayButton.prototype.createEl = function(){ return vjs.Button.prototype.createEl.call(this, 'div', { className: 'vjs-big-play-button', innerHTML: '<span aria-hidden="true"></span>', 'aria-label': 'play video' }); }; vjs.BigPlayButton.prototype.onClick = function(){ this.player_.play(); }; /** * Display that an error has occurred making the video unplayable * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.ErrorDisplay = vjs.Component.extend({ init: function(player, options){ vjs.Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } }); vjs.ErrorDisplay.prototype.createEl = function(){ var el = vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = vjs.createEl('div'); el.appendChild(this.contentEl_); return el; }; vjs.ErrorDisplay.prototype.update = function(){ if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; /** * @fileoverview Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ /** * Base class for media (HTML5 Video, Flash) controllers * @param {vjs.Player|Object} player Central player instance * @param {Object=} options Options object * @constructor */ vjs.MediaTechController = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ options = options || {}; // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; vjs.Component.call(this, player, options, ready); // Manually track progress in cases where the browser/flash player doesn't report it. if (!this['featuresProgressEvents']) { this.manualProgressOn(); } // Manually track timeudpates in cases where the browser/flash player doesn't report it. if (!this['featuresTimeupdateEvents']) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); } }); /** * 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 */ vjs.MediaTechController.prototype.initControlsListeners = function(){ var player, activateControls; player = this.player(); activateControls = function(){ if (player.controls() && !player.usingNativeControls()) { this.addControlsListeners(); } }; // Set up event listeners once the tech is ready and has an element to apply // listeners to this.ready(activateControls); this.on(player, 'controlsenabled', activateControls); this.on(player, 'controlsdisabled', this.removeControlsListeners); // 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.player().trigger('loadstart'); } }); }; vjs.MediaTechController.prototype.addControlsListeners = function(){ var userWasActive; // 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('mousedown', this.onClick); // 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('touchstart', function(event) { userWasActive = this.player_.userActive(); }); this.on('touchmove', function(event) { if (userWasActive){ this.player().reportUserActivity(); } }); this.on('touchend', function(event) { // Stop the mouse events from also happening event.preventDefault(); }); // Turn on component tap events this.emitTapEvents(); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on('tap', this.onTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. */ vjs.MediaTechController.prototype.removeControlsListeners = function(){ // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off('tap'); this.off('touchstart'); this.off('touchmove'); this.off('touchleave'); this.off('touchcancel'); this.off('touchend'); this.off('click'); this.off('mousedown'); }; /** * Handle a click on the media element. By default will play/pause the media. */ vjs.MediaTechController.prototype.onClick = function(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.player().controls()) { if (this.player().paused()) { this.player().play(); } else { this.player().pause(); } } }; /** * Handle a tap on the media element. By default it will toggle the user * activity state, which hides and shows the controls. */ vjs.MediaTechController.prototype.onTap = function(){ this.player().userActive(!this.player().userActive()); }; /* 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 vjs.MediaTechController.prototype.manualProgressOn = function(){ this.manualProgress = true; // Trigger progress watching when a source begins loading this.trackProgress(); }; vjs.MediaTechController.prototype.manualProgressOff = function(){ this.manualProgress = false; this.stopTrackingProgress(); }; vjs.MediaTechController.prototype.trackProgress = function(){ this.progressInterval = setInterval(vjs.bind(this, function(){ // Don't trigger unless buffered amount is greater than last time var bufferedPercent = this.player().bufferedPercent(); if (this.bufferedPercent_ != bufferedPercent) { this.player().trigger('progress'); } this.bufferedPercent_ = bufferedPercent; if (bufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; vjs.MediaTechController.prototype.stopTrackingProgress = function(){ clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ vjs.MediaTechController.prototype.manualTimeUpdatesOn = function(){ var player = this.player_; this.manualTimeUpdates = true; this.on(player, 'play', this.trackCurrentTime); this.on(player, 'pause', this.stopTrackingCurrentTime); // timeupdate is also called by .currentTime whenever current time is set // Watch for native timeupdate event this.one('timeupdate', function(){ // Update known progress support for this playback technology this['featuresTimeupdateEvents'] = true; // Turn off manual progress tracking this.manualTimeUpdatesOff(); }); }; vjs.MediaTechController.prototype.manualTimeUpdatesOff = function(){ this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; vjs.MediaTechController.prototype.trackCurrentTime = function(){ if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = setInterval(vjs.bind(this, function(){ this.player().trigger('timeupdate'); }), 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; // Turn off play progress tracking (when paused or dragging) vjs.MediaTechController.prototype.stopTrackingCurrentTime = function(){ 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.player().trigger('timeupdate'); }; vjs.MediaTechController.prototype.dispose = function() { // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } vjs.Component.prototype.dispose.call(this); }; vjs.MediaTechController.prototype.setCurrentTime = function() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.player().trigger('timeupdate'); } }; /** * 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. */ vjs.MediaTechController.prototype.setPoster = function(){}; vjs.MediaTechController.prototype['featuresVolumeControl'] = true; // Resizing plugins using request fullscreen reloads the plugin vjs.MediaTechController.prototype['featuresFullscreenResize'] = false; vjs.MediaTechController.prototype['featuresPlaybackRate'] = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf vjs.MediaTechController.prototype['featuresProgressEvents'] = false; vjs.MediaTechController.prototype['featuresTimeupdateEvents'] = false; vjs.media = {}; /** * @fileoverview HTML5 Media Controller - Wrapper for HTML5 Media API */ /** * HTML5 Media Controller - Wrapper for HTML5 Media API * @param {vjs.Player|Object} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Html5 = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ // volume cannot be changed from 1 on iOS this['featuresVolumeControl'] = vjs.Html5.canControlVolume(); // just in case; or is it excessively... this['featuresPlaybackRate'] = vjs.Html5.canControlPlaybackRate(); // In iOS, if you move a video element in the DOM, it breaks video playback. this['movingMediaElementInDOM'] = !vjs.IS_IOS; // HTML video is able to automatically resize when going to fullscreen this['featuresFullscreenResize'] = true; // HTML video supports progress events this['featuresProgressEvents'] = true; vjs.MediaTechController.call(this, player, options, ready); this.setupTriggers(); 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) || (player.tag && player.tag.initNetworkState_ === 3)) { this.el_.src = source.src; } // 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 (vjs.TOUCH_ENABLED && player.options()['nativeControlsForTouch'] === true) { this.useNativeControls(); } // 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 player.ready(function(){ if (this.tag && this.options_['autoplay'] && this.paused()) { delete this.tag['poster']; // Chrome Fix. Fixed in Chrome v16. this.play(); } }); this.triggerReady(); } }); vjs.Html5.prototype.dispose = function(){ vjs.Html5.disposeMediaElement(this.el_); vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Html5.prototype.createEl = function(){ var player = this.player_, // If possible, reuse original tag for HTML5 playback technology element el = player.tag, newEl, clone; // 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) { clone = el.cloneNode(false); vjs.Html5.disposeMediaElement(el); el = clone; player.tag = null; } else { el = vjs.createEl('video'); vjs.setElementAttributes(el, vjs.obj.merge(player.tagAttributes || {}, { id:player.id() + '_html5_api', 'class':'vjs-tech' }) ); } // associate the player with the new tag el['player'] = player; vjs.insertFirst(el, player.el()); } // 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 player.options_[attr] !== 'undefined') { overwriteAttrs[attr] = player.options_[attr]; } vjs.setElementAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; // Make video events trigger player events // May seem verbose here, but makes other APIs possible. // Triggers removed using this.off when disposed vjs.Html5.prototype.setupTriggers = function(){ for (var i = vjs.Html5.Events.length - 1; i >= 0; i--) { this.on(vjs.Html5.Events[i], this.eventHandler); } }; vjs.Html5.prototype.eventHandler = function(evt){ // In the case of an error on the video element, set the error prop // on the player and let the player handle triggering the event. On // some platforms, error events fire that do not cause the error // property on the video element to be set. See #1465 for an example. if (evt.type == 'error' && this.error()) { this.player().error(this.error().code); // in some cases we pass the event directly to the player } else { // No need for media events to bubble up. evt.bubbles = false; this.player().trigger(evt); } }; vjs.Html5.prototype.useNativeControls = function(){ var tech, player, controlsOn, controlsOff, cleanUp; tech = this; player = this.player(); // If the player controls are enabled turn on the native controls tech.setControls(player.controls()); // Update the native controls when player controls state is updated controlsOn = function(){ tech.setControls(true); }; controlsOff = function(){ tech.setControls(false); }; player.on('controlsenabled', controlsOn); player.on('controlsdisabled', controlsOff); // Clean up when not using native controls anymore cleanUp = function(){ player.off('controlsenabled', controlsOn); player.off('controlsdisabled', controlsOff); }; tech.on('dispose', cleanUp); player.on('usingcustomcontrols', cleanUp); // Update the state of the player to using native controls player.usingNativeControls(true); }; vjs.Html5.prototype.play = function(){ this.el_.play(); }; vjs.Html5.prototype.pause = function(){ this.el_.pause(); }; vjs.Html5.prototype.paused = function(){ return this.el_.paused; }; vjs.Html5.prototype.currentTime = function(){ return this.el_.currentTime; }; vjs.Html5.prototype.setCurrentTime = function(seconds){ try { this.el_.currentTime = seconds; } catch(e) { vjs.log(e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; vjs.Html5.prototype.duration = function(){ return this.el_.duration || 0; }; vjs.Html5.prototype.buffered = function(){ return this.el_.buffered; }; vjs.Html5.prototype.volume = function(){ return this.el_.volume; }; vjs.Html5.prototype.setVolume = function(percentAsDecimal){ this.el_.volume = percentAsDecimal; }; vjs.Html5.prototype.muted = function(){ return this.el_.muted; }; vjs.Html5.prototype.setMuted = function(muted){ this.el_.muted = muted; }; vjs.Html5.prototype.width = function(){ return this.el_.offsetWidth; }; vjs.Html5.prototype.height = function(){ return this.el_.offsetHeight; }; vjs.Html5.prototype.supportsFullScreen = function(){ if (typeof this.el_.webkitEnterFullScreen == 'function') { // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(vjs.USER_AGENT) || !/Chrome|Mac OS X 10.5/.test(vjs.USER_AGENT)) { return true; } } return false; }; vjs.Html5.prototype.enterFullScreen = function(){ var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function() { this.player_.isFullscreen(true); this.one('webkitendfullscreen', function() { this.player_.isFullscreen(false); this.player_.trigger('fullscreenchange'); }); this.player_.trigger('fullscreenchange'); }); } 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 setTimeout(function(){ video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; vjs.Html5.prototype.exitFullScreen = function(){ this.el_.webkitExitFullScreen(); }; vjs.Html5.prototype.src = function(src) { if (src === undefined) { return this.el_.src; } else { this.el_.src = src; } }; vjs.Html5.prototype.load = function(){ this.el_.load(); }; vjs.Html5.prototype.currentSrc = function(){ return this.el_.currentSrc; }; vjs.Html5.prototype.poster = function(){ return this.el_.poster; }; vjs.Html5.prototype.setPoster = function(val){ this.el_.poster = val; }; vjs.Html5.prototype.preload = function(){ return this.el_.preload; }; vjs.Html5.prototype.setPreload = function(val){ this.el_.preload = val; }; vjs.Html5.prototype.autoplay = function(){ return this.el_.autoplay; }; vjs.Html5.prototype.setAutoplay = function(val){ this.el_.autoplay = val; }; vjs.Html5.prototype.controls = function(){ return this.el_.controls; }; vjs.Html5.prototype.setControls = function(val){ this.el_.controls = !!val; }; vjs.Html5.prototype.loop = function(){ return this.el_.loop; }; vjs.Html5.prototype.setLoop = function(val){ this.el_.loop = val; }; vjs.Html5.prototype.error = function(){ return this.el_.error; }; vjs.Html5.prototype.seeking = function(){ return this.el_.seeking; }; vjs.Html5.prototype.ended = function(){ return this.el_.ended; }; vjs.Html5.prototype.defaultMuted = function(){ return this.el_.defaultMuted; }; vjs.Html5.prototype.playbackRate = function(){ return this.el_.playbackRate; }; vjs.Html5.prototype.setPlaybackRate = function(val){ this.el_.playbackRate = val; }; vjs.Html5.prototype.networkState = function(){ return this.el_.networkState; }; /* HTML5 Support Testing ---------------------------------------------------- */ vjs.Html5.isSupported = function(){ // ie9 with no Media Player is a LIAR! (#984) try { vjs.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!vjs.TEST_VID.canPlayType; }; vjs.Html5.canPlaySource = function(srcObj){ // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return !!vjs.TEST_VID.canPlayType(srcObj.type); } catch(e) { return ''; } // TODO: Check Type // If no Type, check ext // Check Media Type }; vjs.Html5.canControlVolume = function(){ var volume = vjs.TEST_VID.volume; vjs.TEST_VID.volume = (volume / 2) + 0.1; return volume !== vjs.TEST_VID.volume; }; vjs.Html5.canControlPlaybackRate = function(){ var playbackRate = vjs.TEST_VID.playbackRate; vjs.TEST_VID.playbackRate = (playbackRate / 2) + 0.1; return playbackRate !== vjs.TEST_VID.playbackRate; }; // HTML5 Feature detection and Device Fixes --------------------------------- // (function() { var canPlayType, mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i, mp4RE = /^video\/mp4/i; vjs.Html5.patchCanPlayType = function() { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (vjs.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.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 (vjs.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = vjs.TEST_VID.constructor.prototype.canPlayType; } vjs.TEST_VID.constructor.prototype.canPlayType = function(type){ if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; vjs.Html5.unpatchCanPlayType = function() { var r = vjs.TEST_VID.constructor.prototype.canPlayType; vjs.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element vjs.Html5.patchCanPlayType(); })(); // List of all HTML5 events (various uses). vjs.Html5.Events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(','); vjs.Html5.disposeMediaElement = function(el){ if (!el) { return; } el['player'] = null; 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 } })(); } }; /** * @fileoverview 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 */ /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {vjs.Player} player * @param {Object=} options * @param {Function=} ready * @constructor */ vjs.Flash = vjs.MediaTechController.extend({ /** @constructor */ init: function(player, options, ready){ vjs.MediaTechController.call(this, player, options, ready); var source = options['source'], // Which element to embed in parentEl = options['parentEl'], // Create a temporary element to be replaced by swf object placeHolder = this.el_ = vjs.createEl('div', { id: player.id() + '_temp_flash' }), // Generate ID for swf object objId = player.id()+'_flash_api', // Store player options in local var for optimization // TODO: switch to using player methods instead of options // e.g. player.autoplay(); playerOptions = player.options_, // Merge default flashvars with ones passed in to init flashVars = vjs.obj.merge({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': playerOptions.autoplay, 'preload': playerOptions.preload, 'loop': playerOptions.loop, 'muted': playerOptions.muted }, options['flashVars']), // Merge default parames with ones passed in params = vjs.obj.merge({ '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 attributes = vjs.obj.merge({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identifty itself 'class': 'vjs-tech' }, options['attributes']) ; // If source was supplied pass as a flash var. if (source) { if (source.type && vjs.Flash.isStreamingType(source.type)) { var parts = vjs.Flash.streamToParts(source.src); flashVars['rtmpConnection'] = encodeURIComponent(parts.connection); flashVars['rtmpStream'] = encodeURIComponent(parts.stream); } else { flashVars['src'] = encodeURIComponent(vjs.getAbsoluteURL(source.src)); } } // Add placeholder to player div vjs.insertFirst(placeHolder, parentEl); // 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']); }); } // firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37 // bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786 if (vjs.IS_FIREFOX) { this.ready(function(){ this.on('mousemove', function(){ // since it's a custom event, don't bubble higher than the player this.player().trigger({ 'type':'mousemove', 'bubbles': false }); }); }); } // native click events on the SWF aren't triggered on IE11, Win8.1RT // use stageclick events triggered from inside the SWF instead player.on('stageclick', player.reportUserActivity); this.el_ = vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes); } }); vjs.Flash.prototype.dispose = function(){ vjs.MediaTechController.prototype.dispose.call(this); }; vjs.Flash.prototype.play = function(){ this.el_.vjs_play(); }; vjs.Flash.prototype.pause = function(){ this.el_.vjs_pause(); }; vjs.Flash.prototype.src = function(src){ if (src === undefined) { return this['currentSrc'](); } if (vjs.Flash.isStreamingSrc(src)) { src = vjs.Flash.streamToParts(src); this.setRtmpConnection(src.connection); this.setRtmpStream(src.stream); } else { // Make sure source URL is abosolute. src = vjs.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.player_.autoplay()) { var tech = this; setTimeout(function(){ tech.play(); }, 0); } }; vjs.Flash.prototype['setCurrentTime'] = function(time){ this.lastSeekTarget_ = time; this.el_.vjs_setProperty('currentTime', time); vjs.MediaTechController.prototype.setCurrentTime.call(this); }; vjs.Flash.prototype['currentTime'] = function(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'); }; vjs.Flash.prototype['currentSrc'] = function(){ var src = this.el_.vjs_getProperty('currentSrc'); // no src, check and see if RTMP if (src == null) { var connection = this['rtmpConnection'](), stream = this['rtmpStream'](); if (connection && stream) { src = vjs.Flash.streamFromParts(connection, stream); } } return src; }; vjs.Flash.prototype.load = function(){ this.el_.vjs_load(); }; vjs.Flash.prototype.poster = function(){ this.el_.vjs_getProperty('poster'); }; vjs.Flash.prototype['setPoster'] = function(){ // poster images are not handled by the Flash tech so make this a no-op }; vjs.Flash.prototype.buffered = function(){ return vjs.createTimeRange(0, this.el_.vjs_getProperty('buffered')); }; vjs.Flash.prototype.supportsFullScreen = function(){ return false; // Flash does not allow fullscreen through javascript }; vjs.Flash.prototype.enterFullScreen = function(){ return false; }; (function(){ // Create setters and getters for attributes var api = vjs.Flash.prototype, readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','), readOnly = 'error,networkState,readyState,seeking,initialTime,duration,startOffsetTime,paused,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks'.split(','), // Overridden: buffered, currentTime, currentSrc i; 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 (i = 0; i < readWrite.length; i++) { createGetter(readWrite[i]); createSetter(readWrite[i]); } // Create getters for read-only attributes for (i = 0; i < readOnly.length; i++) { createGetter(readOnly[i]); } })(); /* Flash Support Testing -------------------------------------------------------- */ vjs.Flash.isSupported = function(){ return vjs.Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; vjs.Flash.canPlaySource = function(srcObj){ var type; if (!srcObj.type) { return ''; } type = srcObj.type.replace(/;.*/,'').toLowerCase(); if (type in vjs.Flash.formats || type in vjs.Flash.streamingFormats) { return 'maybe'; } }; vjs.Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; vjs.Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; vjs.Flash['onReady'] = function(currSwf){ var el, player; el = vjs.el(currSwf); // get player from the player div property player = el && el.parentNode && el.parentNode['player']; // if there is no el or player then the tech has been disposed // and the tech element was removed from the player div if (player) { // reference player on tech element el['player'] = player; // check that the flash object is really ready vjs.Flash['checkReady'](player.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. vjs.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 setTimeout(function(){ vjs.Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player vjs.Flash['onEvent'] = function(swfID, eventName){ var player = vjs.el(swfID)['player']; player.trigger(eventName); }; // Log errors from the swf vjs.Flash['onError'] = function(swfID, err){ var player = vjs.el(swfID)['player']; var msg = 'FLASH: '+err; if (err == 'srcnotfound') { player.error({ code: 4, message: msg }); // errors we haven't categorized into the media errors } else { player.error(msg); } }; // Flash Version Check vjs.Flash.version = function(){ var version = '0,0,0'; // IE try { version = new window.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 vjs.Flash.embed = function(swf, placeHolder, flashVars, params, attributes){ var code = vjs.Flash.getEmbedCode(swf, flashVars, params, attributes), // Get element by embedding code and retrieving created element obj = vjs.createEl('div', { innerHTML: code }).childNodes[0], par = placeHolder.parentNode ; placeHolder.parentNode.replaceChild(obj, placeHolder); // IE6 seems to have an issue where it won't initialize the swf object after injecting it. // This is a dumb fix var newObj = par.childNodes[0]; setTimeout(function(){ newObj.style.display = 'block'; }, 1000); return obj; }; vjs.Flash.getEmbedCode = function(swf, flashVars, params, attributes){ var objTag = '<object type="application/x-shockwave-flash"', flashVarsString = '', paramsString = '', attrsString = ''; // Convert flash vars to string if (flashVars) { vjs.obj.each(flashVars, function(key, val){ flashVarsString += (key + '=' + val + '&amp;'); }); } // Add swf, flashVars, and other default params params = vjs.obj.merge({ '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 vjs.obj.each(params, function(key, val){ paramsString += '<param name="'+key+'" value="'+val+'" />'; }); attributes = vjs.obj.merge({ // 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 vjs.obj.each(attributes, function(key, val){ attrsString += (key + '="' + val + '" '); }); return objTag + attrsString + '>' + paramsString + '</object>'; }; vjs.Flash.streamFromParts = function(connection, stream) { return connection + '&' + stream; }; vjs.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; 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; }; vjs.Flash.isStreamingType = function(srcType) { return srcType in vjs.Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid vjs.Flash.RTMP_RE = /^rtmp[set]?:\/\//i; vjs.Flash.isStreamingSrc = function(src) { return vjs.Flash.RTMP_RE.test(src); }; /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @constructor */ vjs.MediaLoader = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!player.options_['sources'] || player.options_['sources'].length === 0) { for (var i=0,j=player.options_['techOrder']; i<j.length; i++) { var techName = vjs.capitalize(j[i]), tech = window['videojs'][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(player.options_['sources']); } } }); /** * @fileoverview Text Tracks * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impared * Subtitles - text displayed over the video for those who don't understand langauge 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 */ // Player Additions - Functions add to the player object for easier access to tracks /** * List of associated text tracks * @type {Array} * @private */ vjs.Player.prototype.textTracks_; /** * 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 * @private */ vjs.Player.prototype.textTracks = function(){ this.textTracks_ = this.textTracks_ || []; return this.textTracks_; }; /** * 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 * @param {Object=} options Additional track options, like src * @private */ vjs.Player.prototype.addTextTrack = function(kind, label, language, options){ var tracks = this.textTracks_ = this.textTracks_ || []; options = options || {}; options['kind'] = kind; options['label'] = label; options['language'] = language; // HTML5 Spec says default to subtitles. // Uppercase first letter to match class names var Kind = vjs.capitalize(kind || 'subtitles'); // Create correct texttrack class. CaptionsTrack, etc. var track = new window['videojs'][Kind + 'Track'](this, options); tracks.push(track); // If track.dflt() is set, start showing immediately // TODO: Add a process to deterime the best track to show for the specific kind // Incase there are mulitple defaulted tracks of the same kind // Or the user has a set preference of a specific language that should override the default // Note: The setTimeout is a workaround because with the html5 tech, the player is 'ready' // before it's child components (including the textTrackDisplay) have finished loading. if (track.dflt()) { this.ready(function(){ setTimeout(function(){ track.player().showTextTrack(track.id()); }, 0); }); } return track; }; /** * Add an array of text tracks. captions, subtitles, chapters, descriptions * Track objects will be stored in the player.textTracks() array * @param {Array} trackList Array of track elements or objects (fake track elements) * @private */ vjs.Player.prototype.addTextTracks = function(trackList){ var trackObj; for (var i = 0; i < trackList.length; i++) { trackObj = trackList[i]; this.addTextTrack(trackObj['kind'], trackObj['label'], trackObj['language'], trackObj); } return this; }; // Show a text track // disableSameKind: disable all other tracks of the same kind. Value should be a track kind (captions, etc.) vjs.Player.prototype.showTextTrack = function(id, disableSameKind){ var tracks = this.textTracks_, i = 0, j = tracks.length, track, showTrack, kind; // Find Track with same ID for (;i<j;i++) { track = tracks[i]; if (track.id() === id) { track.show(); showTrack = track; // Disable tracks of the same kind } else if (disableSameKind && track.kind() == disableSameKind && track.mode() > 0) { track.disable(); } } // Get track kind from shown track or disableSameKind kind = (showTrack) ? showTrack.kind() : ((disableSameKind) ? disableSameKind : false); // Trigger trackchange event, captionstrackchange, subtitlestrackchange, etc. if (kind) { this.trigger(kind+'trackchange'); } return this; }; /** * The base class for all text tracks * * Handles the parsing, hiding, and showing of text track cues * * @param {vjs.Player|Object} player * @param {Object=} options * @constructor */ vjs.TextTrack = vjs.Component.extend({ /** @constructor */ init: function(player, options){ vjs.Component.call(this, player, options); // Apply track info to track object // Options will often be a track element // Build ID if one doesn't exist this.id_ = options['id'] || ('vjs_' + options['kind'] + '_' + options['language'] + '_' + vjs.guid++); this.src_ = options['src']; // 'default' is a reserved keyword in js so we use an abbreviated version this.dflt_ = options['default'] || options['dflt']; this.title_ = options['title']; this.language_ = options['srclang']; this.label_ = options['label']; this.cues_ = []; this.activeCues_ = []; this.readyState_ = 0; this.mode_ = 0; } }); /** * Track kind value. Captions, subtitles, etc. * @private */ vjs.TextTrack.prototype.kind_; /** * Get the track kind value * @return {String} */ vjs.TextTrack.prototype.kind = function(){ return this.kind_; }; /** * Track src value * @private */ vjs.TextTrack.prototype.src_; /** * Get the track src value * @return {String} */ vjs.TextTrack.prototype.src = function(){ return this.src_; }; /** * Track default value * If default is used, subtitles/captions to start showing * @private */ vjs.TextTrack.prototype.dflt_; /** * Get the track default value. ('default' is a reserved keyword) * @return {Boolean} */ vjs.TextTrack.prototype.dflt = function(){ return this.dflt_; }; /** * Track title value * @private */ vjs.TextTrack.prototype.title_; /** * Get the track title value * @return {String} */ vjs.TextTrack.prototype.title = function(){ return this.title_; }; /** * Language - two letter string to represent track language, e.g. 'en' for English * Spec def: readonly attribute DOMString language; * @private */ vjs.TextTrack.prototype.language_; /** * Get the track language value * @return {String} */ vjs.TextTrack.prototype.language = function(){ return this.language_; }; /** * Track label e.g. 'English' * Spec def: readonly attribute DOMString label; * @private */ vjs.TextTrack.prototype.label_; /** * Get the track label value * @return {String} */ vjs.TextTrack.prototype.label = function(){ return this.label_; }; /** * All cues of the track. Cues have a startTime, endTime, text, and other properties. * Spec def: readonly attribute TextTrackCueList cues; * @private */ vjs.TextTrack.prototype.cues_; /** * Get the track cues * @return {Array} */ vjs.TextTrack.prototype.cues = function(){ return this.cues_; }; /** * ActiveCues is all cues that are currently showing * Spec def: readonly attribute TextTrackCueList activeCues; * @private */ vjs.TextTrack.prototype.activeCues_; /** * Get the track active cues * @return {Array} */ vjs.TextTrack.prototype.activeCues = function(){ return this.activeCues_; }; /** * ReadyState describes if the text file has been loaded * const unsigned short NONE = 0; * const unsigned short LOADING = 1; * const unsigned short LOADED = 2; * const unsigned short ERROR = 3; * readonly attribute unsigned short readyState; * @private */ vjs.TextTrack.prototype.readyState_; /** * Get the track readyState * @return {Number} */ vjs.TextTrack.prototype.readyState = function(){ return this.readyState_; }; /** * Mode describes if the track is showing, hidden, or disabled * const unsigned short OFF = 0; * const unsigned short HIDDEN = 1; (still triggering cuechange events, but not visible) * const unsigned short SHOWING = 2; * attribute unsigned short mode; * @private */ vjs.TextTrack.prototype.mode_; /** * Get the track mode * @return {Number} */ vjs.TextTrack.prototype.mode = function(){ return this.mode_; }; /** * Create basic div to hold cue text * @return {Element} */ vjs.TextTrack.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-' + this.kind_ + ' vjs-text-track' }); }; /** * Show: Mode Showing (2) * Indicates that the text track is active. If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly. * In addition, for text tracks whose kind is subtitles or captions, the cues are being displayed over the video as appropriate; * for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion; * and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue. * The showing by default state is used in conjunction with the default attribute on track elements to indicate that the text track was enabled due to that attribute. * This allows the user agent to override the state if a later track is discovered that is more appropriate per the user's preferences. */ vjs.TextTrack.prototype.show = function(){ this.activate(); this.mode_ = 2; // Show element. vjs.Component.prototype.show.call(this); }; /** * Hide: Mode Hidden (1) * Indicates that the text track is active, but that the user agent is not actively displaying the cues. * If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * The user agent is maintaining a list of which cues are active, and events are being fired accordingly. */ vjs.TextTrack.prototype.hide = function(){ // When hidden, cues are still triggered. Disable to stop triggering. this.activate(); this.mode_ = 1; // Hide element. vjs.Component.prototype.hide.call(this); }; /** * Disable: Mode Off/Disable (0) * Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track. * No cues are active, no events are fired, and the user agent will not attempt to obtain the track's cues. */ vjs.TextTrack.prototype.disable = function(){ // If showing, hide. if (this.mode_ == 2) { this.hide(); } // Stop triggering cues this.deactivate(); // Switch Mode to Off this.mode_ = 0; }; /** * Turn on cue tracking. Tracks that are showing OR hidden are active. */ vjs.TextTrack.prototype.activate = function(){ // Load text file if it hasn't been yet. if (this.readyState_ === 0) { this.load(); } // Only activate if not already active. if (this.mode_ === 0) { // Update current cue on timeupdate // Using unique ID for bind function so other tracks don't remove listener this.player_.on('timeupdate', vjs.bind(this, this.update, this.id_)); // Reset cue time on media end this.player_.on('ended', vjs.bind(this, this.reset, this.id_)); // Add to display if (this.kind_ === 'captions' || this.kind_ === 'subtitles') { this.player_.getChild('textTrackDisplay').addChild(this); } } }; /** * Turn off cue tracking. */ vjs.TextTrack.prototype.deactivate = function(){ // Using unique ID for bind function so other tracks don't remove listener this.player_.off('timeupdate', vjs.bind(this, this.update, this.id_)); this.player_.off('ended', vjs.bind(this, this.reset, this.id_)); this.reset(); // Reset // Remove from display this.player_.getChild('textTrackDisplay').removeChild(this); }; // A readiness state // One of the following: // // Not loaded // Indicates that the text track is known to exist (e.g. it has been declared with a track element), but its cues have not been obtained. // // Loading // Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track. // // Loaded // Indicates that the text track has been loaded with no fatal errors. No new cues will be added to the track except if the text track corresponds to a MutableTextTrack object. // // Failed to load // Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g. URL could not be resolved, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained. vjs.TextTrack.prototype.load = function(){ // Only load if not loaded yet. if (this.readyState_ === 0) { this.readyState_ = 1; vjs.get(this.src_, vjs.bind(this, this.parseCues), vjs.bind(this, this.onError)); } }; vjs.TextTrack.prototype.onError = function(err){ this.error = err; this.readyState_ = 3; this.trigger('error'); }; // Parse the WebVTT text format for cue times. // TODO: Separate parser into own class so alternative timed text formats can be used. (TTML, DFXP) vjs.TextTrack.prototype.parseCues = function(srcContent) { var cue, time, text, lines = srcContent.split('\n'), line = '', id; for (var i=1, j=lines.length; i<j; i++) { // Line 0 should be 'WEBVTT', so skipping i=0 line = vjs.trim(lines[i]); // Trim whitespace and linebreaks if (line) { // Loop until a line with content // First line could be an optional cue ID // Check if line has the time separator if (line.indexOf('-->') == -1) { id = line; // Advance to next line for timing. line = vjs.trim(lines[++i]); } else { id = this.cues_.length; } // First line - Number cue = { id: id, // Cue Number index: this.cues_.length // Position in Array }; // Timing line time = line.split(/[\t ]+/); cue.startTime = this.parseCueTime(time[0]); cue.endTime = this.parseCueTime(time[2]); // Additional lines - Cue Text text = []; // Loop until a blank line or end of lines // Assumeing trim('') returns false for blank lines while (lines[++i] && (line = vjs.trim(lines[i]))) { text.push(line); } cue.text = text.join('<br/>'); // Add this cue this.cues_.push(cue); } } this.readyState_ = 2; this.trigger('loaded'); }; vjs.TextTrack.prototype.parseCueTime = function(timeText) { var parts = timeText.split(':'), time = 0, hours, minutes, other, seconds, ms; // Check if optional hours place is included // 00:00:00.000 vs. 00:00.000 if (parts.length == 3) { hours = parts[0]; minutes = parts[1]; other = parts[2]; } else { hours = 0; minutes = parts[0]; other = parts[1]; } // Break other (seconds, milliseconds, and flags) by spaces // TODO: Make additional cue layout settings work with flags other = other.split(/\s+/); // Remove seconds. Seconds is the first part before any spaces. seconds = other.splice(0,1)[0]; // Could use either . or , for decimal seconds = seconds.split(/\.|,/); // Get milliseconds ms = parseFloat(seconds[1]); seconds = seconds[0]; // hours => seconds time += parseFloat(hours) * 3600; // minutes => seconds time += parseFloat(minutes) * 60; // Add seconds time += parseFloat(seconds); // Add milliseconds if (ms) { time += ms/1000; } return time; }; // Update active cues whenever timeupdate events are triggered on the player. vjs.TextTrack.prototype.update = function(){ if (this.cues_.length > 0) { // Get current player time, adjust for track offset var offset = this.player_.options()['trackTimeOffset'] || 0; var time = this.player_.currentTime() + offset; // Check if the new time is outside the time box created by the the last update. if (this.prevChange === undefined || time < this.prevChange || this.nextChange <= time) { var cues = this.cues_, // Create a new time box for this state. newNextChange = this.player_.duration(), // Start at beginning of the timeline newPrevChange = 0, // Start at end reverse = false, // Set the direction of the loop through the cues. Optimized the cue check. newCues = [], // Store new active cues. // Store where in the loop the current active cues are, to provide a smart starting point for the next loop. firstActiveIndex, lastActiveIndex, cue, i; // Loop vars // Check if time is going forwards or backwards (scrubbing/rewinding) // If we know the direction we can optimize the starting position and direction of the loop through the cues array. if (time >= this.nextChange || this.nextChange === undefined) { // NextChange should happen // Forwards, so start at the index of the first active cue and loop forward i = (this.firstActiveIndex !== undefined) ? this.firstActiveIndex : 0; } else { // Backwards, so start at the index of the last active cue and loop backward reverse = true; i = (this.lastActiveIndex !== undefined) ? this.lastActiveIndex : cues.length - 1; } while (true) { // Loop until broken cue = cues[i]; // Cue ended at this point if (cue.endTime <= time) { newPrevChange = Math.max(newPrevChange, cue.endTime); if (cue.active) { cue.active = false; } // No earlier cues should have an active start time. // Nevermind. Assume first cue could have a duration the same as the video. // In that case we need to loop all the way back to the beginning. // if (reverse && cue.startTime) { break; } // Cue hasn't started } else if (time < cue.startTime) { newNextChange = Math.min(newNextChange, cue.startTime); if (cue.active) { cue.active = false; } // No later cues should have an active start time. if (!reverse) { break; } // Cue is current } else { if (reverse) { // Add cue to front of array to keep in time order newCues.splice(0,0,cue); // If in reverse, the first current cue is our lastActiveCue if (lastActiveIndex === undefined) { lastActiveIndex = i; } firstActiveIndex = i; } else { // Add cue to end of array newCues.push(cue); // If forward, the first current cue is our firstActiveIndex if (firstActiveIndex === undefined) { firstActiveIndex = i; } lastActiveIndex = i; } newNextChange = Math.min(newNextChange, cue.endTime); newPrevChange = Math.max(newPrevChange, cue.startTime); cue.active = true; } if (reverse) { // Reverse down the array of cues, break if at first if (i === 0) { break; } else { i--; } } else { // Walk up the array fo cues, break if at last if (i === cues.length - 1) { break; } else { i++; } } } this.activeCues_ = newCues; this.nextChange = newNextChange; this.prevChange = newPrevChange; this.firstActiveIndex = firstActiveIndex; this.lastActiveIndex = lastActiveIndex; this.updateDisplay(); this.trigger('cuechange'); } } }; // Add cue HTML to display vjs.TextTrack.prototype.updateDisplay = function(){ var cues = this.activeCues_, html = '', i=0,j=cues.length; for (;i<j;i++) { html += '<span class="vjs-tt-cue">'+cues[i].text+'</span>'; } this.el_.innerHTML = html; }; // Set all loop helper values back vjs.TextTrack.prototype.reset = function(){ this.nextChange = 0; this.prevChange = this.player_.duration(); this.firstActiveIndex = 0; this.lastActiveIndex = 0; }; // Create specific track types /** * The track component for managing the hiding and showing of captions * * @constructor */ vjs.CaptionsTrack = vjs.TextTrack.extend(); vjs.CaptionsTrack.prototype.kind_ = 'captions'; // Exporting here because Track creation requires the track kind // to be available on global object. e.g. new window['videojs'][Kind + 'Track'] /** * The track component for managing the hiding and showing of subtitles * * @constructor */ vjs.SubtitlesTrack = vjs.TextTrack.extend(); vjs.SubtitlesTrack.prototype.kind_ = 'subtitles'; /** * The track component for managing the hiding and showing of chapters * * @constructor */ vjs.ChaptersTrack = vjs.TextTrack.extend(); vjs.ChaptersTrack.prototype.kind_ = 'chapters'; /* Text Track Display ============================================================================= */ // Global container for both subtitle and captions text. Simple div container. /** * The component for displaying text track cues * * @constructor */ vjs.TextTrackDisplay = vjs.Component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.Component.call(this, player, options, ready); // 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. if (player.options_['tracks'] && player.options_['tracks'].length > 0) { this.player_.addTextTracks(player.options_['tracks']); } } }); vjs.TextTrackDisplay.prototype.createEl = function(){ return vjs.Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * The specific menu item type for selecting a language within a text track kind * * @constructor */ vjs.TextTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track']; // Modify options for parent MenuItem class's init. options['label'] = track.label(); options['selected'] = track.dflt(); vjs.MenuItem.call(this, player, options); this.on(player, track.kind() + 'trackchange', this.update); } }); vjs.TextTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.showTextTrack(this.track.id_, this.track.kind()); }; vjs.TextTrackMenuItem.prototype.update = function(){ this.selected(this.track.mode() == 2); }; /** * A special menu item for turning of a specific type of text track * * @constructor */ vjs.OffTextTrackMenuItem = vjs.TextTrackMenuItem.extend({ /** @constructor */ init: function(player, options){ // Create pseudo track info // Requires options['kind'] options['track'] = { kind: function() { return options['kind']; }, player: player, label: function(){ return options['kind'] + ' off'; }, dflt: function(){ return false; }, mode: function(){ return false; } }; vjs.TextTrackMenuItem.call(this, player, options); this.selected(true); } }); vjs.OffTextTrackMenuItem.prototype.onClick = function(){ vjs.TextTrackMenuItem.prototype.onClick.call(this); this.player_.showTextTrack(this.track.id_, this.track.kind()); }; vjs.OffTextTrackMenuItem.prototype.update = function(){ var tracks = this.player_.textTracks(), i=0, j=tracks.length, track, off = true; for (;i<j;i++) { track = tracks[i]; if (track.kind() == this.track.kind() && track.mode() == 2) { off = false; } } this.selected(off); }; /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @constructor */ vjs.TextTrackButton = vjs.MenuButton.extend({ /** @constructor */ init: function(player, options){ vjs.MenuButton.call(this, player, options); if (this.items.length <= 1) { this.hide(); } } }); // vjs.TextTrackButton.prototype.buttonPressed = false; // vjs.TextTrackButton.prototype.createMenu = function(){ // var menu = new vjs.Menu(this.player_); // // Add a title list item to the top // // menu.el().appendChild(vjs.createEl('li', { // // className: 'vjs-menu-title', // // innerHTML: vjs.capitalize(this.kind_), // // tabindex: -1 // // })); // this.items = this.createItems(); // // Add menu items to the menu // for (var i = 0; i < this.items.length; i++) { // menu.addItem(this.items[i]); // } // // Add list to element // this.addChild(menu); // return menu; // }; // Create a menu item for each text track vjs.TextTrackButton.prototype.createItems = function(){ var items = [], track; // Add an OFF menu item to turn all tracks off items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ })); for (var i = 0; i < this.player_.textTracks().length; i++) { track = this.player_.textTracks()[i]; if (track.kind() === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; /** * The button component for toggling and selecting captions * * @constructor */ vjs.CaptionsButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Captions Menu'); } }); vjs.CaptionsButton.prototype.kind_ = 'captions'; vjs.CaptionsButton.prototype.buttonText = 'Captions'; vjs.CaptionsButton.prototype.className = 'vjs-captions-button'; /** * The button component for toggling and selecting subtitles * * @constructor */ vjs.SubtitlesButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Subtitles Menu'); } }); vjs.SubtitlesButton.prototype.kind_ = 'subtitles'; vjs.SubtitlesButton.prototype.buttonText = 'Subtitles'; vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button'; // Chapters act much differently than other text tracks // Cues are navigation vs. other tracks of alternative languages /** * The button component for toggling and selecting chapters * * @constructor */ vjs.ChaptersButton = vjs.TextTrackButton.extend({ /** @constructor */ init: function(player, options, ready){ vjs.TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label','Chapters Menu'); } }); vjs.ChaptersButton.prototype.kind_ = 'chapters'; vjs.ChaptersButton.prototype.buttonText = 'Chapters'; vjs.ChaptersButton.prototype.className = 'vjs-chapters-button'; // Create a menu item for each text track vjs.ChaptersButton.prototype.createItems = function(){ var items = [], track; for (var i = 0; i < this.player_.textTracks().length; i++) { track = this.player_.textTracks()[i]; if (track.kind() === this.kind_) { items.push(new vjs.TextTrackMenuItem(this.player_, { 'track': track })); } } return items; }; vjs.ChaptersButton.prototype.createMenu = function(){ var tracks = this.player_.textTracks(), i = 0, j = tracks.length, track, chaptersTrack, items = this.items = []; for (;i<j;i++) { track = tracks[i]; if (track.kind() == this.kind_) { if (track.readyState() === 0) { track.load(); track.on('loaded', vjs.bind(this, this.createMenu)); } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new vjs.Menu(this.player_); menu.contentEl().appendChild(vjs.createEl('li', { className: 'vjs-menu-title', innerHTML: vjs.capitalize(this.kind_), tabindex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack.cues_, cue, mi; i = 0; j = cues.length; for (;i<j;i++) { cue = cues[i]; mi = new vjs.ChaptersTrackMenuItem(this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; /** * @constructor */ vjs.ChaptersTrackMenuItem = vjs.MenuItem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], cue = this.cue = options['cue'], currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = (cue.startTime <= currentTime && currentTime < cue.endTime); vjs.MenuItem.call(this, player, options); track.on('cuechange', vjs.bind(this, this.update)); } }); vjs.ChaptersTrackMenuItem.prototype.onClick = function(){ vjs.MenuItem.prototype.onClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; vjs.ChaptersTrackMenuItem.prototype.update = function(){ var cue = this.cue, currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue.startTime <= currentTime && currentTime < cue.endTime); }; // Add Buttons to controlBar vjs.obj.merge(vjs.ControlBar.prototype.options_['children'], { 'subtitlesButton': {}, 'captionsButton': {}, 'chaptersButton': {} }); // vjs.Cue = vjs.Component.extend({ // /** @constructor */ // init: function(player, options){ // vjs.Component.call(this, player, options); // } // }); /** * @fileoverview Add JSON support * @suppress {undefinedVars} * (Compiler doesn't like JSON not being declared) */ /** * Javascript JSON implementation * (Parse Method Only) * https://github.com/douglascrockford/JSON-js/blob/master/json2.js * Only using for parse method when parsing data-setup attribute JSON. * @suppress {undefinedVars} * @namespace * @private */ vjs.JSON; if (typeof window.JSON !== 'undefined' && typeof window.JSON.parse === 'function') { vjs.JSON = window.JSON; } else { vjs.JSON = {}; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; /** * parse the json * * @memberof vjs.JSON * @param {String} text The JSON string to parse * @param {Function=} [reviver] Optional function that can transform the results * @return {Object|Array} The parsed JSON */ vjs.JSON.parse = function (text, reviver) { var j; function walk(holder, key) { 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); } 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); }); } 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, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new SyntaxError('JSON.parse(): invalid or malformed JSON data'); }; } /** * @fileoverview Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ // Automatically set up any tags that have a data-setup attribute vjs.autoSetup = function(){ var options, mediaEl, player, i, e; // 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 = document.getElementsByTagName('video'); var audios = document.getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for(i=0, e=vids.length; i<e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for(i=0, e=audios.length; i<e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (i=0,e=mediaEls.length; i<e; i++) { 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) { 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. player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { vjs.autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!vjs.windowLoaded) { vjs.autoSetupTimeout(1); } }; // Pause to let the DOM keep processing vjs.autoSetupTimeout = function(wait){ setTimeout(vjs.autoSetup, wait); }; if (document.readyState === 'complete') { vjs.windowLoaded = true; } else { vjs.one(window, 'load', function(){ vjs.windowLoaded = true; }); } // 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) vjs.autoSetupTimeout(1); /** * 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 */ vjs.plugin = function(name, init){ vjs.Player.prototype[name] = init; };
packages/material-ui-icons/src/AirlineSeatReclineExtraTwoTone.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M5.35 5.64c-.9-.64-1.12-1.88-.49-2.79.63-.9 1.88-1.12 2.79-.49.9.64 1.12 1.88.49 2.79-.64.9-1.88 1.12-2.79.49zM16 19H8.93c-1.48 0-2.74-1.08-2.96-2.54L4 7H2l1.99 9.76C4.37 19.2 6.47 21 8.94 21H16v-2zm.23-4h-4.88l-1.03-4.1c1.58.89 3.28 1.54 5.15 1.22V9.99c-1.63.31-3.44-.27-4.69-1.25L9.14 7.47c-.23-.18-.49-.3-.76-.38-.32-.09-.66-.12-.99-.06h-.02c-1.23.22-2.05 1.39-1.84 2.61l1.35 5.92C7.16 16.98 8.39 18 9.83 18h6.85l3.82 3 1.5-1.5-5.77-4.5z" /> , 'AirlineSeatReclineExtraTwoTone');
ajax/libs/react-redux/3.0.0-alpha/react-redux.min.js
wil93/cdnjs
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e(require("react"),require("redux")):"function"==typeof define&&define.amd?define(["react","redux"],e):"object"==typeof exports?exports.ReactRedux=e(require("react"),require("redux")):t.ReactRedux=e(t.React,t.Redux)}(this,function(t,e){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var o=r(9),u=n(o),i=r(2),s=n(i),a=s.default(u.default),c=a.Provider,p=a.connect;e.Provider=c,e.connect=p},function(t,e){"use strict";function r(t){return t.shape({subscribe:t.func.isRequired,dispatch:t.func.isRequired,getState:t.func.isRequired})}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function o(t){var e=i.default(t),r=a.default(t);return{Provider:e,connect:r}}e.__esModule=!0,e.default=o;var u=r(4),i=n(u),s=r(3),a=n(s);t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function i(t){return t.displayName||t.name||"Component"}function s(t){var e=t.Component,r=t.PropTypes,n=f.default(r);return function(r,s,p){function f(t,e){var r=t.getState(),n=R?S(r,e):S(r);return g.default(y.default(n),"`mapStateToProps` must return an object. Instead received %s.",n),n}function l(t,e){var r=t.dispatch,n=C?j(r,e):j(r);return g.default(y.default(n),"`mapDispatchToProps` must return an object. Instead received %s.",n),n}function h(t,e,r){var n=O(t,e,r);return g.default(y.default(n),"`mergeProps` must return an object. Instead received %s.",n),n}var b=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],m=Boolean(r),S=r||x,j=y.default(s)?v.default(s):s||P,O=p||_,R=S.length>1,C=j.length>1,M=b.pure,T=void 0===M?!0:M,k=w++;return function(r){var s=function(e){function s(t,r){o(this,s),e.call(this,t,r),this.version=k,this.store=t.store||r.store,g.default(this.store,'Could not find "store" in either the context or '+('props of "'+this.constructor.displayName+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+this.constructor.displayName+'".')),this.stateProps=f(this.store,t),this.dispatchProps=l(this.store,t),this.state={storeState:null},this.updateState()}return u(s,e),s.prototype.shouldComponentUpdate=function(t,e){if(!T)return this.updateState(t),!0;var r=e.storeState!==this.state.storeState,n=!d.default(t,this.props),o=!1,u=!1;return(r||n&&R)&&(o=this.updateStateProps(t)),n&&C&&(u=this.updateDispatchProps(t)),n||o||u?(this.updateState(t),!0):!1},a(s,null,[{key:"displayName",value:"Connect("+i(r)+")",enumerable:!0},{key:"WrappedComponent",value:r,enumerable:!0},{key:"contextTypes",value:{store:n},enumerable:!0},{key:"propTypes",value:{store:n},enumerable:!0}]),s.prototype.computeNextState=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0];return h(this.stateProps,this.dispatchProps,t)},s.prototype.updateStateProps=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],e=f(this.store,t);return d.default(e,this.stateProps)?!1:(this.stateProps=e,!0)},s.prototype.updateDispatchProps=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0],e=l(this.store,t);return d.default(e,this.dispatchProps)?!1:(this.dispatchProps=e,!0)},s.prototype.updateState=function(){var t=arguments.length<=0||void 0===arguments[0]?this.props:arguments[0];this.nextState=this.computeNextState(t)},s.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},s.prototype.trySubscribe=function(){m&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},s.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},s.prototype.componentDidMount=function(){this.trySubscribe()},s.prototype.componentWillUnmount=function(){this.tryUnsubscribe()},s.prototype.handleChange=function(){this.unsubscribe&&this.setState({storeState:this.store.getState()})},s.prototype.getWrappedInstance=function(){return this.refs.wrappedInstance},s.prototype.render=function(){return t.createElement(r,c({ref:"wrappedInstance"},this.nextState))},s}(e);return s}}}e.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}(),c=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}return t};e.default=s;var p=r(1),f=n(p),l=r(6),d=n(l),h=r(5),y=n(h),b=r(7),v=n(b),m=r(8),g=n(m),x=function(){return{}},P=function(t){return{dispatch:t}},_=function(t,e,r){return c({},r,t,e)},w=0;t.exports=e.default},function(t,e,r){"use strict";function n(t){return t&&t.__esModule?t:{"default":t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function u(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function i(t){var e=t.version;if("string"!=typeof e)return!0;var r=e.split("."),n=parseInt(r[0],10),o=parseInt(r[1],10);return 0===n&&13===o}function s(t){function e(){h||d||(h=!0,console.error("With React 0.14 and later versions, you no longer need to wrap <Provider> child into a function."))}function r(){!h&&d&&(h=!0,console.error("With React 0.13, you need to wrap <Provider> child into a function. This restriction will be removed with React 0.14."))}function n(){y||(y=!0,console.error("<Provider> does not support changing `store` on the fly. It is most likely that you see this error because you updated to Redux 2.x and React Redux 2.x which no longer hot reload reducers automatically. See https://github.com/rackt/react-redux/releases/tag/v2.0.0 for the migration instructions."))}var s=t.Component,c=t.PropTypes,f=t.Children,l=p.default(c),d=i(t),h=!1,y=!1;return function(t){function i(e,r){o(this,i),t.call(this,e,r),this.store=e.store}return u(i,t),i.prototype.getChildContext=function(){return{store:this.store}},a(i,null,[{key:"childContextTypes",value:{store:l.isRequired},enumerable:!0},{key:"propTypes",value:{store:l.isRequired,children:(d?c.func:c.element).isRequired},enumerable:!0}]),i.prototype.componentWillReceiveProps=function(t){var e=this.store,r=t.store;e!==r&&n()},i.prototype.render=function(){var t=this.props.children;return"function"==typeof t?(e(),t=t()):r(),f.only(t)},i}(s)}e.__esModule=!0;var a=function(){function t(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(e,r,n){return r&&t(e.prototype,r),n&&t(e,n),e}}();e.default=s;var c=r(1),p=n(c);t.exports=e.default},function(t,e){"use strict";function r(t){if(!t||"object"!=typeof t)return!1;var e="function"==typeof t.constructor?Object.getPrototypeOf(t):Object.prototype;if(null===e)return!0;var r=e.constructor;return"function"==typeof r&&r instanceof r&&n(r)===n(Object)}e.__esModule=!0,e.default=r;var n=function(t){return Function.prototype.toString.call(t)};t.exports=e.default},function(t,e){"use strict";function r(t,e){if(t===e)return!0;var r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(var o=Object.prototype.hasOwnProperty,u=0;u<r.length;u++)if(!o.call(e,r[u])||t[r[u]]!==e[r[u]])return!1;return!0}e.__esModule=!0,e.default=r,t.exports=e.default},function(t,e,r){"use strict";function n(t){return function(e){return o.bindActionCreators(t,e)}}e.__esModule=!0,e.default=n;var o=r(10);t.exports=e.default},function(t,e,r){"use strict";var n=function(t,e,r,n,o,u,i,s){if(!t){var a;if(void 0===e)a=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,n,o,u,i,s],p=0;a=new Error("Invariant Violation: "+e.replace(/%s/g,function(){return c[p++]}))}throw a.framesToPop=1,a}};t.exports=n},function(e,r){e.exports=t},function(t,r){t.exports=e}])});
packages/icons/src/dv/Database.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function DvDatabase(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M24 44c-9.465 0-17.144-2.56-17.144-5.715v-5.714c0-.496.25-.97.607-1.428 1.911 2.46 8.557 4.285 16.537 4.285 7.98 0 14.626-1.824 16.537-4.285.358.46.605.932.605 1.428v5.714c0 3.153-7.679 5.715-17.143 5.715zm17.144-22.858v5.714c0 3.153-7.68 5.715-17.144 5.715-9.464 0-17.144-2.562-17.144-5.715v-5.714c.024-.565.32-1.041.607-1.43 1.911 2.46 8.557 4.285 16.537 4.285 7.98 0 14.626-1.826 16.537-4.285.337.464.594.939.607 1.43zm-17.146.002c-9.464 0-17.142-2.56-17.142-5.715V9.715C6.856 6.56 14.534 4 23.998 4 33.463 4 41.14 6.56 41.14 9.715v5.714c0 3.154-7.677 5.715-17.142 5.715zM35.426 9.716c0-2.191-9.553-3.568-17.154-2.472-7.601 1.095-7.601 3.85 0 4.945 7.6 1.096 17.154-.281 17.154-2.473z" /> </IconBase> ); } export default DvDatabase;
lib/angular-1.1.5/angular-scenario.js
SmilingJoe/ui-router
/*! * jQuery JavaScript Library v1.8.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time) */ (function( window, undefined ) { 'use strict'; 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.2", // 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" && ( !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"); // Preliminary tests div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Can't get basic test support if ( !all || !all.length ) { return {}; } // First batch of supports tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; 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, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (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 ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } 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() ]; } 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 ]; if ( !pattern ) { pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") ); } return 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); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length, argument ) { 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, i = 1; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 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 ) { soFar = soFar.slice( match[0].length ); } 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 ] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[ type ]( match, document, true ))) ) { 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 ) { // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if ( seed && postFinder ) { return; } var i, elem, postFilterIn, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [], seed ), // 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 ) { postFilterIn = condense( matcherOut, postMap ); postFilter( postFilterIn, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while ( i-- ) { if ( (elem = postFilterIn[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } // Keep seed and results synchronized if ( seed ) { // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { seed[ preMap[i] ] = !(results[ preMap[i] ] = elem); } } } 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 { // The concatenated values are (context, xml) for backCompat 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, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } 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), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"], // matchesSelector(:focus) reports false when true (Chrome 21), // 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", ":focus" ], 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 || !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 || !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 = {}, 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 ) { ret = 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() ) || false; s.crossDomain = parts && ( parts.join(":") + ( parts[ 3 ] ? "" : parts[ 1 ] === "http:" ? 80 : 443 ) ) !== ( ajaxLocParts.join(":") + ( 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( _ ) { } // 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 ), percent = 1 - ( remaining / animation.duration || 0 ), 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, 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 ]; 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 ) { 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; 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(); } }; 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 ); /** * @license AngularJS v1.1.5 * (c) 2010-2012 Google, Inc. http://angularjs.org * License: MIT */ (function(window, document){ var _jQuery = window.jQuery.noConflict(true); //////////////////////////////////// /** * @ngdoc function * @name angular.lowercase * @function * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; /** * @ngdoc function * @name angular.uppercase * @function * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; var manualLowercase = function(s) { return isString(s) ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) : s; }; var manualUppercase = function(s) { return isString(s) ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) : s; }; // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods // with correct but slower alternatives. if ('i' !== 'I'.toLowerCase()) { lowercase = manualLowercase; uppercase = manualUppercase; } var /** holds major version number for IE or NaN for real browsers */ msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]), jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, push = [].push, toString = Object.prototype.toString, _angular = window.angular, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, nodeName_, uid = ['0', '0', '0']; /** * @ngdoc function * @name angular.noConflict * @function * * @description * Restores the previous global value of angular and returns the current instance. Other libraries may already use the * angular namespace. Or a previous version of angular is already loaded on the page. In these cases you may want to * restore the previous namespace and keep a reference to angular. * * @return {Object} The current angular namespace */ function noConflict() { var a = window.angular; window.angular = _angular; return a; } /** * @private * @param {*} obj * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...) */ function isArrayLike(obj) { if (!obj || (typeof obj.length !== 'number')) return false; // We have on object which has length property. Should we treat it as array? if (typeof obj.hasOwnProperty != 'function' && typeof obj.constructor != 'function') { // This is here for IE8: it is a bogus object treat it as array; return true; } else { return obj instanceof JQLite || // JQLite (jQuery && obj instanceof jQuery) || // jQuery toString.call(obj) !== '[object Object]' || // some browser native object typeof obj.callee === 'function'; // arguments (on IE8 looks like regular obj) } } /** * @ngdoc function * @name angular.forEach * @function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` * is the value of an object property or an array element and `key` is the object property key or * array element index. Specifying a `context` for the function is optional. * * Note: this function was previously known as `angular.foreach`. * <pre> var values = {name: 'misko', gender: 'male'}; var log = []; angular.forEach(values, function(value, key){ this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender:male']); </pre> * * @param {Object|Array} obj Object to iterate over. * @param {Function} iterator Iterator function. * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ function forEach(obj, iterator, context) { var key; if (obj) { if (isFunction(obj)){ for (key in obj) { if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context); } else if (isArrayLike(obj)) { for (key = 0; key < obj.length; key++) iterator.call(context, obj[key], key); } else { for (key in obj) { if (obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key); } } } } return obj; } function sortedKeys(obj) { var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key); } } return keys.sort(); } function forEachSorted(obj, iterator, context) { var keys = sortedKeys(obj); for ( var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; } /** * when using forEach the params are value, key, but it is often useful to have key, value. * @param {function(string, *)} iteratorFn * @returns {function(*, string)} */ function reverseParams(iteratorFn) { return function(value, key) { iteratorFn(key, value) }; } /** * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric * characters such as '012ABC'. The reason why we are not using simply a number counter is that * the number string gets longer over time, and it can also overflow, where as the nextId * will grow much slower, it is a string, and it will never overflow. * * @returns an unique alpha-numeric string */ function nextUid() { var index = uid.length; var digit; while(index) { index--; digit = uid[index].charCodeAt(0); if (digit == 57 /*'9'*/) { uid[index] = 'A'; return uid.join(''); } if (digit == 90 /*'Z'*/) { uid[index] = '0'; } else { uid[index] = String.fromCharCode(digit + 1); return uid.join(''); } } uid.unshift('0'); return uid.join(''); } /** * Set or clear the hashkey for an object. * @param obj object * @param h the hashkey (!truthy to delete the hashkey) */ function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; } else { delete obj.$$hashKey; } } /** * @ngdoc function * @name angular.extend * @function * * @description * Extends the destination object `dst` by copying all of the properties from the `src` object(s) * to `dst`. You can specify multiple `src` objects. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { var h = dst.$$hashKey; forEach(arguments, function(obj){ if (obj !== dst) { forEach(obj, function(value, key){ dst[key] = value; }); } }); setHashKey(dst,h); return dst; } function int(str) { return parseInt(str, 10); } function inherit(parent, extra) { return extend(new (extend(function() {}, {prototype:parent}))(), extra); } var START_SPACE = /^\s*/; var END_SPACE = /\s*$/; function stripWhitespace(str) { return isString(str) ? str.replace(START_SPACE, '').replace(END_SPACE, '') : str; } /** * @ngdoc function * @name angular.noop * @function * * @description * A function that performs no operations. This function can be useful when writing code in the * functional style. <pre> function foo(callback) { var result = calculateResult(); (callback || angular.noop)(result); } </pre> */ function noop() {} noop.$inject = []; /** * @ngdoc function * @name angular.identity * @function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * <pre> function transformer(transformationFn, value) { return (transformationFn || identity)(value); }; </pre> */ function identity($) {return $;} identity.$inject = []; function valueFn(value) {return function() {return value;};} /** * @ngdoc function * @name angular.isUndefined * @function * * @description * Determines if a reference is undefined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ function isUndefined(value){return typeof value == 'undefined';} /** * @ngdoc function * @name angular.isDefined * @function * * @description * Determines if a reference is defined. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ function isDefined(value){return typeof value != 'undefined';} /** * @ngdoc function * @name angular.isObject * @function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not * considered to be objects. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ function isObject(value){return value != null && typeof value == 'object';} /** * @ngdoc function * @name angular.isString * @function * * @description * Determines if a reference is a `String`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ function isString(value){return typeof value == 'string';} /** * @ngdoc function * @name angular.isNumber * @function * * @description * Determines if a reference is a `Number`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ function isNumber(value){return typeof value == 'number';} /** * @ngdoc function * @name angular.isDate * @function * * @description * Determines if a value is a date. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ function isDate(value){ return toString.apply(value) == '[object Date]'; } /** * @ngdoc function * @name angular.isArray * @function * * @description * Determines if a reference is an `Array`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ function isArray(value) { return toString.apply(value) == '[object Array]'; } /** * @ngdoc function * @name angular.isFunction * @function * * @description * Determines if a reference is a `Function`. * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ function isFunction(value){return typeof value == 'function';} /** * Checks if `obj` is a window object. * * @private * @param {*} obj Object to check * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { return obj && obj.document && obj.location && obj.alert && obj.setInterval; } function isScope(obj) { return obj && obj.$evalAsync && obj.$watch; } function isFile(obj) { return toString.apply(obj) === '[object File]'; } function isBoolean(value) { return typeof value == 'boolean'; } function trim(value) { return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value; } /** * @ngdoc function * @name angular.isElement * @function * * @description * Determines if a reference is a DOM element (or wrapped jQuery element). * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element). */ function isElement(node) { return node && (node.nodeName // we are a direct element || (node.bind && node.find)); // we have a bind and find method part of jQuery API } /** * @param str 'key1,key2,...' * @returns {object} in the form of {key1:true, key2:true, ...} */ function makeMap(str){ var obj = {}, items = str.split(","), i; for ( i = 0; i < items.length; i++ ) obj[ items[i] ] = true; return obj; } if (msie < 9) { nodeName_ = function(element) { element = element.nodeName ? element : element[0]; return (element.scopeName && element.scopeName != 'HTML') ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName; }; } else { nodeName_ = function(element) { return element.nodeName ? element.nodeName : element[0].nodeName; }; } function map(obj, iterator, context) { var results = []; forEach(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; } /** * @description * Determines the number of elements in an array, the number of properties an object has, or * the length of a string. * * Note: This function is used to augment the Object type in Angular expressions. See * {@link angular.Object} for more information about Angular arrays. * * @param {Object|Array|string} obj Object, array, or string to inspect. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array. */ function size(obj, ownPropsOnly) { var size = 0, key; if (isArray(obj) || isString(obj)) { return obj.length; } else if (isObject(obj)){ for (key in obj) if (!ownPropsOnly || obj.hasOwnProperty(key)) size++; } return size; } function includes(array, obj) { return indexOf(array, obj) != -1; } function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } function arrayRemove(array, value) { var index = indexOf(array, value); if (index >=0) array.splice(index, 1); return value; } function isLeafNode (node) { if (node) { switch (node.nodeName) { case "OPTION": case "PRE": case "TITLE": return true; } } return false; } /** * @ngdoc function * @name angular.copy * @function * * @description * Creates a deep copy of `source`, which should be an object or an array. * * * If no destination is supplied, a copy of the object or array is created. * * If a destination is provided, all of its elements (for array) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array, `source` is returned. * * Note: this function is used to augment the Object type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {*} source The source that will be used to make a copy. * Can be any type, including primitives, `null`, and `undefined`. * @param {(Object|Array)=} destination Destination into which the source is copied. If * provided, must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. */ function copy(source, destination){ if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope"); if (!destination) { destination = source; if (source) { if (isArray(source)) { destination = copy(source, []); } else if (isDate(source)) { destination = new Date(source.getTime()); } else if (isObject(source)) { destination = copy(source, {}); } } } else { if (source === destination) throw Error("Can't copy equivalent objects or arrays"); if (isArray(source)) { destination.length = 0; for ( var i = 0; i < source.length; i++) { destination.push(copy(source[i])); } } else { var h = destination.$$hashKey; forEach(destination, function(value, key){ delete destination[key]; }); for ( var key in source) { destination[key] = copy(source[key]); } setHashKey(destination,h); } } return destination; } /** * Create a shallow copy of an object */ function shallowCopy(src, dst) { dst = dst || {}; for(var key in src) { if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') { dst[key] = src[key]; } } return dst; } /** * @ngdoc function * @name angular.equals * @function * * @description * Determines if two objects or two values are equivalent. Supports value types, arrays and * objects. * * Two objects or values are considered equivalent if at least one of the following is true: * * * Both objects or values pass `===` comparison. * * Both objects or values are of the same type and all of their properties pass `===` comparison. * * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal) * * During a property comparison, properties of `function` type and properties with names * that begin with `$` are ignored. * * Scope and DOMWindow objects are being compared only by identify (`===`). * * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. */ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; if (t1 == t2) { if (t1 == 'object') { if (isArray(o1)) { if ((length = o1.length) == o2.length) { for(key=0; key<length; key++) { if (!equals(o1[key], o2[key])) return false; } return true; } } else if (isDate(o1)) { return isDate(o2) && o1.getTime() == o2.getTime(); } else { if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false; keySet = {}; for(key in o1) { if (key.charAt(0) === '$' || isFunction(o1[key])) continue; if (!equals(o1[key], o2[key])) return false; keySet[key] = true; } for(key in o2) { if (!keySet[key] && key.charAt(0) !== '$' && o2[key] !== undefined && !isFunction(o2[key])) return false; } return true; } } } return false; } function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); } function sliceArgs(args, startIndex) { return slice.call(args, startIndex || 0); } /** * @ngdoc function * @name angular.bind * @function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for * `fn`). You can supply optional `args` that are prebound to the function. This feature is also * known as [function currying](http://en.wikipedia.org/wiki/Currying). * * @param {Object} self Context which `fn` should be evaluated in. * @param {function()} fn Function to be bound. * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) : fn.apply(self, curryArgs); } : function() { return arguments.length ? fn.apply(self, arguments) : fn.call(self); }; } else { // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) return fn; } } function toJsonReplacer(key, value) { var val = value; if (/^\$+/.test(key)) { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; } else if (value && document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; } return val; } /** * @ngdoc function * @name angular.toJson * @function * * @description * Serializes input into a JSON-formatted string. * * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. * @returns {string} Jsonified string representing `obj`. */ function toJson(obj, pretty) { return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); } /** * @ngdoc function * @name angular.fromJson * @function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. * @returns {Object|Array|Date|string|number} Deserialized thingy. */ function fromJson(json) { return isString(json) ? JSON.parse(json) : json; } function toBoolean(value) { if (value && value.length !== 0) { var v = lowercase("" + value); value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); } else { value = false; } return value; } /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { element = jqLite(element).clone(); try { // turns out IE does not let you set .html() on elements which // are not allowed to have children. So we just ignore it. element.html(''); } catch(e) {} // As Per DOM Standards var TEXT_NODE = 3; var elemHtml = jqLite('<div>').append(element).html(); try { return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); } catch(e) { return lowercase(elemHtml); } } ///////////////////////////////////////////////// /** * Parses an escaped url query string into key-value pairs. * @returns Object.<(string|boolean)> */ function parseKeyValue(/**string*/keyValue) { var obj = {}, key_value, key; forEach((keyValue || "").split('&'), function(keyValue){ if (keyValue) { key_value = keyValue.split('='); key = decodeURIComponent(key_value[0]); obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true; } }); return obj; } function toKeyValue(obj) { var parts = []; forEach(obj, function(value, key) { parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true))); }); return parts.length ? parts.join('&') : ''; } /** * We need our custom method because encodeURIComponent is too aggressive and doesn't follow * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path * segments: * segment = *pchar * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * pct-encoded = "%" HEXDIG HEXDIG * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriSegment(val) { return encodeUriQuery(val, true). replace(/%26/gi, '&'). replace(/%3D/gi, '='). replace(/%2B/gi, '+'); } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" */ function encodeUriQuery(val, pctEncodeSpaces) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } /** * @ngdoc directive * @name ng.directive:ngApp * * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. * * @description * * Use this directive to auto-bootstrap an application. Only * one directive can be used per HTML document. The directive * designates the root of the application and is typically placed * at the root of the page. * * In the example below if the `ngApp` directive would not be placed * on the `html` element then the document would not be compiled * and the `{{ 1+2 }}` would not be resolved to `3`. * * `ngApp` is the easiest way to bootstrap an application. * <doc:example> <doc:source> I can add: 1 + 2 = {{ 1+2 }} </doc:source> </doc:example> * */ function angularInit(element, bootstrap) { var elements = [element], appElement, module, names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; function append(element) { element && elements.push(element); } forEach(names, function(name) { names[name] = true; append(document.getElementById(name)); name = name.replace(':', '\\:'); if (element.querySelectorAll) { forEach(element.querySelectorAll('.' + name), append); forEach(element.querySelectorAll('.' + name + '\\:'), append); forEach(element.querySelectorAll('[' + name + ']'), append); } }); forEach(elements, function(element) { if (!appElement) { var className = ' ' + element.className + ' '; var match = NG_APP_CLASS_REGEXP.exec(className); if (match) { appElement = element; module = (match[2] || '').replace(/\s+/g, ','); } else { forEach(element.attributes, function(attr) { if (!appElement && names[attr.name]) { appElement = element; module = attr.value; } }); } } }); if (appElement) { bootstrap(appElement, module ? [module] : []); } } /** * @ngdoc function * @name angular.bootstrap * @description * Use this function to manually start up angular application. * * See: {@link guide/bootstrap Bootstrap} * * @param {Element} element DOM element which is the root of angular application. * @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules} * @returns {AUTO.$injector} Returns the newly created injector for this app. */ function bootstrap(element, modules) { var resumeBootstrapInternal = function() { element = jqLite(element); modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); modules.unshift('ng'); var injector = createInjector(modules); injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animator', function(scope, element, compile, injector, animator) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); animator.enabled(true); }] ); return injector; }; var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { return resumeBootstrapInternal(); } window.name = window.name.replace(NG_DEFER_BOOTSTRAP, ''); angular.resumeBootstrap = function(extraModules) { forEach(extraModules, function(module) { modules.push(module); }); resumeBootstrapInternal(); }; } var SNAKE_CASE_REGEXP = /[A-Z]/g; function snake_case(name, separator){ separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } function bindJQuery() { // bind to jQuery if present; jQuery = window.jQuery; // reset to jQuery or default to us. if (jQuery) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, controller: JQLitePrototype.controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); JQLitePatchJQueryRemove('remove', true); JQLitePatchJQueryRemove('empty'); JQLitePatchJQueryRemove('html'); } else { jqLite = JQLite; } angular.element = jqLite; } /** * throw error if the argument is falsy. */ function assertArg(arg, name, reason) { if (!arg) { throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required")); } return arg; } function assertArgFn(arg, name, acceptArrayAnnotation) { if (acceptArrayAnnotation && isArray(arg)) { arg = arg[arg.length - 1]; } assertArg(isFunction(arg), name, 'not a function, got ' + (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } return ensure(ensure(window, 'angular', Object), 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating and registering Angular modules. All * modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * * # Module * * A module is a collocation of services, directives, filters, and configuration information. Module * is used to configure the {@link AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the * the module is being retrieved for further configuration. * @param {Function} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw Error('No module: ' + name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the service. * @description * See {@link AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @methodOf angular.Module * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an animation. * @description * * Defines an animation hook that can be later used with {@link ng.directive:ngAnimate ngAnimate} * alongside {@link ng.directive:ngAnimate#Description common ng directives} as well as custom directives. * <pre> * module.animation('animation-name', function($inject1, $inject2) { * return { * //this gets called in preparation to setup an animation * setup : function(element) { ... }, * * //this gets called once the animation is run * start : function(element, done, memo) { ... } * } * }) * </pre> * * See {@link ng.$animationProvider#register $animationProvider.register()} and * {@link ng.directive:ngAnimate ngAnimate} for more information. */ animation: invokeLater('$animationProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string} name Controller name. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string} name directive name * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; } } }); }; }); } /** * @ngdoc property * @name angular.version * @description * An object that contains information about the current AngularJS version. This object has the * following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". * - `minor` – `{number}` – Minor version number, such as "9". * - `dot` – `{number}` – Dot version number, such as "18". * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { full: '1.1.5', // all of these placeholder strings will be replaced by grunt's major: 1, // package task minor: 1, dot: 5, codeName: 'triangle-squarification' }; function publishExternalAPI(angular){ extend(angular, { 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, 'noop':noop, 'bind':bind, 'toJson': toJson, 'fromJson': fromJson, 'identity':identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, 'isFunction': isFunction, 'isObject': isObject, 'isNumber': isNumber, 'isElement': isElement, 'isArray': isArray, 'version': version, 'isDate': isDate, 'lowercase': lowercase, 'uppercase': uppercase, 'callbacks': {counter: 0}, 'noConflict': noConflict }); angularModule = setupModuleLoader(window); try { angularModule('ngLocale'); } catch (e) { angularModule('ngLocale', []).provider('$locale', $LocaleProvider); } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { $provide.provider('$compile', $CompileProvider). directive({ a: htmlAnchorDirective, input: inputDirective, textarea: inputDirective, form: formDirective, script: scriptDirective, select: selectDirective, style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective, ngBindTemplate: ngBindTemplateDirective, ngClass: ngClassDirective, ngClassEven: ngClassEvenDirective, ngClassOdd: ngClassOddDirective, ngCsp: ngCspDirective, ngCloak: ngCloakDirective, ngController: ngControllerDirective, ngForm: ngFormDirective, ngHide: ngHideDirective, ngIf: ngIfDirective, ngInclude: ngIncludeDirective, ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngSubmit: ngSubmitDirective, ngStyle: ngStyleDirective, ngSwitch: ngSwitchDirective, ngSwitchWhen: ngSwitchWhenDirective, ngSwitchDefault: ngSwitchDefaultDirective, ngOptions: ngOptionsDirective, ngView: ngViewDirective, ngTransclude: ngTranscludeDirective, ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, required: requiredDirective, ngRequired: requiredDirective, ngValue: ngValueDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $animation: $AnimationProvider, $animator: $AnimatorProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, $interpolate: $InterpolateProvider, $http: $HttpProvider, $httpBackend: $HttpBackendProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $route: $RouteProvider, $routeParams: $RouteParamsProvider, $rootScope: $RootScopeProvider, $q: $QProvider, $sniffer: $SnifferProvider, $templateCache: $TemplateCacheProvider, $timeout: $TimeoutProvider, $window: $WindowProvider }); } ]); } ////////////////////////////////// //JQLite ////////////////////////////////// /** * @ngdoc function * @name angular.element * @function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if * jQuery is available, or a function that wraps the element or string in Angular's jQuery lite * implementation (commonly referred to as jqLite). * * Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded` * event fired. * * jqLite is a tiny, API-compatible subset of jQuery that allows * Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality * within a very small footprint, so only a subset of the jQuery API - methods, arguments and * invocation styles - are supported. * * Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never * raw DOM references. * * ## Angular's jQuery lite provides the following methods: * * - [addClass()](http://api.jquery.com/addClass/) * - [after()](http://api.jquery.com/after/) * - [append()](http://api.jquery.com/append/) * - [attr()](http://api.jquery.com/attr/) * - [bind()](http://api.jquery.com/bind/) - Does not support namespaces * - [children()](http://api.jquery.com/children/) - Does not support selectors * - [clone()](http://api.jquery.com/clone/) * - [contents()](http://api.jquery.com/contents/) * - [css()](http://api.jquery.com/css/) * - [data()](http://api.jquery.com/data/) * - [eq()](http://api.jquery.com/eq/) * - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name * - [hasClass()](http://api.jquery.com/hasClass/) * - [html()](http://api.jquery.com/html/) * - [next()](http://api.jquery.com/next/) - Does not support selectors * - [parent()](http://api.jquery.com/parent/) - Does not support selectors * - [prepend()](http://api.jquery.com/prepend/) * - [prop()](http://api.jquery.com/prop/) * - [ready()](http://api.jquery.com/ready/) * - [remove()](http://api.jquery.com/remove/) * - [removeAttr()](http://api.jquery.com/removeAttr/) * - [removeClass()](http://api.jquery.com/removeClass/) * - [removeData()](http://api.jquery.com/removeData/) * - [replaceWith()](http://api.jquery.com/replaceWith/) * - [text()](http://api.jquery.com/text/) * - [toggleClass()](http://api.jquery.com/toggleClass/) * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. * - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces * - [val()](http://api.jquery.com/val/) * - [wrap()](http://api.jquery.com/wrap/) * * ## In addition to the above, Angular provides additional methods to both jQuery and jQuery lite: * * - `controller(name)` - retrieves the controller of the current element or its parent. By default * retrieves controller associated with the `ngController` directive. If `name` is provided as * camelCase directive name, then the controller for this directive will be retrieved (e.g. * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current * element or its parent. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ var jqCache = JQLite.cache = {}, jqName = JQLite.expando = 'ng-' + new Date().getTime(), jqId = 1, addEventListenerFn = (window.document.addEventListener ? function(element, type, fn) {element.addEventListener(type, fn, false);} : function(element, type, fn) {element.attachEvent('on' + type, fn);}), removeEventListenerFn = (window.document.removeEventListener ? function(element, type, fn) {element.removeEventListener(type, fn, false); } : function(element, type, fn) {element.detachEvent('on' + type, fn); }); function jqNextId() { return ++jqId; } var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; var MOZ_HACK_REGEXP = /^moz([A-Z])/; /** * Converts snake_case to camelCase. * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function camelCase(name) { return name. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { return offset ? letter.toUpperCase() : letter; }). replace(MOZ_HACK_REGEXP, 'Moz$1'); } ///////////////////////////////////////////// // jQuery mutation patch // // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a // $destroy event on all DOM nodes being removed. // ///////////////////////////////////////////// function JQLitePatchJQueryRemove(name, dispatchThis) { var originalJqFn = jQuery.fn[name]; originalJqFn = originalJqFn.$original || originalJqFn; removePatch.$original = originalJqFn; jQuery.fn[name] = removePatch; function removePatch() { var list = [this], fireEvent = dispatchThis, set, setIndex, setLength, element, childIndex, childLength, children, fns, events; while(list.length) { set = list.shift(); for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { element = jqLite(set[setIndex]); if (fireEvent) { element.triggerHandler('$destroy'); } else { fireEvent = !fireEvent; } for(childIndex = 0, childLength = (children = element.children()).length; childIndex < childLength; childIndex++) { list.push(jQuery(children[childIndex])); } } } return originalJqFn.apply(this, arguments); } } ///////////////////////////////////////////// function JQLite(element) { if (element instanceof JQLite) { return element; } if (!(this instanceof JQLite)) { if (isString(element) && element.charAt(0) != '<') { throw Error('selectors not implemented'); } return new JQLite(element); } if (isString(element)) { var div = document.createElement('div'); // Read about the NoScope elements here: // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work! div.removeChild(div.firstChild); // remove the superfluous div JQLiteAddNodes(this, div.childNodes); this.remove(); // detach the elements from the temporary DOM div. } else { JQLiteAddNodes(this, element); } } function JQLiteClone(element) { return element.cloneNode(true); } function JQLiteDealoc(element){ JQLiteRemoveData(element); for ( var i = 0, children = element.childNodes || []; i < children.length; i++) { JQLiteDealoc(children[i]); } } function JQLiteUnbind(element, type, fn) { var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!handle) return; //no listeners registered if (isUndefined(type)) { forEach(events, function(eventHandler, type) { removeEventListenerFn(element, type, eventHandler); delete events[type]; }); } else { if (isUndefined(fn)) { removeEventListenerFn(element, type, events[type]); delete events[type]; } else { arrayRemove(events[type], fn); } } } function JQLiteRemoveData(element) { var expandoId = element[jqName], expandoStore = jqCache[expandoId]; if (expandoStore) { if (expandoStore.handle) { expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); JQLiteUnbind(element); } delete jqCache[expandoId]; element[jqName] = undefined; // ie does not allow deletion of attributes on elements. } } function JQLiteExpandoStore(element, key, value) { var expandoId = element[jqName], expandoStore = jqCache[expandoId || -1]; if (isDefined(value)) { if (!expandoStore) { element[jqName] = expandoId = jqNextId(); expandoStore = jqCache[expandoId] = {}; } expandoStore[key] = value; } else { return expandoStore && expandoStore[key]; } } function JQLiteData(element, key, value) { var data = JQLiteExpandoStore(element, 'data'), isSetter = isDefined(value), keyDefined = !isSetter && isDefined(key), isSimpleGetter = keyDefined && !isObject(key); if (!data && !isSimpleGetter) { JQLiteExpandoStore(element, 'data', data = {}); } if (isSetter) { data[key] = value; } else { if (keyDefined) { if (isSimpleGetter) { // don't create data in this case. return data && data[key]; } else { extend(data, key); } } else { return data; } } } function JQLiteHasClass(element, selector) { return ((" " + element.className + " ").replace(/[\n\t]/g, " "). indexOf( " " + selector + " " ) > -1); } function JQLiteRemoveClass(element, cssClasses) { if (cssClasses) { forEach(cssClasses.split(' '), function(cssClass) { element.className = trim( (" " + element.className + " ") .replace(/[\n\t]/g, " ") .replace(" " + trim(cssClass) + " ", " ") ); }); } } function JQLiteAddClass(element, cssClasses) { if (cssClasses) { forEach(cssClasses.split(' '), function(cssClass) { if (!JQLiteHasClass(element, cssClass)) { element.className = trim(element.className + ' ' + trim(cssClass)); } }); } } function JQLiteAddNodes(root, elements) { if (elements) { elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) ? elements : [ elements ]; for(var i=0; i < elements.length; i++) { root.push(elements[i]); } } } function JQLiteController(element, name) { return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); } function JQLiteInheritedData(element, name, value) { element = jqLite(element); // if element is the document object work with the html element instead // this makes $(document).scope() possible if(element[0].nodeType == 9) { element = element.find('html'); } while (element.length) { if (value = element.data(name)) return value; element = element.parent(); } } ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { ready: function(fn) { var fired = false; function trigger() { if (fired) return; fired = true; fn(); } // check if document already is loaded if (document.readyState === 'complete'){ setTimeout(trigger); } else { this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9 // we can not use jqLite since we are not done loading and jQuery could be loaded later. JQLite(window).bind('load', trigger); // fallback to window.onload for others } }, toString: function() { var value = []; forEach(this, function(e){ value.push('' + e);}); return '[' + value.join(', ') + ']'; }, eq: function(index) { return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]); }, length: 0, push: push, sort: [].sort, splice: [].splice }; ////////////////////////////////////////// // Functions iterating getter/setters. // these functions return self on setter and // value on get. ////////////////////////////////////////// var BOOLEAN_ATTR = {}; forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) { BOOLEAN_ATTR[lowercase(value)] = value; }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { BOOLEAN_ELEMENTS[uppercase(value)] = true; }); function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; } forEach({ data: JQLiteData, inheritedData: JQLiteInheritedData, scope: function(element) { return JQLiteInheritedData(element, '$scope'); }, controller: JQLiteController , injector: function(element) { return JQLiteInheritedData(element, '$injector'); }, removeAttr: function(element,name) { element.removeAttribute(name); }, hasClass: JQLiteHasClass, css: function(element, name, value) { name = camelCase(name); if (isDefined(value)) { element.style[name] = value; } else { var val; if (msie <= 8) { // this is some IE specific weirdness that jQuery 1.6.4 does not sure why val = element.currentStyle && element.currentStyle[name]; if (val === '') val = 'auto'; } val = val || element.style[name]; if (msie <= 8) { // jquery weirdness :-/ val = (val === '') ? undefined : val; } return val; } }, attr: function(element, name, value){ var lowercasedName = lowercase(name); if (BOOLEAN_ATTR[lowercasedName]) { if (isDefined(value)) { if (!!value) { element[name] = true; element.setAttribute(name, lowercasedName); } else { element[name] = false; element.removeAttribute(lowercasedName); } } else { return (element[name] || (element.attributes.getNamedItem(name)|| noop).specified) ? lowercasedName : undefined; } } else if (isDefined(value)) { element.setAttribute(name, value); } else if (element.getAttribute) { // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code // some elements (e.g. Document) don't have get attribute, so return undefined var ret = element.getAttribute(name, 2); // normalize non-existing attributes to undefined (as jQuery) return ret === null ? undefined : ret; } }, prop: function(element, name, value) { if (isDefined(value)) { element[name] = value; } else { return element[name]; } }, text: extend((msie < 9) ? function(element, value) { if (element.nodeType == 1 /** Element */) { if (isUndefined(value)) return element.innerText; element.innerText = value; } else { if (isUndefined(value)) return element.nodeValue; element.nodeValue = value; } } : function(element, value) { if (isUndefined(value)) { return element.textContent; } element.textContent = value; }, {$dv:''}), val: function(element, value) { if (isUndefined(value)) { return element.value; } element.value = value; }, html: function(element, value) { if (isUndefined(value)) { return element.innerHTML; } for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { JQLiteDealoc(childNodes[i]); } element.innerHTML = value; } }, function(fn, name){ /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; // JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values for(i=0; i < this.length; i++) { if (fn === JQLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); } else { for (key in arg1) { fn(this[i], key, arg1[key]); } } } // return self for chaining return this; } else { // we are a read, so read the first child. if (this.length) return fn(this[0], arg1, arg2); } } else { // we are a write, so apply to all children for(i=0; i < this.length; i++) { fn(this[i], arg1, arg2); } // return self for chaining return this; } return fn.$dv; }; }); function createEventHandler(element, events) { var eventHandler = function (event, type) { if (!event.preventDefault) { event.preventDefault = function() { event.returnValue = false; //ie }; } if (!event.stopPropagation) { event.stopPropagation = function() { event.cancelBubble = true; //ie }; } if (!event.target) { event.target = event.srcElement || document; } if (isUndefined(event.defaultPrevented)) { var prevent = event.preventDefault; event.preventDefault = function() { event.defaultPrevented = true; prevent.call(event); }; event.defaultPrevented = false; } event.isDefaultPrevented = function() { return event.defaultPrevented || event.returnValue == false; }; forEach(events[type || event.type], function(fn) { fn.call(element, event); }); // Remove monkey-patched methods (IE), // as they would cause memory leaks in IE8. if (msie <= 8) { // IE7/8 does not allow to delete property on native object event.preventDefault = null; event.stopPropagation = null; event.isDefaultPrevented = null; } else { // It shouldn't affect normal browsers (native methods are defined on prototype). delete event.preventDefault; delete event.stopPropagation; delete event.isDefaultPrevented; } }; eventHandler.elem = element; return eventHandler; } ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single // selector. ////////////////////////////////////////// forEach({ removeData: JQLiteRemoveData, dealoc: JQLiteDealoc, bind: function bindFn(element, type, fn){ var events = JQLiteExpandoStore(element, 'events'), handle = JQLiteExpandoStore(element, 'handle'); if (!events) JQLiteExpandoStore(element, 'events', events = {}); if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); forEach(type.split(' '), function(type){ var eventFns = events[type]; if (!eventFns) { if (type == 'mouseenter' || type == 'mouseleave') { var contains = document.body.contains || document.body.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; }; events[type] = []; // Refer to jQuery's implementation of mouseenter & mouseleave // Read about mouseenter and mouseleave: // http://www.quirksmode.org/js/events_mouse.html#link8 var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"} bindFn(element, eventmap[type], function(event) { var ret, target = this, related = event.relatedTarget; // 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 && !contains(target, related)) ){ handle(event, type); } }); } else { addEventListenerFn(element, type, handle); events[type] = []; } eventFns = events[type] } eventFns.push(fn); }); }, unbind: JQLiteUnbind, replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; JQLiteDealoc(element); forEach(new JQLite(replaceNode), function(node){ if (index) { parent.insertBefore(node, index.nextSibling); } else { parent.replaceChild(node, element); } index = node; }); }, children: function(element) { var children = []; forEach(element.childNodes, function(element){ if (element.nodeType === 1) children.push(element); }); return children; }, contents: function(element) { return element.childNodes || []; }, append: function(element, node) { forEach(new JQLite(node), function(child){ if (element.nodeType === 1 || element.nodeType === 11) { element.appendChild(child); } }); }, prepend: function(element, node) { if (element.nodeType === 1) { var index = element.firstChild; forEach(new JQLite(node), function(child){ if (index) { element.insertBefore(child, index); } else { element.appendChild(child); index = child; } }); } }, wrap: function(element, wrapNode) { wrapNode = jqLite(wrapNode)[0]; var parent = element.parentNode; if (parent) { parent.replaceChild(wrapNode, element); } wrapNode.appendChild(element); }, remove: function(element) { JQLiteDealoc(element); var parent = element.parentNode; if (parent) parent.removeChild(element); }, after: function(element, newElement) { var index = element, parent = element.parentNode; forEach(new JQLite(newElement), function(node){ parent.insertBefore(node, index.nextSibling); index = node; }); }, addClass: JQLiteAddClass, removeClass: JQLiteRemoveClass, toggleClass: function(element, selector, condition) { if (isUndefined(condition)) { condition = !JQLiteHasClass(element, selector); } (condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector); }, parent: function(element) { var parent = element.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, next: function(element) { if (element.nextElementSibling) { return element.nextElementSibling; } // IE8 doesn't have nextElementSibling var elm = element.nextSibling; while (elm != null && elm.nodeType !== 1) { elm = elm.nextSibling; } return elm; }, find: function(element, selector) { return element.getElementsByTagName(selector); }, clone: JQLiteClone, triggerHandler: function(element, eventName) { var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; var event; forEach(eventFns, function(fn) { fn.call(element, {preventDefault: noop}); }); } }, function(fn, name){ /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2) { var value; for(var i=0; i < this.length; i++) { if (value == undefined) { value = fn(this[i], arg1, arg2); if (value !== undefined) { // any function which returns a value needs to be wrapped value = jqLite(value); } } else { JQLiteAddNodes(value, fn(this[i], arg1, arg2)); } } return value == undefined ? this : value; }; }); /** * Computes a hash of an 'obj'. * Hash of a: * string is string * number is number as string * object is either result of calling $$hashKey function on the object or uniquely generated id, * that is also assigned to the $$hashKey property of the object. * * @param obj * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ function hashKey(obj) { var objType = typeof obj, key; if (objType == 'object' && obj !== null) { if (typeof (key = obj.$$hashKey) == 'function') { // must invoke on object to keep the right this key = obj.$$hashKey(); } else if (key === undefined) { key = obj.$$hashKey = nextUid(); } } else { key = obj; } return objType + ':' + key; } /** * HashMap which can use objects as keys */ function HashMap(array){ forEach(array, this.put, this); } HashMap.prototype = { /** * Store key value pair * @param key key to store can be any type * @param value value to store can be any type */ put: function(key, value) { this[hashKey(key)] = value; }, /** * @param key * @returns the value for the key */ get: function(key) { return this[hashKey(key)]; }, /** * Remove the key/value pair * @param key */ remove: function(key) { var value = this[key = hashKey(key)]; delete this[key]; return value; } }; /** * @ngdoc function * @name angular.injector * @function * * @description * Creates an injector function that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * * @param {Array.<string|Function>} modules A list of module functions or their aliases. See * {@link angular.module}. The `ng` module must be explicitly added. * @returns {function()} Injector function. See {@link AUTO.$injector $injector}. * * @example * Typical usage * <pre> * // create an injector * var $injector = angular.injector(['ng']); * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection * $injector.invoke(function($rootScope, $compile, $document){ * $compile($document)($rootScope); * $rootScope.$digest(); * }); * </pre> */ /** * @ngdoc overview * @name AUTO * @description * * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}. */ var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; function annotate(fn) { var $inject, fnText, argDecl, last; if (typeof fn == 'function') { if (!($inject = fn.$inject)) { $inject = []; fnText = fn.toString().replace(STRIP_COMMENTS, ''); argDecl = fnText.match(FN_ARGS); forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ arg.replace(FN_ARG, function(all, underscore, name){ $inject.push(name); }); }); fn.$inject = $inject; } } else if (isArray(fn)) { last = fn.length - 1; assertArgFn(fn[last], 'fn'); $inject = fn.slice(0, last); } else { assertArgFn(fn, 'fn', true); } return $inject; } /////////////////////////////////////// /** * @ngdoc object * @name AUTO.$injector * @function * * @description * * `$injector` is used to retrieve object instances as defined by * {@link AUTO.$provide provider}, instantiate types, invoke methods, * and load modules. * * The following always holds true: * * <pre> * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); * expect($injector.invoke(function($injector){ * return $injector; * }).toBe($injector); * </pre> * * # Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. * * <pre> * // inferred (only works if code not minified/obfuscated) * $injector.invoke(function(serviceA){}); * * // annotated * function explicit(serviceA) {}; * explicit.$inject = ['serviceA']; * $injector.invoke(explicit); * * // inline * $injector.invoke(['serviceA', function(serviceA){}]); * </pre> * * ## Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition can then be * parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation * tools since these tools change the argument names. * * ## `$inject` Annotation * By adding a `$inject` property onto a function the injection parameters can be specified. * * ## Inline * As an array of injection names, where the last item in the array is the function to call. */ /** * @ngdoc method * @name AUTO.$injector#get * @methodOf AUTO.$injector * * @description * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. * @return {*} The instance. */ /** * @ngdoc method * @name AUTO.$injector#invoke * @methodOf AUTO.$injector * * @description * Invoke the method and supply the method arguments from the `$injector`. * * @param {!function} fn The function to invoke. The function arguments come form the function annotation. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {*} the value returned by the invoked `fn` function. */ /** * @ngdoc method * @name AUTO.$injector#has * @methodOf AUTO.$injector * * @description * Allows the user to query if the particular service exist. * * @param {string} Name of the service to query. * @returns {boolean} returns true if injector has given service. */ /** * @ngdoc method * @name AUTO.$injector#instantiate * @methodOf AUTO.$injector * @description * Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies * all of the arguments to the constructor function as specified by the constructor annotation. * * @param {function} Type Annotated constructor function. * @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before * the `$injector` is consulted. * @returns {Object} new instance of `Type`. */ /** * @ngdoc method * @name AUTO.$injector#annotate * @methodOf AUTO.$injector * * @description * Returns an array of service names which the function is requesting for injection. This API is used by the injector * to determine which services need to be injected into the function when the function is invoked. There are three * ways in which the function can be annotated with the needed dependencies. * * # Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done by converting * the function into a string using `toString()` method and extracting the argument names. * <pre> * // Given * function MyController($scope, $route) { * // ... * } * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * This method does not work with code minfication / obfuscation. For this reason the following annotation strategies * are supported. * * # The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings represent names of * services to be injected into the function. * <pre> * // Given * var MyController = function(obfuscatedScope, obfuscatedRoute) { * // ... * } * // Define function dependencies * MyController.$inject = ['$scope', '$route']; * * // Then * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * </pre> * * # The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property is very * inconvenient. In these situations using the array notation to specify the dependencies in a way that survives * minification is a better choice: * * <pre> * // We wish to write this (not minification / obfuscation safe) * injector.invoke(function($compile, $rootScope) { * // ... * }); * * // We are forced to write break inlining * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) { * // ... * }; * tmpFn.$inject = ['$compile', '$rootScope']; * injector.invoke(tmpFn); * * // To better support inline function the inline annotation is supported * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) { * // ... * }]); * * // Therefore * expect(injector.annotate( * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}]) * ).toEqual(['$compile', '$rootScope']); * </pre> * * @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described * above. * * @returns {Array.<string>} The names of the services which the function requires. */ /** * @ngdoc object * @name AUTO.$provide * * @description * * Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance. * The providers share the same name as the instance they create with `Provider` suffixed to them. * * A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of * a service. The Provider can have additional methods which would allow for configuration of the provider. * * <pre> * function GreetProvider() { * var salutation = 'Hello'; * * this.salutation = function(text) { * salutation = text; * }; * * this.$get = function() { * return function (name) { * return salutation + ' ' + name + '!'; * }; * }; * } * * describe('Greeter', function(){ * * beforeEach(module(function($provide) { * $provide.provider('greet', GreetProvider); * })); * * it('should greet', inject(function(greet) { * expect(greet('angular')).toEqual('Hello angular!'); * })); * * it('should allow configuration of salutation', function() { * module(function(greetProvider) { * greetProvider.salutation('Ahoj'); * }); * inject(function(greet) { * expect(greet('angular')).toEqual('Ahoj angular!'); * }); * }); * </pre> */ /** * @ngdoc method * @name AUTO.$provide#provider * @methodOf AUTO.$provide * @description * * Register a provider for a service. The providers can be retrieved and can have additional configuration methods. * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: * * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created. * - `Constructor`: a new instance of the provider will be created using * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`. * * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#factory * @methodOf AUTO.$provide * @description * * A short hand for configuring services if only `$get` method is required. * * @param {string} name The name of the instance. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for * `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#service * @methodOf AUTO.$provide * @description * * A short hand for registering service of given class. * * @param {string} name The name of the instance. * @param {Function} constructor A class (constructor function) that will be instantiated. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#value * @methodOf AUTO.$provide * @description * * A short hand for configuring services if the `$get` method is a constant. * * @param {string} name The name of the instance. * @param {*} value The value. * @returns {Object} registered provider instance */ /** * @ngdoc method * @name AUTO.$provide#constant * @methodOf AUTO.$provide * @description * * A constant value, but unlike {@link AUTO.$provide#value value} it can be injected * into configuration function (other modules) and it is not interceptable by * {@link AUTO.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. * @returns {Object} registered instance */ /** * @ngdoc method * @name AUTO.$provide#decorator * @methodOf AUTO.$provide * @description * * Decoration of service, allows the decorator to intercept the service instance creation. The * returned instance may be the original instance, or a new instance which delegates to the * original instance. * * @param {string} name The name of the service to decorate. * @param {function()} decorator This function will be invoked when the service needs to be * instantiated. The function is called using the {@link AUTO.$injector#invoke * injector.invoke} method and is therefore fully injectable. Local injection arguments: * * * `$delegate` - The original service instance, which can be monkey patched, configured, * decorated or delegated to. */ function createInjector(modulesToLoad) { var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], loadedModules = new HashMap(), providerCache = { $provide: { provider: supportObject(provider), factory: supportObject(factory), service: supportObject(service), value: supportObject(value), constant: supportObject(constant), decorator: decorator } }, providerInjector = (providerCache.$injector = createInternalInjector(providerCache, function() { throw Error("Unknown provider: " + path.join(' <- ')); })), instanceCache = {}, instanceInjector = (instanceCache.$injector = createInternalInjector(instanceCache, function(servicename) { var provider = providerInjector.get(servicename + providerSuffix); return instanceInjector.invoke(provider.$get, provider); })); forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; //////////////////////////////////// // $provider //////////////////////////////////// function supportObject(delegate) { return function(key, value) { if (isObject(key)) { forEach(key, reverseParams(delegate)); } else { return delegate(key, value); } } } function provider(name, provider_) { if (isFunction(provider_) || isArray(provider_)) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { throw Error('Provider ' + name + ' must define $get factory method.'); } return providerCache[name + providerSuffix] = provider_; } function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } function service(name, constructor) { return factory(name, ['$injector', function($injector) { return $injector.instantiate(constructor); }]); } function value(name, value) { return factory(name, valueFn(value)); } function constant(name, value) { providerCache[name] = value; instanceCache[name] = value; } function decorator(serviceName, decorFn) { var origProvider = providerInjector.get(serviceName + providerSuffix), orig$get = origProvider.$get; origProvider.$get = function() { var origInstance = instanceInjector.invoke(orig$get, origProvider); return instanceInjector.invoke(decorFn, null, {$delegate: origInstance}); }; } //////////////////////////////////// // Module Loading //////////////////////////////////// function loadModules(modulesToLoad){ var runBlocks = []; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; loadedModules.put(module, true); if (isString(module)) { var moduleFn = angularModule(module); runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); try { for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { var invokeArgs = invokeQueue[i], provider = providerInjector.get(invokeArgs[0]); provider[invokeArgs[1]].apply(provider, invokeArgs[2]); } } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isFunction(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + module; throw e; } } else if (isArray(module)) { try { runBlocks.push(providerInjector.invoke(module)); } catch (e) { if (e.message) e.message += ' from ' + String(module[module.length - 1]); throw e; } } else { assertArgFn(module, 'module'); } }); return runBlocks; } //////////////////////////////////// // internal Injector //////////////////////////////////// function createInternalInjector(cache, factory) { function getService(serviceName) { if (typeof serviceName !== 'string') { throw Error('Service name expected'); } if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { throw Error('Circular dependency: ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; return cache[serviceName] = factory(serviceName); } finally { path.shift(); } } } function invoke(fn, self, locals){ var args = [], $inject = annotate(fn), length, i, key; for(i = 0, length = $inject.length; i < length; i++) { key = $inject[i]; args.push( locals && locals.hasOwnProperty(key) ? locals[key] : getService(key) ); } if (!fn.$inject) { // this means that we must be an array. fn = fn[length]; } // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke switch (self ? -1 : args.length) { case 0: return fn(); case 1: return fn(args[0]); case 2: return fn(args[0], args[1]); case 3: return fn(args[0], args[1], args[2]); case 4: return fn(args[0], args[1], args[2], args[3]); case 5: return fn(args[0], args[1], args[2], args[3], args[4]); case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]); case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]); case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]); default: return fn.apply(self, args); } } function instantiate(Type, locals) { var Constructor = function() {}, instance, returnedValue; // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; instance = new Constructor(); returnedValue = invoke(Type, instance, locals); return isObject(returnedValue) ? returnedValue : instance; } return { invoke: invoke, instantiate: instantiate, get: getService, annotate: annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } }; } } /** * @ngdoc function * @name ng.$anchorScroll * @requires $window * @requires $location * @requires $rootScope * * @description * When called, it checks current value of `$location.hash()` and scroll to related element, * according to rules specified in * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}. * * It also watches the `$location.hash()` and scroll whenever it changes to match any anchor. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; // helper function to get first anchor from a NodeList // can't use filter.filter, as it accepts only instances of Array // and IE can't convert NodeList to an array using [].slice // TODO(vojta): use filter if we change it to accept lists as well function getFirstAnchor(list) { var result = null; forEach(list, function(element) { if (!result && lowercase(element.nodeName) === 'a') result = element; }); return result; } function scroll() { var hash = $location.hash(), elm; // empty hash, scroll to the top of the page if (!hash) $window.scrollTo(0, 0); // element with given id else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); // first anchor with given name :-D else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); // no element and hash == 'top', scroll to the top of the page else if (hash === 'top') $window.scrollTo(0, 0); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, function autoScrollWatchAction() { $rootScope.$evalAsync(scroll); }); } return scroll; }]; } /** * @ngdoc object * @name ng.$animationProvider * @description * * The $AnimationProvider provider allows developers to register and access custom JavaScript animations directly inside * of a module. * */ $AnimationProvider.$inject = ['$provide']; function $AnimationProvider($provide) { var suffix = 'Animation'; /** * @ngdoc function * @name ng.$animation#register * @methodOf ng.$animationProvider * * @description * Registers a new injectable animation factory function. The factory function produces the animation object which * has these two properties: * * * `setup`: `function(Element):*` A function which receives the starting state of the element. The purpose * of this function is to get the element ready for animation. Optionally the function returns an memento which * is passed to the `start` function. * * `start`: `function(Element, doneFunction, *)` The element to animate, the `doneFunction` to be called on * element animation completion, and an optional memento from the `setup` function. * * @param {string} name The name of the animation. * @param {function} factory The factory function that will be executed to return the animation object. * */ this.register = function(name, factory) { $provide.factory(camelCase(name) + suffix, factory); }; this.$get = ['$injector', function($injector) { /** * @ngdoc function * @name ng.$animation * @function * * @description * The $animation service is used to retrieve any defined animation functions. When executed, the $animation service * will return a object that contains the setup and start functions that were defined for the animation. * * @param {String} name Name of the animation function to retrieve. Animation functions are registered and stored * inside of the AngularJS DI so a call to $animate('custom') is the same as injecting `customAnimation` * via dependency injection. * @return {Object} the animation object which contains the `setup` and `start` functions that perform the animation. */ return function $animation(name) { if (name) { var animationName = camelCase(name) + suffix; if ($injector.has(animationName)) { return $injector.get(animationName); } } }; }]; } // NOTE: this is a pseudo directive. /** * @ngdoc directive * @name ng.directive:ngAnimate * * @description * The `ngAnimate` directive works as an attribute that is attached alongside pre-existing directives. * It effects how the directive will perform DOM manipulation. This allows for complex animations to take place * without burdening the directive which uses the animation with animation details. The built in directives * `ngRepeat`, `ngInclude`, `ngSwitch`, `ngShow`, `ngHide` and `ngView` already accept `ngAnimate` directive. * Custom directives can take advantage of animation through {@link ng.$animator $animator service}. * * Below is a more detailed breakdown of the supported callback events provided by pre-exisitng ng directives: * * | Directive | Supported Animations | * |========================================================== |====================================================| * | {@link ng.directive:ngRepeat#animations ngRepeat} | enter, leave and move | * | {@link ng.directive:ngView#animations ngView} | enter and leave | * | {@link ng.directive:ngInclude#animations ngInclude} | enter and leave | * | {@link ng.directive:ngSwitch#animations ngSwitch} | enter and leave | * | {@link ng.directive:ngIf#animations ngIf} | enter and leave | * | {@link ng.directive:ngShow#animations ngShow & ngHide} | show and hide | * * You can find out more information about animations upon visiting each directive page. * * Below is an example of a directive that makes use of the ngAnimate attribute: * * <pre> * <!-- you can also use data-ng-animate, ng:animate or x-ng-animate as well --> * <ANY ng-directive ng-animate="{event1: 'animation-name', event2: 'animation-name-2'}"></ANY> * * <!-- you can also use a short hand --> * <ANY ng-directive ng-animate=" 'animation' "></ANY> * <!-- which expands to --> * <ANY ng-directive ng-animate="{ enter: 'animation-enter', leave: 'animation-leave', ...}"></ANY> * * <!-- keep in mind that ng-animate can take expressions --> * <ANY ng-directive ng-animate=" computeCurrentAnimation() "></ANY> * </pre> * * The `event1` and `event2` attributes refer to the animation events specific to the directive that has been assigned. * * Keep in mind that if an animation is running, no child element of such animation can also be animated. * * <h2>CSS-defined Animations</h2> * By default, ngAnimate attaches two CSS classes per animation event to the DOM element to achieve the animation. * It is up to you, the developer, to ensure that the animations take place using cross-browser CSS3 transitions as * well as CSS animations. * * The following code below demonstrates how to perform animations using **CSS transitions** with ngAnimate: * * <pre> * <style type="text/css"> * /&#42; * The animate-enter CSS class is the event name that you * have provided within the ngAnimate attribute. * &#42;/ * .animate-enter { * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/ * -moz-transition: 1s linear all; /&#42; Firefox &#42;/ * -o-transition: 1s linear all; /&#42; Opera &#42;/ * transition: 1s linear all; /&#42; IE10+ and Future Browsers &#42;/ * * /&#42; The animation preparation code &#42;/ * opacity: 0; * } * * /&#42; * Keep in mind that you want to combine both CSS * classes together to avoid any CSS-specificity * conflicts * &#42;/ * .animate-enter.animate-enter-active { * /&#42; The animation code itself &#42;/ * opacity: 1; * } * </style> * * <div ng-directive ng-animate="{enter: 'animate-enter'}"></div> * </pre> * * The following code below demonstrates how to perform animations using **CSS animations** with ngAnimate: * * <pre> * <style type="text/css"> * .animate-enter { * -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/ * -moz-animation: enter_sequence 1s linear; /&#42; Firefox &#42;/ * -o-animation: enter_sequence 1s linear; /&#42; Opera &#42;/ * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/ * } * &#64-webkit-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64-moz-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64-o-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * </style> * * <div ng-directive ng-animate="{enter: 'animate-enter'}"></div> * </pre> * * ngAnimate will first examine any CSS animation code and then fallback to using CSS transitions. * * Upon DOM mutation, the event class is added first, then the browser is allowed to reflow the content and then, * the active class is added to trigger the animation. The ngAnimate directive will automatically extract the duration * of the animation to determine when the animation ends. Once the animation is over then both CSS classes will be * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end * immediately resulting in a DOM element that is at it's final state. This final state is when the DOM element * has no CSS transition/animation classes surrounding it. * * <h2>JavaScript-defined Animations</h2> * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations to browsers that do not * yet support them, then you can make use of JavaScript animations defined inside of your AngularJS module. * * <pre> * var ngModule = angular.module('YourApp', []); * ngModule.animation('animate-enter', function() { * return { * setup : function(element) { * //prepare the element for animation * element.css({ 'opacity': 0 }); * var memo = "..."; //this value is passed to the start function * return memo; * }, * start : function(element, done, memo) { * //start the animation * element.animate({ * 'opacity' : 1 * }, function() { * //call when the animation is complete * done() * }); * } * } * }); * </pre> * * As you can see, the JavaScript code follows a similar template to the CSS3 animations. Once defined, the animation * can be used in the same way with the ngAnimate attribute. Keep in mind that, when using JavaScript-enabled * animations, ngAnimate will also add in the same CSS classes that CSS-enabled animations do (even if you're not using * CSS animations) to animated the element, but it will not attempt to find any CSS3 transition or animation duration/delay values. * It will instead close off the animation once the provided done function is executed. So it's important that you * make sure your animations remember to fire off the done function once the animations are complete. * * @param {expression} ngAnimate Used to configure the DOM manipulation animations. * */ var $AnimatorProvider = function() { var NG_ANIMATE_CONTROLLER = '$ngAnimateController'; var rootAnimateController = {running:true}; this.$get = ['$animation', '$window', '$sniffer', '$rootElement', '$rootScope', function($animation, $window, $sniffer, $rootElement, $rootScope) { $rootElement.data(NG_ANIMATE_CONTROLLER, rootAnimateController); /** * @ngdoc function * @name ng.$animator * @function * * @description * The $animator.create service provides the DOM manipulation API which is decorated with animations. * * @param {Scope} scope the scope for the ng-animate. * @param {Attributes} attr the attributes object which contains the ngAnimate key / value pair. (The attributes are * passed into the linking function of the directive using the `$animator`.) * @return {object} the animator object which contains the enter, leave, move, show, hide and animate methods. */ var AnimatorService = function(scope, attrs) { var animator = {}; /** * @ngdoc function * @name ng.animator#enter * @methodOf ng.$animator * @function * * @description * Injects the element object into the DOM (inside of the parent element) and then runs the enter animation. * * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation */ animator.enter = animateActionFactory('enter', insert, noop); /** * @ngdoc function * @name ng.animator#leave * @methodOf ng.$animator * @function * * @description * Runs the leave animation operation and, upon completion, removes the element from the DOM. * * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the leave animation */ animator.leave = animateActionFactory('leave', noop, remove); /** * @ngdoc function * @name ng.animator#move * @methodOf ng.$animator * @function * * @description * Fires the move DOM operation. Just before the animation starts, the animator will either append it into the parent container or * add the element directly after the after element if present. Then the move animation will be run. * * @param {jQuery/jqLite element} element the element that will be the focus of the move animation * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation */ animator.move = animateActionFactory('move', move, noop); /** * @ngdoc function * @name ng.animator#show * @methodOf ng.$animator * @function * * @description * Reveals the element by setting the CSS property `display` to `block` and then starts the show animation directly after. * * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden */ animator.show = animateActionFactory('show', show, noop); /** * @ngdoc function * @name ng.animator#hide * @methodOf ng.$animator * * @description * Starts the hide animation first and sets the CSS `display` property to `none` upon completion. * * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden */ animator.hide = animateActionFactory('hide', noop, hide); /** * @ngdoc function * @name ng.animator#animate * @methodOf ng.$animator * * @description * Triggers a custom animation event to be executed on the given element * * @param {jQuery/jqLite element} element that will be animated */ animator.animate = function(event, element) { animateActionFactory(event, noop, noop)(element); } return animator; function animateActionFactory(type, beforeFn, afterFn) { return function(element, parent, after) { var ngAnimateValue = scope.$eval(attrs.ngAnimate); var className = ngAnimateValue ? isObject(ngAnimateValue) ? ngAnimateValue[type] : ngAnimateValue + '-' + type : ''; var animationPolyfill = $animation(className); var polyfillSetup = animationPolyfill && animationPolyfill.setup; var polyfillStart = animationPolyfill && animationPolyfill.start; var polyfillCancel = animationPolyfill && animationPolyfill.cancel; if (!className) { beforeFn(element, parent, after); afterFn(element, parent, after); } else { var activeClassName = className + '-active'; if (!parent) { parent = after ? after.parent() : element.parent(); } if ((!$sniffer.transitions && !polyfillSetup && !polyfillStart) || (parent.inheritedData(NG_ANIMATE_CONTROLLER) || noop).running) { beforeFn(element, parent, after); afterFn(element, parent, after); return; } var animationData = element.data(NG_ANIMATE_CONTROLLER) || {}; if(animationData.running) { (polyfillCancel || noop)(element); animationData.done(); } element.data(NG_ANIMATE_CONTROLLER, {running:true, done:done}); element.addClass(className); beforeFn(element, parent, after); if (element.length == 0) return done(); var memento = (polyfillSetup || noop)(element); // $window.setTimeout(beginAnimation, 0); this was causing the element not to animate // keep at 1 for animation dom rerender $window.setTimeout(beginAnimation, 1); } function parseMaxTime(str) { var total = 0, values = isString(str) ? str.split(/\s*,\s*/) : []; forEach(values, function(value) { total = Math.max(parseFloat(value) || 0, total); }); return total; } function beginAnimation() { element.addClass(activeClassName); if (polyfillStart) { polyfillStart(element, done, memento); } else if (isFunction($window.getComputedStyle)) { //one day all browsers will have these properties var w3cAnimationProp = 'animation'; var w3cTransitionProp = 'transition'; //but some still use vendor-prefixed styles var vendorAnimationProp = $sniffer.vendorPrefix + 'Animation'; var vendorTransitionProp = $sniffer.vendorPrefix + 'Transition'; var durationKey = 'Duration', delayKey = 'Delay', animationIterationCountKey = 'IterationCount', duration = 0; //we want all the styles defined before and after var ELEMENT_NODE = 1; forEach(element, function(element) { if (element.nodeType == ELEMENT_NODE) { var w3cProp = w3cTransitionProp, vendorProp = vendorTransitionProp, iterations = 1, elementStyles = $window.getComputedStyle(element) || {}; //use CSS Animations over CSS Transitions if(parseFloat(elementStyles[w3cAnimationProp + durationKey]) > 0 || parseFloat(elementStyles[vendorAnimationProp + durationKey]) > 0) { w3cProp = w3cAnimationProp; vendorProp = vendorAnimationProp; iterations = Math.max(parseInt(elementStyles[w3cProp + animationIterationCountKey]) || 0, parseInt(elementStyles[vendorProp + animationIterationCountKey]) || 0, iterations); } var parsedDelay = Math.max(parseMaxTime(elementStyles[w3cProp + delayKey]), parseMaxTime(elementStyles[vendorProp + delayKey])); var parsedDuration = Math.max(parseMaxTime(elementStyles[w3cProp + durationKey]), parseMaxTime(elementStyles[vendorProp + durationKey])); duration = Math.max(parsedDelay + (iterations * parsedDuration), duration); } }); $window.setTimeout(done, duration * 1000); } else { done(); } } function done() { if(!done.run) { done.run = true; afterFn(element, parent, after); element.removeClass(className); element.removeClass(activeClassName); element.removeData(NG_ANIMATE_CONTROLLER); } } }; } function show(element) { element.css('display', ''); } function hide(element) { element.css('display', 'none'); } function insert(element, parent, after) { if (after) { after.after(element); } else { parent.append(element); } } function remove(element) { element.remove(); } function move(element, parent, after) { // Do not remove element before insert. Removing will cause data associated with the // element to be dropped. Insert will implicitly do the remove. insert(element, parent, after); } }; /** * @ngdoc function * @name ng.animator#enabled * @methodOf ng.$animator * @function * * @param {Boolean=} If provided then set the animation on or off. * @return {Boolean} Current animation state. * * @description * Globally enables/disables animations. * */ AnimatorService.enabled = function(value) { if (arguments.length) { rootAnimateController.running = !value; } return !rootAnimateController.running; }; return AnimatorService; }]; }; /** * ! This is a private undocumented service ! * * @name ng.$browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {function()} XHR XMLHttpRequest constructor. * @param {object} $log console.log or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while(outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn){ pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name ng.$browser#addPollFn * @methodOf ng.$browser * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn){ pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location.href, baseElement = document.find('base'); /** * @name ng.$browser#url * @methodOf ng.$browser * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record ? */ self.url = function(url, replace) { // setter if (url) { if (lastBrowserUrl == url) return; lastBrowserUrl = url; if ($sniffer.history) { if (replace) history.replaceState(null, '', url); else { history.pushState(null, '', url); // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement.attr('href', baseElement.attr('href')); } } else { if (replace) location.replace(url); else location.href = url; } return self; // getter } else { // the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return location.href.replace(/%27/g,"'"); } }; var urlChangeListeners = [], urlChangeInit = false; function fireUrlChange() { if (lastBrowserUrl == self.url()) return; lastBrowserUrl = self.url(); forEach(urlChangeListeners, function(listener) { listener(self.url()); }); } /** * @name ng.$browser#onUrlChange * @methodOf ng.$browser * @TODO(vojta): refactor to use node's syntax for events * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed by outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange); // hashchange event if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange); // polling else self.addPollFn(fireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * Returns current <base href> * (always relative - without domain) * * @returns {string=} */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); /** * @name ng.$browser#cookies * @methodOf ng.$browser * * @param {string=} name Cookie name * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * <ul> * <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li> * <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li> * <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li> * </ul> * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { $log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+ cookieLength + " > 4096 bytes)!"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies var name = unescape(cookie.substring(0, index)); // the first value that is seen for a cookie is the most // specific one. values for the same cookie name that // follow are for less specific paths. if (lastCookies[name] === undefined) { lastCookies[name] = unescape(cookie.substring(index + 1)); } } } } return lastCookies; } }; /** * @name ng.$browser#defer * @methodOf ng.$browser * @param {function()} fn A function, who's execution should be defered. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name ng.$browser#defer.cancel * @methodOf ng.$browser.defer * * @description * Cancels a defered task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider(){ this.$get = ['$window', '$log', '$sniffer', '$document', function( $window, $log, $sniffer, $document){ return new Browser($window, $document, $log, $sniffer); }]; } /** * @ngdoc object * @name ng.$cacheFactory * * @description * Factory that constructs cache objects. * * * @param {string} cacheId Name or id of the newly created cache. * @param {object=} options Options object that specifies the cache behavior. Properties: * * - `{number=}` `capacity` — turns the cache into LRU cache. * * @returns {object} Newly created cache object with the following set of methods: * * - `{object}` `info()` — Returns id, size, and options of cache. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns it. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache. * - `{void}` `removeAll()` — Removes all cached values. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * */ function $CacheFactoryProvider() { this.$get = function() { var caches = {}; function cacheFactory(cacheId, options) { if (cacheId in caches) { throw Error('cacheId ' + cacheId + ' taken'); } var size = 0, stats = extend({}, options, {id: cacheId}), data = {}, capacity = (options && options.capacity) || Number.MAX_VALUE, lruHash = {}, freshEnd = null, staleEnd = null; return caches[cacheId] = { put: function(key, value) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; if (size > capacity) { this.remove(staleEnd.key); } return value; }, get: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; refresh(lruEntry); return data[key]; }, remove: function(key) { var lruEntry = lruHash[key]; if (!lruEntry) return; if (lruEntry == freshEnd) freshEnd = lruEntry.p; if (lruEntry == staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; delete data[key]; size--; }, removeAll: function() { data = {}; size = 0; lruHash = {}; freshEnd = staleEnd = null; }, destroy: function() { data = null; stats = null; lruHash = null; delete caches[cacheId]; }, info: function() { return extend({}, stats, {size: size}); } }; /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { if (entry != freshEnd) { if (!staleEnd) { staleEnd = entry; } else if (staleEnd == entry) { staleEnd = entry.n; } link(entry.n, entry.p); link(entry, freshEnd); freshEnd = entry; freshEnd.n = null; } } /** * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { if (nextEntry != prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } } } cacheFactory.info = function() { var info = {}; forEach(caches, function(cache, cacheId) { info[cacheId] = cache.info(); }); return info; }; cacheFactory.get = function(cacheId) { return caches[cacheId]; }; return cacheFactory; }; } /** * @ngdoc object * @name ng.$templateCache * * @description * Cache used for storing html templates. * * See {@link ng.$cacheFactory $cacheFactory}. * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { return $cacheFactory('templates'); }]; } /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: * * - "node" - DOM Node * - "element" - DOM Element or Node * - "$node" or "$element" - jqLite-wrapped node or element * * * Compiler related stuff: * * - "linkFn" - linking fn of a single directive * - "nodeLinkFn" - function that aggregates all linking fns for a particular node * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList) */ var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: '; /** * @ngdoc function * @name ng.$compile * @function * * @description * Compiles a piece of HTML string or DOM into a template and produces a template function, which * can then be used to link {@link ng.$rootScope.Scope scope} and the template together. * * The compilation is a process of walking the DOM tree and trying to match DOM elements to * {@link ng.$compileProvider#directive directives}. For each match it * executes corresponding template function and collects the * instance functions into a single template function which is then returned. * * The template function can then be used once to produce the view or as it is the case with * {@link ng.directive:ngRepeat repeater} many-times, in which * case each call results in a view that is a DOM clone of the original template. * <doc:example module="compile"> <doc:source> <script> // declare a new module, and inject the $compileProvider angular.module('compile', [], function($compileProvider) { // configure new 'compile' directive by passing a directive // factory function. The factory function injects the '$compile' $compileProvider.directive('compile', function($compile) { // directive factory creates a link function return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'compile' expression for changes return scope.$eval(attrs.compile); }, function(value) { // when the 'compile' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }) }); function Ctrl($scope) { $scope.name = 'Angular'; $scope.html = 'Hello {{name}}'; } </script> <div ng-controller="Ctrl"> <input ng-model="name"> <br> <textarea ng-model="html"></textarea> <br> <div compile="html"></div> </div> </doc:source> <doc:scenario> it('should auto compile', function() { expect(element('div[compile]').text()).toBe('Hello Angular'); input('html').enter('{{name}}!'); expect(element('div[compile]').text()).toBe('Angular!'); }); </doc:scenario> </doc:example> * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives. * @param {number} maxPriority only apply directives lower then given priority (Only effects the * root element(s), not their children) * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is * called as: <br> `cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * * Calling the linking function returns the element of the template. It is either the original element * passed in, or the clone of the element if the `cloneAttachFn` is provided. * * After linking the view is not updated until after a call to $digest which typically is done by * Angular automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * <pre> * var element = $compile('<p>{{total}}</p>')(scope); * </pre> * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In * this case, you can access the clone via the cloneAttachFn: * <pre> * var templateHTML = angular.element('<p>{{total}}</p>'), * scope = ....; * * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) { * //attach the clone to DOM document at the right place * }); * * //now we have reference to the cloned DOM via `clone` * </pre> * * * For information on how the compiler works, see the * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. */ /** * @ngdoc service * @name ng.$compileProvider * @function * * @description */ $CompileProvider.$inject = ['$provide']; function $CompileProvider($provide) { var hasDirectives = {}, Suffix = 'Directive', COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/, MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ', urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/; /** * @ngdoc function * @name ng.$compileProvider#directive * @methodOf ng.$compileProvider * @function * * @description * Register a new directives with the compiler. * * @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as * <code>ng-bind</code>). * @param {function} directiveFactory An injectable directive factory function. See {@link guide/directive} for more * info. * @returns {ng.$compileProvider} Self for chaining. */ this.directive = function registerDirective(name, directiveFactory) { if (isString(name)) { assertArg(directiveFactory, 'directive'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', function($injector, $exceptionHandler) { var directives = []; forEach(hasDirectives[name], function(directiveFactory) { try { var directive = $injector.invoke(directiveFactory); if (isFunction(directive)) { directive = { compile: valueFn(directive) }; } else if (!directive.compile && directive.link) { directive.compile = valueFn(directive.link); } directive.priority = directive.priority || 0; directive.name = directive.name || name; directive.require = directive.require || (directive.controller && directive.name); directive.restrict = directive.restrict || 'A'; directives.push(directive); } catch (e) { $exceptionHandler(e); } }); return directives; }]); } hasDirectives[name].push(directiveFactory); } else { forEach(name, reverseParams(registerDirective)); } return this; }; /** * @ngdoc function * @name ng.$compileProvider#urlSanitizationWhitelist * @methodOf ng.$compileProvider * @function * * @description * Retrieves or overrides the default regular expression that is used for whitelisting of safe * urls during a[href] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular * expression. If a match is found the original url is written into the dom. Otherwise the * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM. * * @param {RegExp=} regexp New regexp to whitelist urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ this.urlSanitizationWhitelist = function(regexp) { if (isDefined(regexp)) { urlSanitizationWhitelist = regexp; return this; } return urlSanitizationWhitelist; }; this.$get = [ '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', '$controller', '$rootScope', '$document', function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, $controller, $rootScope, $document) { var Attributes = function(element, attr) { this.$$element = element; this.$attr = attr || {}; }; Attributes.prototype = { $normalize: directiveNormalize, /** * Set a normalized attribute on the element in a way such that all directives * can share the attribute. This function properly handles boolean attributes. * @param {string} key Normalized key. (ie ngAttribute) * @param {string|boolean} value The value to set. If `null` attribute will be deleted. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute. * Defaults to true. * @param {string=} attrName Optional none normalized name. Defaults to key. */ $set: function(key, value, writeAttr, attrName) { var booleanKey = getBooleanAttrName(this.$$element[0], key), $$observers = this.$$observers, normalizedVal; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; } this[key] = value; // translate normalized key to actual key if (attrName) { this.$attr[key] = attrName; } else { attrName = this.$attr[key]; if (!attrName) { this.$attr[key] = attrName = snake_case(key, '-'); } } // sanitize a[href] values if (nodeName_(this.$$element[0]) === 'A' && key === 'href') { urlSanitizationNode.setAttribute('href', value); // href property always returns normalized absolute url, so we can match against that normalizedVal = urlSanitizationNode.href; if (!normalizedVal.match(urlSanitizationWhitelist)) { this[key] = value = 'unsafe:' + normalizedVal; } } if (writeAttr !== false) { if (value === null || value === undefined) { this.$$element.removeAttr(attrName); } else { this.$$element.attr(attrName, value); } } // fire observers $$observers && forEach($$observers[key], function(fn) { try { fn(value); } catch (e) { $exceptionHandler(e); } }); }, /** * Observe an interpolated attribute. * The observer will never be called, if given attribute is not interpolated. * * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(*)} fn Function that will be called whenever the attribute value changes. * @returns {function(*)} the `fn` Function passed in. */ $observe: function(key, fn) { var attrs = this, $$observers = (attrs.$$observers || (attrs.$$observers = {})), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { if (!listeners.$$inter) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); return fn; } }; var urlSanitizationNode = $document[0].createElement('a'), startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }, NG_ATTR_BINDING = /^ngAttr[A-Z]/; return compile; //================================ function compile($compileNodes, transcludeFn, maxPriority) { if (!($compileNodes instanceof jqLite)) { // jquery always rewraps, whereas we need to preserve the original selector so that we can modify it. $compileNodes = jqLite($compileNodes); } // We can not compile top level text elements since text nodes can be merged and we will // not be able to attach scope data to them, so we will wrap them in <span> forEach($compileNodes, function(node, index){ if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0]; } }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority); return function publicLinkFn(scope, cloneConnectFn){ assertArg(scope, 'scope'); // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart // and sometimes changes the structure of the DOM. var $linkNode = cloneConnectFn ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! : $compileNodes; // Attach scope only to non-text nodes. for(var i = 0, ii = $linkNode.length; i<ii; i++) { var node = $linkNode[i]; if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) { $linkNode.eq(i).data('$scope', scope); } } safeAddClass($linkNode, 'ng-scope'); if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); return $linkNode; }; } function wrongMode(localName, mode) { throw Error("Unsupported '" + mode + "' for '" + localName + "'."); } function safeAddClass($element, className) { try { $element.addClass(className); } catch(e) { // ignore, since it means that we are trying to set class on // SVG element, where class name is read-only. } } /** * Compile function matches each node in nodeList against the directives. Once all directives * for a particular node are collected their compile functions are executed. The compile * functions return values - the linking functions - are combined into a composite linking * function, which is the a linking function for the node. * * @param {NodeList} nodeList an array of nodes or NodeList to compile * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the * rootElement must be set the jqLite collection of the compile root. This is * needed so that the jqLite collection items can be replaced with widgets. * @param {number=} max directive priority * @returns {?function} A composite linking function of all of the matched directives or null. */ function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) { var linkFns = [], nodeLinkFn, childLinkFn, directives, attrs, linkFnFound; for(var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, maxPriority); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement) : null; childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes || !nodeList[i].childNodes.length) ? null : compileNodes(nodeList[i].childNodes, nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); linkFns.push(nodeLinkFn); linkFns.push(childLinkFn); linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn); } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn, i, ii, n; // copy nodeList so that linking doesn't break due to live list updates. var stableNodeList = []; for (i = 0, ii = nodeList.length; i < ii; i++) { stableNodeList.push(nodeList[i]); } for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) { node = stableNodeList[n]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(isObject(nodeLinkFn.scope)); jqLite(node).data('$scope', childScope); } else { childScope = scope; } childTranscludeFn = nodeLinkFn.transclude; if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { nodeLinkFn(childLinkFn, childScope, node, $rootElement, (function(transcludeFn) { return function(cloneFn) { var transcludeScope = scope.$new(); transcludeScope.$$transcluded = true; return transcludeFn(transcludeScope, cloneFn). bind('$destroy', bind(transcludeScope, transcludeScope.$destroy)); }; })(childTranscludeFn || transcludeFn) ); } else { nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn); } } else if (childLinkFn) { childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); } } } } /** * Looks for directives on the given node and adds them to the directive collection which is * sorted. * * @param node Node to search. * @param directives An array to which the directives are added to. This array is sorted before * the function returns. * @param attrs The shared attrs object which is used to populate the normalized attributes. * @param {number=} maxPriority Max directive priority. */ function collectDirectives(node, directives, attrs, maxPriority) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, className; switch(nodeType) { case 1: /* Element */ // use the node name: <directive> addDirective(directives, directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority); // iterate over the attributes for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { attr = nAttrs[j]; if (attr.specified) { name = attr.name; // support ngAttr attribute binding ngAttrName = directiveNormalize(name); if (NG_ATTR_BINDING.test(ngAttrName)) { name = ngAttrName.substr(6).toLowerCase(); } nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; attrs[nName] = value = trim((msie && name == 'href') ? decodeURIComponent(node.getAttribute(name, 2)) : attr.value); if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } addAttrInterpolateDirective(node, directives, value, nName); addDirective(directives, nName, 'A', maxPriority); } } // use class as directive className = node.className; if (isString(className) && className !== '') { while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority)) { attrs[nName] = trim(match[3]); } className = className.substr(match.index + match[0].length); } } break; case 3: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; case 8: /* Comment */ try { match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); if (match) { nName = directiveNormalize(match[1]); if (addDirective(directives, nName, 'M', maxPriority)) { attrs[nName] = trim(match[2]); } } } catch (e) { // turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value. // Just ignore it and continue. (Can't seem to reproduce in test case.) } break; } directives.sort(byPriority); return directives; } /** * Once the directives have been collected, their compile functions are executed. This method * is responsible for inlining directive templates as well as terminating the application * of the directives if the terminal directive has been reached. * * @param {Array} directives Array of collected directives to execute their compile function. * this needs to be pre-sorted by priority order. * @param {Node} compileNode The raw DOM node to apply the compile functions to * @param {Object} templateAttrs The shared attribute function * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the * scope argument is auto-generated to the new child of the transcluded parent scope. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this * argument has the root jqLite array so that we can replace nodes on it. * @returns linkFn */ function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) { var terminalPriority = -Number.MAX_VALUE, preLinkFns = [], postLinkFns = [], newScopeDirective = null, newIsolateScopeDirective = null, templateDirective = null, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, directiveName, $template, transcludeDirective, childTranscludeFn = transcludeFn, controllerDirectives, linkFn, directiveValue; // executes all directives on the current element for(var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; $template = undefined; if (terminalPriority > directive.priority) { break; // prevent further processing of directives } if (directiveValue = directive.scope) { assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode); if (isObject(directiveValue)) { safeAddClass($compileNode, 'ng-isolate-scope'); newIsolateScopeDirective = directive; } safeAddClass($compileNode, 'ng-scope'); newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; if (directiveValue = directive.controller) { controllerDirectives = controllerDirectives || {}; assertNoDuplicate("'" + directiveName + "' controller", controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } if (directiveValue = directive.transclude) { assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode); transcludeDirective = directive; terminalPriority = directive.priority; if (directiveValue == 'element') { $template = jqLite(compileNode); $compileNode = templateAttrs.$$element = jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' ')); compileNode = $compileNode[0]; replaceWith(jqCollection, jqLite($template[0]), compileNode); childTranscludeFn = compile($template, transcludeFn, terminalPriority); } else { $template = jqLite(JQLiteClone(compileNode)).contents(); $compileNode.html(''); // clear contents childTranscludeFn = compile($template, transcludeFn); } } if (directive.template) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; directiveValue = (isFunction(directive.template)) ? directive.template($compileNode, templateAttrs) : directive.template; directiveValue = denormalizeTemplate(directiveValue); if (directive.replace) { $template = jqLite('<div>' + trim(directiveValue) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue); } replaceWith(jqCollection, $compileNode, compileNode); var newTemplateAttrs = {$attr: {}}; // combine directives from the original node and from the template: // - take the array of directives for this element // - split it into two parts, those that were already applied and those that weren't // - collect directives from the template, add them to the second group and sort them // - append the second group with new directives to the first group directives = directives.concat( collectDirectives( compileNode, directives.splice(i + 1, directives.length - (i + 1)), newTemplateAttrs ) ); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); ii = directives.length; } else { $compileNode.html(directiveValue); } } if (directive.templateUrl) { assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace, childTranscludeFn); ii = directives.length; } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); if (isFunction(linkFn)) { addLinkFns(null, linkFn); } else if (linkFn) { addLinkFns(linkFn.pre, linkFn.post); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); } } if (directive.terminal) { nodeLinkFn.terminal = true; terminalPriority = Math.max(terminalPriority, directive.priority); } } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope; nodeLinkFn.transclude = transcludeDirective && childTranscludeFn; // might be normal or delayed nodeLinkFn depending on if templateUrl is present return nodeLinkFn; //////////////////// function addLinkFns(pre, post) { if (pre) { pre.require = directive.require; preLinkFns.push(pre); } if (post) { post.require = directive.require; postLinkFns.push(post); } } function getControllers(require, $element) { var value, retrievalMethod = 'data', optional = false; if (isString(require)) { while((value = require.charAt(0)) == '^' || value == '?') { require = require.substr(1); if (value == '^') { retrievalMethod = 'inheritedData'; } optional = optional || value == '?'; } value = $element[retrievalMethod]('$' + require + 'Controller'); if (!value && !optional) { throw Error("No controller: " + require); } return value; } else if (isArray(require)) { value = []; forEach(require, function(require) { value.push(getControllers(require, $element)); }); } return value; } function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { var attrs, $element, i, ii, linkFn, controller; if (compileNode === linkNode) { attrs = templateAttrs; } else { attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); } $element = attrs.$$element; if (newIsolateScopeDirective) { var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; var parentScope = scope.$parent || scope; forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) { var match = definiton.match(LOCAL_REGEXP) || [], attrName = match[3] || scopeName, optional = (match[2] == '?'), mode = match[1], // @, =, or & lastValue, parentGet, parentSet; scope.$$isolateBindings[scopeName] = mode + attrName; switch (mode) { case '@': { attrs.$observe(attrName, function(value) { scope[scopeName] = value; }); attrs.$$observers[attrName].$$scope = parentScope; if( attrs[attrName] ) { // If the attribute has been provided then we trigger an interpolation to ensure the value is there for use in the link fn scope[scopeName] = $interpolate(attrs[attrName])(parentScope); } break; } case '=': { if (optional && !attrs[attrName]) { return; } parentGet = $parse(attrs[attrName]); parentSet = parentGet.assign || function() { // reset the change, or we will throw this exception on every $digest lastValue = scope[scopeName] = parentGet(parentScope); throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] + ' (directive: ' + newIsolateScopeDirective.name + ')'); }; lastValue = scope[scopeName] = parentGet(parentScope); scope.$watch(function parentValueWatch() { var parentValue = parentGet(parentScope); if (parentValue !== scope[scopeName]) { // we are out of sync and need to copy if (parentValue !== lastValue) { // parent changed and it has precedence lastValue = scope[scopeName] = parentValue; } else { // if the parent can be assigned then do so parentSet(parentScope, parentValue = lastValue = scope[scopeName]); } } return parentValue; }); break; } case '&': { parentGet = $parse(attrs[attrName]); scope[scopeName] = function(locals) { return parentGet(parentScope, locals); }; break; } default: { throw Error('Invalid isolate scope definition for directive ' + newIsolateScopeDirective.name + ': ' + definiton); } } }); } if (controllerDirectives) { forEach(controllerDirectives, function(directive) { var locals = { $scope: scope, $element: $element, $attrs: attrs, $transclude: boundTranscludeFn }; controller = directive.controller; if (controller == '@') { controller = attrs[directive.name]; } $element.data( '$' + directive.name + 'Controller', $controller(controller, locals)); }); } // PRELINKING for(i = 0, ii = preLinkFns.length; i < ii; i++) { try { linkFn = preLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } // RECURSION childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn); // POSTLINKING for(i = 0, ii = postLinkFns.length; i < ii; i++) { try { linkFn = postLinkFns[i]; linkFn(scope, $element, attrs, linkFn.require && getControllers(linkFn.require, $element)); } catch (e) { $exceptionHandler(e, startingTag($element)); } } } } /** * looks up the directive and decorates it with exception handling and proper parameters. We * call this the boundDirective. * * @param {string} name name of the directive to look up. * @param {string} location The directive must be found in specific format. * String containing any of theses characters: * * * `E`: element name * * `A': attribute * * `C`: class * * `M`: comment * @returns true if directive was added. */ function addDirective(tDirectives, name, location, maxPriority) { var match = false; if (hasDirectives.hasOwnProperty(name)) { for(var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i<ii; i++) { try { directive = directives[i]; if ( (maxPriority === undefined || maxPriority > directive.priority) && directive.restrict.indexOf(location) != -1) { tDirectives.push(directive); match = true; } } catch(e) { $exceptionHandler(e); } } } return match; } /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. * The desired effect is to have both of the attributes present. * * @param {object} dst destination attributes (original DOM) * @param {object} src source attributes (from the directive template) */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, dstAttr = dst.$attr, $element = dst.$$element; // reapply the old attributes to the new element forEach(dst, function(value, key) { if (key.charAt(0) != '$') { if (src[key]) { value += (key === 'style' ? ';' : ' ') + src[key]; } dst.$set(key, value, true, srcAttr[key]); } }); // copy the new attributes on the old attrs object forEach(src, function(value, key) { if (key == 'class') { safeAddClass($element, value); dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; } else if (key == 'style') { $element.attr('style', $element.attr('style') + ';' + value); } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { dst[key] = value; dstAttr[key] = srcAttr[key]; } }); } function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs, $rootElement, replace, childTranscludeFn) { var linkQueue = [], afterTemplateNodeLinkFn, afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), // The fact that we have to copy and patch the directive seems wrong! derivedSyncDirective = extend({}, origAsyncDirective, { controller: null, templateUrl: null, transclude: null, scope: null }), templateUrl = (isFunction(origAsyncDirective.templateUrl)) ? origAsyncDirective.templateUrl($compileNode, tAttrs) : origAsyncDirective.templateUrl; $compileNode.html(''); $http.get(templateUrl, {cache: $templateCache}). success(function(content) { var compileNode, tempTemplateAttrs, $template; content = denormalizeTemplate(content); if (replace) { $template = jqLite('<div>' + trim(content) + '</div>').contents(); compileNode = $template[0]; if ($template.length != 1 || compileNode.nodeType !== 1) { throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content); } tempTemplateAttrs = {$attr: {}}; replaceWith($rootElement, $compileNode, compileNode); collectDirectives(compileNode, directives, tempTemplateAttrs); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); } else { compileNode = beforeTemplateCompileNode; $compileNode.html(content); } directives.unshift(derivedSyncDirective); afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); while(linkQueue.length) { var scope = linkQueue.shift(), beforeTemplateLinkNode = linkQueue.shift(), linkRootElement = linkQueue.shift(), controller = linkQueue.shift(), linkNode = compileNode; if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { // it was cloned therefore we have to clone as well. linkNode = JQLiteClone(compileNode); replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); } afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller); }, scope, linkNode, $rootElement, controller); } linkQueue = null; }). error(function(response, code, headers, config) { throw Error('Failed to load template: ' + config.url); }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) { if (linkQueue) { linkQueue.push(scope); linkQueue.push(node); linkQueue.push(rootElement); linkQueue.push(controller); } else { afterTemplateNodeLinkFn(function() { beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller); }, scope, node, rootElement, controller); } }; } /** * Sorting function for bound directives. */ function byPriority(a, b) { return b.priority - a.priority; } function assertNoDuplicate(what, previousDirective, directive, element) { if (previousDirective) { throw Error('Multiple directives [' + previousDirective.name + ', ' + directive.name + '] asking for ' + what + ' on: ' + startingTag(element)); } } function addTextInterpolateDirective(directives, text) { var interpolateFn = $interpolate(text, true); if (interpolateFn) { directives.push({ priority: 0, compile: valueFn(function textInterpolateLinkFn(scope, node) { var parent = node.parent(), bindings = parent.data('$binding') || []; bindings.push(interpolateFn); safeAddClass(parent.data('$binding', bindings), 'ng-binding'); scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { node[0].nodeValue = value; }); }) }); } } function addAttrInterpolateDirective(node, directives, value, name) { var interpolateFn = $interpolate(value, true); // no interpolation found -> ignore if (!interpolateFn) return; directives.push({ priority: 100, compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) { var $$observers = (attr.$$observers || (attr.$$observers = {})); // we need to interpolate again, in case the attribute value has been updated // (e.g. by another directive's compile function) interpolateFn = $interpolate(attr[name], true); // if attribute was updated so that there is no interpolation going on we don't want to // register any observers if (!interpolateFn) return; attr[name] = interpolateFn(scope); ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(value) { attr.$set(name, value); }); }) }); } /** * This is a special jqLite.replaceWith, which can replace items which * have no parents, provided that the containing jqLite collection is provided. * * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes * in the root of the tree. * @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell, * but replace its DOM node reference. * @param {Node} newNode The new DOM node. */ function replaceWith($rootElement, $element, newNode) { var oldNode = $element[0], parent = oldNode.parentNode, i, ii; if ($rootElement) { for(i = 0, ii = $rootElement.length; i < ii; i++) { if ($rootElement[i] == oldNode) { $rootElement[i] = newNode; break; } } } if (parent) { parent.replaceChild(newNode, oldNode); } newNode[jqLite.expando] = oldNode[jqLite.expando]; $element[0] = newNode; } }]; } var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; /** * Converts all accepted directives format into proper directive name. * All of these will become 'myDirective': * my:DiRective * my-directive * x-my-directive * data-my:directive * * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { return camelCase(name.replace(PREFIX_REGEXP, '')); } /** * @ngdoc object * @name ng.$compile.directive.Attributes * @description * * A shared object between directive compile / linking functions which contains normalized DOM element * attributes. The the values reflect current binding state `{{ }}`. The normalization is needed * since all of these are treated as equivalent in Angular: * * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a"> */ /** * @ngdoc property * @name ng.$compile.directive.Attributes#$attr * @propertyOf ng.$compile.directive.Attributes * @returns {object} A map of DOM element attribute names to the normalized name. This is * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc function * @name ng.$compile.directive.Attributes#$set * @methodOf ng.$compile.directive.Attributes * @function * * @description * Set DOM element attribute value. * * * @param {string} name Normalized element attribute name of the property to modify. The name is * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr} * property to the original name. * @param {string} value Value to set the attribute to. The value can be an interpolated string. */ /** * Closure compiler type information */ function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, /* angular.Scope */ scope, /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn ){} /** * @ngdoc object * @name ng.$controllerProvider * @description * The {@link ng.$controller $controller service} is used by Angular to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { var controllers = {}, CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; /** * @ngdoc function * @name ng.$controllerProvider#register * @methodOf ng.$controllerProvider * @param {string} name Controller name * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI * annotations in the array notation). */ this.register = function(name, constructor) { if (isObject(name)) { extend(controllers, name) } else { controllers[name] = constructor; } }; this.$get = ['$injector', '$window', function($injector, $window) { /** * @ngdoc function * @name ng.$controller * @requires $injector * * @param {Function|string} constructor If called with a function then it's considered to be the * controller constructor function. Otherwise it's considered to be a string which is used * to retrieve the controller constructor using the following steps: * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor * * check `window[constructor]` on the global `window` object * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. * * @description * `$controller` service is responsible for instantiating controllers. * * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into * a service, so that one can override this service with {@link https://gist.github.com/1649788 * BC version}. */ return function(expression, locals) { var instance, match, constructor, identifier; if(isString(expression)) { match = expression.match(CNTRL_REG), constructor = match[1], identifier = match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] : getter(locals.$scope, constructor, true) || getter($window, constructor, true); assertArgFn(expression, constructor, true); } instance = $injector.instantiate(expression, locals); if (identifier) { if (typeof locals.$scope !== 'object') { throw new Error('Can not export controller as "' + identifier + '". ' + 'No scope object provided!'); } locals.$scope[identifier] = instance; } return instance; }; }]; } /** * @ngdoc object * @name ng.$document * @requires $window * * @description * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document` * element. */ function $DocumentProvider(){ this.$get = ['$window', function(window){ return jqLite(window.document); }]; } /** * @ngdoc function * @name ng.$exceptionHandler * @requires $log * * @description * Any uncaught exception in angular expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing. * * @param {Error} exception Exception associated with the error. * @param {string=} cause optional information about the context in which * the error was thrown. * */ function $ExceptionHandlerProvider() { this.$get = ['$log', function($log) { return function(exception, cause) { $log.error.apply($log, arguments); }; }]; } /** * @ngdoc object * @name ng.$interpolateProvider * @function * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. */ function $InterpolateProvider() { var startSymbol = '{{'; var endSymbol = '}}'; /** * @ngdoc method * @name ng.$interpolateProvider#startSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote start of expression in the interpolated string. Defaults to `{{`. * * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.startSymbol = function(value){ if (value) { startSymbol = value; return this; } else { return startSymbol; } }; /** * @ngdoc method * @name ng.$interpolateProvider#endSymbol * @methodOf ng.$interpolateProvider * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ this.endSymbol = function(value){ if (value) { endSymbol = value; return this; } else { return endSymbol; } }; this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) { var startSymbolLength = startSymbol.length, endSymbolLength = endSymbol.length; /** * @ngdoc function * @name ng.$interpolate * @function * * @requires $parse * * @description * * Compiles a string with markup into an interpolation function. This service is used by the * HTML {@link ng.$compile $compile} service for data binding. See * {@link ng.$interpolateProvider $interpolateProvider} for configuring the * interpolation markup. * * <pre> var $interpolate = ...; // injected var exp = $interpolate('Hello {{name}}!'); expect(exp({name:'Angular'}).toEqual('Hello Angular!'); </pre> * * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have * embedded expression in order to return an interpolation function. Strings with no * embedded expression will return null for the interpolation function. * @returns {function(context)} an interpolation function which is used to compute the interpolated * string. The function has these parameters: * * * `context`: an object against which any expressions embedded in the strings are evaluated * against. * */ function $interpolate(text, mustHaveExpression) { var startIndex, endIndex, index = 0, parts = [], length = text.length, hasInterpolation = false, fn, exp, concat = []; while(index < length) { if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { (index != startIndex) && parts.push(text.substring(index, startIndex)); parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); fn.exp = exp; index = endIndex + endSymbolLength; hasInterpolation = true; } else { // we did not find anything, so we have to add the remainder to the parts array (index != length) && parts.push(text.substring(index)); index = length; } } if (!(length = parts.length)) { // we added, nothing, must have been an empty string. parts.push(''); length = 1; } if (!mustHaveExpression || hasInterpolation) { concat.length = length; fn = function(context) { try { for(var i = 0, ii = length, part; i<ii; i++) { if (typeof (part = parts[i]) == 'function') { part = part(context); if (part == null || part == undefined) { part = ''; } else if (typeof part != 'string') { part = toJson(part); } } concat[i] = part; } return concat.join(''); } catch(err) { var newErr = new Error('Error while interpolating: ' + text + '\n' + err.toString()); $exceptionHandler(newErr); } }; fn.exp = text; fn.parts = parts; return fn; } } /** * @ngdoc method * @name ng.$interpolate#startSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.startSymbol = function() { return startSymbol; } /** * @ngdoc method * @name ng.$interpolate#endSymbol * @methodOf ng.$interpolate * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change * the symbol. * * @returns {string} start symbol. */ $interpolate.endSymbol = function() { return endSymbol; } return $interpolate; }]; } var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/, PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; /** * Encode path using encodeUriSegment, ignoring forward slashes * * @param {string} path Path to encode * @returns {string} */ function encodePath(path) { var segments = path.split('/'), i = segments.length; while (i--) { segments[i] = encodeUriSegment(segments[i]); } return segments.join('/'); } function matchUrl(url, obj) { var match = SERVER_MATCH.exec(url); obj.$$protocol = match[1]; obj.$$host = match[3]; obj.$$port = int(match[5]) || DEFAULT_PORTS[match[1]] || null; } function matchAppUrl(url, obj) { var match = PATH_MATCH.exec(url); obj.$$path = decodeURIComponent(match[1]); obj.$$search = parseKeyValue(match[3]); obj.$$hash = decodeURIComponent(match[5] || ''); // make sure path starts with '/'; if (obj.$$path && obj.$$path.charAt(0) != '/') obj.$$path = '/' + obj.$$path; } function composeProtocolHostPort(protocol, host, port) { return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port); } /** * * @param {string} begin * @param {string} whole * @param {string} otherwise * @returns {string} returns text from whole after begin or otherwise if it does not begin with expected string. */ function beginsWith(begin, whole, otherwise) { return whole.indexOf(begin) == 0 ? whole.substr(begin.length) : otherwise; } function stripHash(url) { var index = url.indexOf('#'); return index == -1 ? url : url.substr(0, index); } function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } /* return the server only */ function serverBase(url) { return url.substring(0, url.indexOf('/', url.indexOf('//') + 2)); } /** * LocationHtml5Url represents an url * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} appBase application base URL * @param {string} basePrefix url path prefix */ function LocationHtml5Url(appBase, basePrefix) { basePrefix = basePrefix || ''; var appBaseNoFile = stripFile(appBase); /** * Parse given html5 (regular) url string into properties * @param {string} newAbsoluteUrl HTML5 url * @private */ this.$$parse = function(url) { var parsed = {} matchUrl(url, parsed); var pathUrl = beginsWith(appBaseNoFile, url); if (!isString(pathUrl)) { throw Error('Invalid url "' + url + '", missing path prefix "' + appBaseNoFile + '".'); } matchAppUrl(pathUrl, parsed); extend(this, parsed); if (!this.$$path) { this.$$path = '/'; } this.$$compose(); }; /** * Compose url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' }; this.$$rewrite = function(url) { var appUrl, prevAppUrl; if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { prevAppUrl = appUrl; if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); } else { return appBase + prevAppUrl; } } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { return appBaseNoFile + appUrl; } else if (appBaseNoFile == url + '/') { return appBaseNoFile; } } } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is disabled or not supported * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangUrl(appBase, hashPrefix) { var appBaseNoFile = stripFile(appBase); /** * Parse given hashbang url into properties * @param {string} url Hashbang url * @private */ this.$$parse = function(url) { matchUrl(url, this); var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); if (!isString(withoutBaseUrl)) { throw new Error('Invalid url "' + url + '", does not start with "' + appBase + '".'); } var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' ? beginsWith(hashPrefix, withoutBaseUrl) : withoutBaseUrl; if (!isString(withoutHashUrl)) { throw new Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '".'); } matchAppUrl(withoutHashUrl, this); this.$$compose(); }; /** * Compose hashbang url and update `absUrl` property * @private */ this.$$compose = function() { var search = toKeyValue(this.$$search), hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); }; this.$$rewrite = function(url) { if(stripHash(appBase) == stripHash(url)) { return url; } } } /** * LocationHashbangUrl represents url * This object is exposed as $location service when html5 history api is enabled but the browser * does not support it. * * @constructor * @param {string} appBase application base URL * @param {string} hashPrefix hashbang prefix */ function LocationHashbangInHtml5Url(appBase, hashPrefix) { LocationHashbangUrl.apply(this, arguments); var appBaseNoFile = stripFile(appBase); this.$$rewrite = function(url) { var appUrl; if ( appBase == stripHash(url) ) { return url; } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { return appBase + hashPrefix + appUrl; } else if ( appBaseNoFile === url + '/') { return appBaseNoFile; } } } LocationHashbangInHtml5Url.prototype = LocationHashbangUrl.prototype = LocationHtml5Url.prototype = { /** * Has any change been replacing ? * @private */ $$replace: false, /** * @ngdoc method * @name ng.$location#absUrl * @methodOf ng.$location * * @description * This method is getter only. * * Return full url representation with all segments encoded according to rules specified in * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}. * * @return {string} full url */ absUrl: locationGetter('$$absUrl'), /** * @ngdoc method * @name ng.$location#url * @methodOf ng.$location * * @description * This method is getter / setter. * * Return url (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url, replace) { if (isUndefined(url)) return this.$$url; var match = PATH_MATCH.exec(url); if (match[1]) this.path(decodeURIComponent(match[1])); if (match[2] || match[1]) this.search(match[3] || ''); this.hash(match[5] || '', replace); return this; }, /** * @ngdoc method * @name ng.$location#protocol * @methodOf ng.$location * * @description * This method is getter only. * * Return protocol of current url. * * @return {string} protocol of current url */ protocol: locationGetter('$$protocol'), /** * @ngdoc method * @name ng.$location#host * @methodOf ng.$location * * @description * This method is getter only. * * Return host of current url. * * @return {string} host of current url. */ host: locationGetter('$$host'), /** * @ngdoc method * @name ng.$location#port * @methodOf ng.$location * * @description * This method is getter only. * * Return port of current url. * * @return {Number} port */ port: locationGetter('$$port'), /** * @ngdoc method * @name ng.$location#path * @methodOf ng.$location * * @description * This method is getter / setter. * * Return path of current url when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * * @param {string=} path New path * @return {string} path */ path: locationGetterSetter('$$path', function(path) { return path.charAt(0) == '/' ? path : '/' + path; }), /** * @ngdoc method * @name ng.$location#search * @methodOf ng.$location * * @description * This method is getter / setter. * * Return search part (as object) of current url when called without any parameter. * * Change search part when called with parameter and return `$location`. * * @param {string|object<string,string>=} search New search params - string or hash object * @param {string=} paramValue If `search` is a string, then `paramValue` will override only a * single search parameter. If the value is `null`, the parameter will be deleted. * * @return {string} search */ search: function(search, paramValue) { if (isUndefined(search)) return this.$$search; if (isDefined(paramValue)) { if (paramValue === null) { delete this.$$search[search]; } else { this.$$search[search] = paramValue; } } else { this.$$search = isString(search) ? parseKeyValue(search) : search; } this.$$compose(); return this; }, /** * @ngdoc method * @name ng.$location#hash * @methodOf ng.$location * * @description * This method is getter / setter. * * Return hash fragment when called without any parameter. * * Change hash fragment when called with parameter and return `$location`. * * @param {string=} hash New hash fragment * @return {string} hash */ hash: locationGetterSetter('$$hash', identity), /** * @ngdoc method * @name ng.$location#replace * @methodOf ng.$location * * @description * If called, all changes to $location during current `$digest` will be replacing current history * record, instead of adding new one. */ replace: function() { this.$$replace = true; return this; } }; function locationGetter(property) { return function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { return function(value) { if (isUndefined(value)) return this[property]; this[property] = preprocess(value); this.$$compose(); return this; }; } /** * @ngdoc object * @name ng.$location * * @requires $browser * @requires $sniffer * @requires $rootElement * * @description * The $location service parses the URL in the browser address bar (based on the * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL * available to your application. Changes to the URL in the address bar are reflected into * $location service and changes to $location are reflected into the browser address bar. * * **The $location service:** * * - Exposes the current URL in the browser address bar, so you can * - Watch and observe the URL. * - Change the URL. * - Synchronizes the URL with the browser when the user * - Changes the address bar. * - Clicks the back or forward button (or clicks a History link). * - Clicks on a link. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash). * * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular * Services: Using $location} */ /** * @ngdoc object * @name ng.$locationProvider * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ function $LocationProvider(){ var hashPrefix = '', html5Mode = false; /** * @ngdoc property * @name ng.$locationProvider#hashPrefix * @methodOf ng.$locationProvider * @description * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.hashPrefix = function(prefix) { if (isDefined(prefix)) { hashPrefix = prefix; return this; } else { return hashPrefix; } }; /** * @ngdoc property * @name ng.$locationProvider#html5Mode * @methodOf ng.$locationProvider * @description * @param {string=} mode Use HTML5 strategy if available. * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { if (isDefined(mode)) { html5Mode = mode; return this; } else { return html5Mode; } }; this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', function( $rootScope, $browser, $sniffer, $rootElement) { var $location, LocationMode, baseHref = $browser.baseHref(), initialUrl = $browser.url(), appBase; if (html5Mode) { appBase = baseHref ? serverBase(initialUrl) + baseHref : initialUrl; LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } $location = new LocationMode(appBase, '#' + hashPrefix); $location.$$parse($location.$$rewrite(initialUrl)); $rootElement.bind('click', function(event) { // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then if (event.ctrlKey || event.metaKey || event.which == 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag while (lowercase(elm[0].nodeName) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } var absHref = elm.prop('href'); var rewrittenUrl = $location.$$rewrite(absHref); if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { event.preventDefault(); if (rewrittenUrl != $browser.url()) { // update location manually $location.$$parse(rewrittenUrl); $rootScope.$apply(); // hack to work around FF6 bug 684208 when scenario runner clicks on links window.angular['ff-684208-preventDefault'] = true; } } }); // rewrite hashbang url <> html5 url if ($location.absUrl() != initialUrl) { $browser.url($location.absUrl(), true); } // update $location when $browser url changes $browser.onUrlChange(function(newUrl) { if ($location.absUrl() != newUrl) { if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) { $browser.url($location.absUrl()); return; } $rootScope.$evalAsync(function() { var oldUrl = $location.absUrl(); $location.$$parse(newUrl); afterLocationChange(oldUrl); }); if (!$rootScope.$$phase) $rootScope.$digest(); } }); // update browser var changeCounter = 0; $rootScope.$watch(function $locationWatch() { var oldUrl = $browser.url(); var currentReplace = $location.$$replace; if (!changeCounter || oldUrl != $location.absUrl()) { changeCounter++; $rootScope.$evalAsync(function() { if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). defaultPrevented) { $location.$$parse(oldUrl); } else { $browser.url($location.absUrl(), currentReplace); afterLocationChange(oldUrl); } }); } $location.$$replace = false; return changeCounter; }); return $location; function afterLocationChange(oldUrl) { $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); } }]; } /** * @ngdoc object * @name ng.$log * @requires $window * * @description * Simple service for logging. Default implementation writes the message * into the browser's console (if present). * * The main purpose of this service is to simplify debugging and troubleshooting. * * @example <example> <file name="script.js"> function LogCtrl($scope, $log) { $scope.$log = $log; $scope.message = 'Hello World!'; } </file> <file name="index.html"> <div ng-controller="LogCtrl"> <p>Reload this page with open console, enter text and hit the log button...</p> Message: <input type="text" ng-model="message"/> <button ng-click="$log.log(message)">log</button> <button ng-click="$log.warn(message)">warn</button> <button ng-click="$log.info(message)">info</button> <button ng-click="$log.error(message)">error</button> </div> </file> </example> */ /** * @ngdoc object * @name ng.$logProvider * @description * Use the `$logProvider` to configure how the application logs messages */ function $LogProvider(){ var debug = true, self = this; /** * @ngdoc property * @name ng.$logProvider#debugEnabled * @methodOf ng.$logProvider * @description * @param {string=} flag enable or disable debug level messages * @returns {*} current value if used as getter or itself (chaining) if used as setter */ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; return this; } else { return debug; } }; this.$get = ['$window', function($window){ return { /** * @ngdoc method * @name ng.$log#log * @methodOf ng.$log * * @description * Write a log message */ log: consoleLog('log'), /** * @ngdoc method * @name ng.$log#warn * @methodOf ng.$log * * @description * Write a warning message */ warn: consoleLog('warn'), /** * @ngdoc method * @name ng.$log#info * @methodOf ng.$log * * @description * Write an information message */ info: consoleLog('info'), /** * @ngdoc method * @name ng.$log#error * @methodOf ng.$log * * @description * Write an error message */ error: consoleLog('error'), /** * @ngdoc method * @name ng.$log#debug * @methodOf ng.$log * * @description * Write a debug message */ debug: (function () { var fn = consoleLog('debug'); return function() { if (debug) { fn.apply(self, arguments); } } }()) }; function formatError(arg) { if (arg instanceof Error) { if (arg.stack) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; } else if (arg.sourceURL) { arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line; } } return arg; } function consoleLog(type) { var console = $window.console || {}, logFn = console[type] || console.log || noop; if (logFn.apply) { return function() { var args = []; forEach(arguments, function(arg) { args.push(formatError(arg)); }); return logFn.apply(console, args); }; } // we are IE which either doesn't have window.console => this is noop and we do nothing, // or we are IE where console.log doesn't have apply so we log at least first 2 args return function(arg1, arg2) { logFn(arg1, arg2); } } }]; } var OPERATORS = { 'null':function(){return null;}, 'true':function(){return true;}, 'false':function(){return false;}, undefined:noop, '+':function(self, locals, a,b){ a=a(self, locals); b=b(self, locals); if (isDefined(a)) { if (isDefined(b)) { return a + b; } return a; } return isDefined(b)?b:undefined;}, '-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);}, '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, '=':noop, '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);}, '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, // '|':function(self, locals, a,b){return a|b;}, '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, '!':function(self, locals, a){return !a(self, locals);} }; var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; function lex(text, csp){ var tokens = [], token, index = 0, json = [], ch, lastCh = ':'; // can start regexp while (index < text.length) { ch = text.charAt(index); if (is('"\'')) { readString(ch); } else if (isNumber(ch) || is('.') && isNumber(peek())) { readNumber(); } else if (isIdent(ch)) { readIdent(); // identifiers can only be if the preceding char was a { or , if (was('{,') && json[0]=='{' && (token=tokens[tokens.length-1])) { token.json = token.text.indexOf('.') == -1; } } else if (is('(){}[].,;:?')) { tokens.push({ index:index, text:ch, json:(was(':[,') && is('{[')) || is('}]:,') }); if (is('{[')) json.unshift(ch); if (is('}]')) json.shift(); index++; } else if (isWhitespace(ch)) { index++; continue; } else { var ch2 = ch + peek(), ch3 = ch2 + peek(2), fn = OPERATORS[ch], fn2 = OPERATORS[ch2], fn3 = OPERATORS[ch3]; if (fn3) { tokens.push({index:index, text:ch3, fn:fn3}); index += 3; } else if (fn2) { tokens.push({index:index, text:ch2, fn:fn2}); index += 2; } else if (fn) { tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')}); index += 1; } else { throwError("Unexpected next character ", index, index+1); } } lastCh = ch; } return tokens; function is(chars) { return chars.indexOf(ch) != -1; } function was(chars) { return chars.indexOf(lastCh) != -1; } function peek(i) { var num = i || 1; return index + num < text.length ? text.charAt(index + num) : false; } function isNumber(ch) { return '0' <= ch && ch <= '9'; } function isWhitespace(ch) { return ch == ' ' || ch == '\r' || ch == '\t' || ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0 } function isIdent(ch) { return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' == ch || ch == '$'; } function isExpOperator(ch) { return ch == '-' || ch == '+' || isNumber(ch); } function throwError(error, start, end) { end = end || index; throw Error("Lexer Error: " + error + " at column" + (isDefined(start) ? "s " + start + "-" + index + " [" + text.substring(start, end) + "]" : " " + end) + " in expression [" + text + "]."); } function readNumber() { var number = ""; var start = index; while (index < text.length) { var ch = lowercase(text.charAt(index)); if (ch == '.' || isNumber(ch)) { number += ch; } else { var peekCh = peek(); if (ch == 'e' && isExpOperator(peekCh)) { number += ch; } else if (isExpOperator(ch) && peekCh && isNumber(peekCh) && number.charAt(number.length - 1) == 'e') { number += ch; } else if (isExpOperator(ch) && (!peekCh || !isNumber(peekCh)) && number.charAt(number.length - 1) == 'e') { throwError('Invalid exponent'); } else { break; } } index++; } number = 1 * number; tokens.push({index:start, text:number, json:true, fn:function() {return number;}}); } function readIdent() { var ident = "", start = index, lastDot, peekIndex, methodName, ch; while (index < text.length) { ch = text.charAt(index); if (ch == '.' || isIdent(ch) || isNumber(ch)) { if (ch == '.') lastDot = index; ident += ch; } else { break; } index++; } //check if this is not a method invocation and if it is back out to last dot if (lastDot) { peekIndex = index; while(peekIndex < text.length) { ch = text.charAt(peekIndex); if (ch == '(') { methodName = ident.substr(lastDot - start + 1); ident = ident.substr(0, lastDot - start); index = peekIndex; break; } if(isWhitespace(ch)) { peekIndex++; } else { break; } } } var token = { index:start, text:ident }; if (OPERATORS.hasOwnProperty(ident)) { token.fn = token.json = OPERATORS[ident]; } else { var getter = getterFn(ident, csp); token.fn = extend(function(self, locals) { return (getter(self, locals)); }, { assign: function(self, value) { return setter(self, ident, value); } }); } tokens.push(token); if (methodName) { tokens.push({ index:lastDot, text: '.', json: false }); tokens.push({ index: lastDot + 1, text: methodName, json: false }); } } function readString(quote) { var start = index; index++; var string = ""; var rawString = quote; var escape = false; while (index < text.length) { var ch = text.charAt(index); rawString += ch; if (escape) { if (ch == 'u') { var hex = text.substring(index + 1, index + 5); if (!hex.match(/[\da-f]{4}/i)) throwError( "Invalid unicode escape [\\u" + hex + "]"); index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; if (rep) { string += rep; } else { string += ch; } } escape = false; } else if (ch == '\\') { escape = true; } else if (ch == quote) { index++; tokens.push({ index:start, text:rawString, string:string, json:true, fn:function() { return string; } }); return; } else { string += ch; } index++; } throwError("Unterminated quote", start); } } ///////////////////////////////////////// function parser(text, json, $filter, csp){ var ZERO = valueFn(0), value, tokens = lex(text, csp), assignment = _assignment, functionCall = _functionCall, fieldAccess = _fieldAccess, objectIndex = _objectIndex, filterChain = _filterChain; if(json){ // The extra level of aliasing is here, just in case the lexer misses something, so that // we prevent any accidental execution in JSON. assignment = logicalOR; functionCall = fieldAccess = objectIndex = filterChain = function() { throwError("is not valid json", {text:text, index:0}); }; value = primary(); } else { value = statements(); } if (tokens.length !== 0) { throwError("is an unexpected token", tokens[0]); } value.literal = !!value.literal; value.constant = !!value.constant; return value; /////////////////////////////////// function throwError(msg, token) { throw Error("Syntax Error: Token '" + token.text + "' " + msg + " at column " + (token.index + 1) + " of the expression [" + text + "] starting at [" + text.substring(token.index) + "]."); } function peekToken() { if (tokens.length === 0) throw Error("Unexpected end of expression: " + text); return tokens[0]; } function peek(e1, e2, e3, e4) { if (tokens.length > 0) { var token = tokens[0]; var t = token.text; if (t==e1 || t==e2 || t==e3 || t==e4 || (!e1 && !e2 && !e3 && !e4)) { return token; } } return false; } function expect(e1, e2, e3, e4){ var token = peek(e1, e2, e3, e4); if (token) { if (json && !token.json) { throwError("is not valid json", token); } tokens.shift(); return token; } return false; } function consume(e1){ if (!expect(e1)) { throwError("is unexpected, expecting [" + e1 + "]", peek()); } } function unaryFn(fn, right) { return extend(function(self, locals) { return fn(self, locals, right); }, { constant:right.constant }); } function ternaryFn(left, middle, right){ return extend(function(self, locals){ return left(self, locals) ? middle(self, locals) : right(self, locals); }, { constant: left.constant && middle.constant && right.constant }); } function binaryFn(left, fn, right) { return extend(function(self, locals) { return fn(self, locals, left, right); }, { constant:left.constant && right.constant }); } function statements() { var statements = []; while(true) { if (tokens.length > 0 && !peek('}', ')', ';', ']')) statements.push(filterChain()); if (!expect(';')) { // optimize for the common case where there is only one statement. // TODO(size): maybe we should not support multiple statements? return statements.length == 1 ? statements[0] : function(self, locals){ var value; for ( var i = 0; i < statements.length; i++) { var statement = statements[i]; if (statement) value = statement(self, locals); } return value; }; } } } function _filterChain() { var left = expression(); var token; while(true) { if ((token = expect('|'))) { left = binaryFn(left, token.fn, filter()); } else { return left; } } } function filter() { var token = expect(); var fn = $filter(token.text); var argsFn = []; while(true) { if ((token = expect(':'))) { argsFn.push(expression()); } else { var fnInvoke = function(self, locals, input){ var args = [input]; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](self, locals)); } return fn.apply(self, args); }; return function() { return fnInvoke; }; } } } function expression() { return assignment(); } function _assignment() { var left = ternary(); var right; var token; if ((token = expect('='))) { if (!left.assign) { throwError("implies assignment but [" + text.substring(0, token.index) + "] can not be assigned to", token); } right = ternary(); return function(scope, locals){ return left.assign(scope, right(scope, locals), locals); }; } else { return left; } } function ternary() { var left = logicalOR(); var middle; var token; if((token = expect('?'))){ middle = ternary(); if((token = expect(':'))){ return ternaryFn(left, middle, ternary()); } else { throwError('expected :', token); } } else { return left; } } function logicalOR() { var left = logicalAND(); var token; while(true) { if ((token = expect('||'))) { left = binaryFn(left, token.fn, logicalAND()); } else { return left; } } } function logicalAND() { var left = equality(); var token; if ((token = expect('&&'))) { left = binaryFn(left, token.fn, logicalAND()); } return left; } function equality() { var left = relational(); var token; if ((token = expect('==','!=','===','!=='))) { left = binaryFn(left, token.fn, equality()); } return left; } function relational() { var left = additive(); var token; if ((token = expect('<', '>', '<=', '>='))) { left = binaryFn(left, token.fn, relational()); } return left; } function additive() { var left = multiplicative(); var token; while ((token = expect('+','-'))) { left = binaryFn(left, token.fn, multiplicative()); } return left; } function multiplicative() { var left = unary(); var token; while ((token = expect('*','/','%'))) { left = binaryFn(left, token.fn, unary()); } return left; } function unary() { var token; if (expect('+')) { return primary(); } else if ((token = expect('-'))) { return binaryFn(ZERO, token.fn, unary()); } else if ((token = expect('!'))) { return unaryFn(token.fn, unary()); } else { return primary(); } } function primary() { var primary; if (expect('(')) { primary = filterChain(); consume(')'); } else if (expect('[')) { primary = arrayDeclaration(); } else if (expect('{')) { primary = object(); } else { var token = expect(); primary = token.fn; if (!primary) { throwError("not a primary expression", token); } if (token.json) { primary.constant = primary.literal = true; } } var next, context; while ((next = expect('(', '[', '.'))) { if (next.text === '(') { primary = functionCall(primary, context); context = null; } else if (next.text === '[') { context = primary; primary = objectIndex(primary); } else if (next.text === '.') { context = primary; primary = fieldAccess(primary); } else { throwError("IMPOSSIBLE"); } } return primary; } function _fieldAccess(object) { var field = expect().text; var getter = getterFn(field, csp); return extend( function(scope, locals, self) { return getter(self || object(scope, locals), locals); }, { assign:function(scope, value, locals) { return setter(object(scope, locals), field, value); } } ); } function _objectIndex(obj) { var indexFn = expression(); consume(']'); return extend( function(self, locals){ var o = obj(self, locals), i = indexFn(self, locals), v, p; if (!o) return undefined; v = o[i]; if (v && v.then) { p = v; if (!('$$v' in v)) { p.$$v = undefined; p.then(function(val) { p.$$v = val; }); } v = v.$$v; } return v; }, { assign:function(self, value, locals){ return obj(self, locals)[indexFn(self, locals)] = value; } }); } function _functionCall(fn, contextGetter) { var argsFn = []; if (peekToken().text != ')') { do { argsFn.push(expression()); } while (expect(',')); } consume(')'); return function(scope, locals){ var args = [], context = contextGetter ? contextGetter(scope, locals) : scope; for ( var i = 0; i < argsFn.length; i++) { args.push(argsFn[i](scope, locals)); } var fnPtr = fn(scope, locals, context) || noop; // IE stupidity! return fnPtr.apply ? fnPtr.apply(context, args) : fnPtr(args[0], args[1], args[2], args[3], args[4]); }; } // This is used with json array declaration function arrayDeclaration () { var elementFns = []; var allConstant = true; if (peekToken().text != ']') { do { var elementFn = expression(); elementFns.push(elementFn); if (!elementFn.constant) { allConstant = false; } } while (expect(',')); } consume(']'); return extend(function(self, locals){ var array = []; for ( var i = 0; i < elementFns.length; i++) { array.push(elementFns[i](self, locals)); } return array; }, { literal:true, constant:allConstant }); } function object () { var keyValues = []; var allConstant = true; if (peekToken().text != '}') { do { var token = expect(), key = token.string || token.text; consume(":"); var value = expression(); keyValues.push({key:key, value:value}); if (!value.constant) { allConstant = false; } } while (expect(',')); } consume('}'); return extend(function(self, locals){ var object = {}; for ( var i = 0; i < keyValues.length; i++) { var keyValue = keyValues[i]; object[keyValue.key] = keyValue.value(self, locals); } return object; }, { literal:true, constant:allConstant }); } } ////////////////////////////////////////////////// // Parser helper functions ////////////////////////////////////////////////// function setter(obj, path, setValue) { var element = path.split('.'); for (var i = 0; element.length > 1; i++) { var key = element.shift(); var propertyObj = obj[key]; if (!propertyObj) { propertyObj = {}; obj[key] = propertyObj; } obj = propertyObj; } obj[element.shift()] = setValue; return setValue; } /** * Return the value accessible from the object by path. Any undefined traversals are ignored * @param {Object} obj starting object * @param {string} path path to traverse * @param {boolean=true} bindFnToScope * @returns value as accessible by path */ //TODO(misko): this function needs to be removed function getter(obj, path, bindFnToScope) { if (!path) return obj; var keys = path.split('.'); var key; var lastInstance = obj; var len = keys.length; for (var i = 0; i < len; i++) { key = keys[i]; if (obj) { obj = (lastInstance = obj)[key]; } } if (!bindFnToScope && isFunction(obj)) { return bind(lastInstance, obj); } return obj; } var getterFnCache = {}; /** * Implementation of the "Black Hole" variant from: * - http://jsperf.com/angularjs-parse-getter/4 * - http://jsperf.com/path-evaluation-simplified/7 */ function cspSafeGetterFn(key0, key1, key2, key3, key4) { return function(scope, locals) { var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, promise; if (pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key0]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key1 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key1]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key2 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key2]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key3 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key3]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } if (!key4 || pathVal === null || pathVal === undefined) return pathVal; pathVal = pathVal[key4]; if (pathVal && pathVal.then) { if (!("$$v" in pathVal)) { promise = pathVal; promise.$$v = undefined; promise.then(function(val) { promise.$$v = val; }); } pathVal = pathVal.$$v; } return pathVal; }; } function getterFn(path, csp) { if (getterFnCache.hasOwnProperty(path)) { return getterFnCache[path]; } var pathKeys = path.split('.'), pathKeysLength = pathKeys.length, fn; if (csp) { fn = (pathKeysLength < 6) ? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4]) : function(scope, locals) { var i = 0, val; do { val = cspSafeGetterFn( pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++] )(scope, locals); locals = undefined; // clear after first iteration scope = val; } while (i < pathKeysLength); return val; } } else { var code = 'var l, fn, p;\n'; forEach(pathKeys, function(key, index) { code += 'if(s === null || s === undefined) return s;\n' + 'l=s;\n' + 's='+ (index // we simply dereference 's' on any .dot notation ? 's' // but if we are first then we check locals first, and if so read it first : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + 'if (s && s.then) {\n' + ' if (!("$$v" in s)) {\n' + ' p=s;\n' + ' p.$$v = undefined;\n' + ' p.then(function(v) {p.$$v=v;});\n' + '}\n' + ' s=s.$$v\n' + '}\n'; }); code += 'return s;'; fn = Function('s', 'k', code); // s=scope, k=locals fn.toString = function() { return code; }; } return getterFnCache[path] = fn; } /////////////////////////////////// /** * @ngdoc function * @name ng.$parse * @function * * @description * * Converts Angular {@link guide/expression expression} into a function. * * <pre> * var getter = $parse('user.name'); * var setter = getter.assign; * var context = {user:{name:'angular'}}; * var locals = {user:{name:'local'}}; * * expect(getter(context)).toEqual('angular'); * setter(context, 'newValue'); * expect(context.user.name).toEqual('newValue'); * expect(getter(context, locals)).toEqual('local'); * </pre> * * * @param {string} expression String expression to compile. * @returns {function(context, locals)} a function which represents the compiled expression: * * * `context` – `{object}` – an object against which any expressions embedded in the strings * are evaluated against (typically a scope object). * * `locals` – `{object=}` – local variables context object, useful for overriding values in * `context`. * * The returned function also has the following properties: * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript * literal. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript * constant literals. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be * set to a function to change its value on the given context. * */ function $ParseProvider() { var cache = {}; this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { return function(exp) { switch(typeof exp) { case 'string': return cache.hasOwnProperty(exp) ? cache[exp] : cache[exp] = parser(exp, false, $filter, $sniffer.csp); case 'function': return exp; default: return noop; } }; }]; } /** * @ngdoc service * @name ng.$q * @requires $rootScope * * @description * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is * performed asynchronously, and may or may not be finished at any given point in time. * * From the perspective of dealing with error handling, deferred and promise APIs are to * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * * <pre> * // for the purpose of this example let's assume that variables `$q` and `scope` are * // available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { * // since this fn executes async in a future turn of the event loop, we need to wrap * // our code into an $apply call so that the model changes are properly observed. * scope.$apply(function() { * if (okToGreet(name)) { * deferred.resolve('Hello, ' + name + '!'); * } else { * deferred.reject('Greeting ' + name + ' is not allowed.'); * } * }); * }, 1000); * * return deferred.promise; * } * * var promise = asyncGreet('Robin Hood'); * promise.then(function(greeting) { * alert('Success: ' + greeting); * }, function(reason) { * alert('Failed: ' + reason); * }); * </pre> * * At first it might not be obvious why this extra complexity is worth the trouble. The payoff * comes in the way of * [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md). * * Additionally the promise api allows for composition that is very hard to do with the * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * * * # The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * * The purpose of the deferred object is to expose the associated Promise instance as well as APIs * that can be used for signaling the successful or unsuccessful completion of the task. * * **Methods** * * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection * constructed via `$q.reject`, the promise will be rejected instead. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to * resolving it with a rejection constructed via `$q.reject`. * * **Properties** * * - promise – `{Promise}` – promise object associated with this deferred. * * * # The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. * * The purpose of the promise object is to allow for interested parties to get access to the result * of the deferred task when it completes. * * **Methods** * * - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved * or rejected calls one of the success or error callbacks asynchronously as soon as the result * is available. The callbacks are called with a single argument the result or rejection reason. * * This method *returns a new promise* which is resolved or rejected via the return value of the * `successCallback` or `errorCallback`. * * - `always(callback)` – allows you to observe either the fulfillment or rejection of a promise, * but to do so without modifying the final value. This is useful to release resources or do some * clean-up that needs to be done whether the promise was rejected or resolved. See the [full * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for * more information. * * # Chaining promises * * Because calling `then` api of a promise returns a new derived promise, it is easily possible * to create a chain of promises: * * <pre> * promiseB = promiseA.then(function(result) { * return result + 1; * }); * * // promiseB will be resolved immediately after promiseA is resolved and its value will be * // the result of promiseA incremented by 1 * </pre> * * It is possible to create chains of any length and since a promise can be resolved with another * promise (which will defer its resolution further), it is possible to pause/defer resolution of * the promises at any point in the chain. This makes it possible to implement powerful apis like * $http's response interceptors. * * * # Differences between Kris Kowal's Q and $q * * There are three main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation * mechanism in angular, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - $q promises are recognized by the templating engine in angular, which means that in templates * you can treat promises attached to a scope as if they were the resulting values. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. * * # Testing * * <pre> * it('should simulate promise', inject(function($q, $rootScope) { * var deferred = $q.defer(); * var promise = deferred.promise; * var resolvedValue; * * promise.then(function(value) { resolvedValue = value; }); * expect(resolvedValue).toBeUndefined(); * * // Simulate resolving of promise * deferred.resolve(123); * // Note that the 'then' function does not get called synchronously. * // This is because we want the promise API to always be async, whether or not * // it got called synchronously or asynchronously. * expect(resolvedValue).toBeUndefined(); * * // Propagate promise resolution to 'then' functions using $apply(). * $rootScope.$apply(); * expect(resolvedValue).toEqual(123); * }); * </pre> */ function $QProvider() { this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); }, $exceptionHandler); }]; } /** * Constructs a promise manager. * * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. * @returns {object} Promise manager. */ function qFactory(nextTick, exceptionHandler) { /** * @ngdoc * @name ng.$q#defer * @methodOf ng.$q * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ var defer = function() { var pending = [], value, deferred; deferred = { resolve: function(val) { if (pending) { var callbacks = pending; pending = undefined; value = ref(val); if (callbacks.length) { nextTick(function() { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; value.then(callback[0], callback[1]); } }); } } }, reject: function(reason) { deferred.resolve(reject(reason)); }, promise: { then: function(callback, errback) { var result = defer(); var wrappedCallback = function(value) { try { result.resolve((callback || defaultCallback)(value)); } catch(e) { exceptionHandler(e); result.reject(e); } }; var wrappedErrback = function(reason) { try { result.resolve((errback || defaultErrback)(reason)); } catch(e) { exceptionHandler(e); result.reject(e); } }; if (pending) { pending.push([wrappedCallback, wrappedErrback]); } else { value.then(wrappedCallback, wrappedErrback); } return result.promise; }, always: function(callback) { function makePromise(value, resolved) { var result = defer(); if (resolved) { result.resolve(value); } else { result.reject(value); } return result.promise; } function handleCallback(value, isResolved) { var callbackOutput = null; try { callbackOutput = (callback ||defaultCallback)(); } catch(e) { return makePromise(e, false); } if (callbackOutput && callbackOutput.then) { return callbackOutput.then(function() { return makePromise(value, isResolved); }, function(error) { return makePromise(error, false); }); } else { return makePromise(value, isResolved); } } return this.then(function(value) { return handleCallback(value, true); }, function(error) { return handleCallback(error, false); }); } } }; return deferred; }; var ref = function(value) { if (value && value.then) return value; return { then: function(callback) { var result = defer(); nextTick(function() { result.resolve(callback(value)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#reject * @methodOf ng.$q * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be * used to forward rejection in a chain of promises. If you are dealing with the last promise in * a promise chain, you don't need to worry about it. * * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via * a promise error callback and you want to forward the error to the promise derived from the * current promise, you have to "rethrow" the error by returning a rejection constructed via * `reject`. * * <pre> * promiseB = promiseA.then(function(result) { * // success: do something and resolve promiseB * // with the old or a new result * return result; * }, function(reason) { * // error: handle the error if possible and * // resolve promiseB with newPromiseOrValue, * // otherwise forward the rejection to promiseB * if (canHandle(reason)) { * // handle the error and recover * return newPromiseOrValue; * } * return $q.reject(reason); * }); * </pre> * * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ var reject = function(reason) { return { then: function(callback, errback) { var result = defer(); nextTick(function() { result.resolve((errback || defaultErrback)(reason)); }); return result.promise; } }; }; /** * @ngdoc * @name ng.$q#when * @methodOf ng.$q * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. * This is useful when you are dealing with an object that might or might not be a promise, or if * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise * @returns {Promise} Returns a promise of the passed value or promise */ var when = function(value, callback, errback) { var result = defer(), done; var wrappedCallback = function(value) { try { return (callback || defaultCallback)(value); } catch (e) { exceptionHandler(e); return reject(e); } }; var wrappedErrback = function(reason) { try { return (errback || defaultErrback)(reason); } catch (e) { exceptionHandler(e); return reject(e); } }; nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); }); }); return result.promise; }; function defaultCallback(value) { return value; } function defaultErrback(reason) { return reject(reason); } /** * @ngdoc * @name ng.$q#all * @methodOf ng.$q * @description * Combines multiple promises into a single promise that is resolved when all of the input * promises are resolved. * * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, * each value corresponding to the promise at the same index/key in the `promises` array/hash. If any of * the promises is resolved with a rejection, this resulting promise will be resolved with the * same rejection. */ function all(promises) { var deferred = defer(), counter = 0, results = isArray(promises) ? [] : {}; forEach(promises, function(promise, key) { counter++; ref(promise).then(function(value) { if (results.hasOwnProperty(key)) return; results[key] = value; if (!(--counter)) deferred.resolve(results); }, function(reason) { if (results.hasOwnProperty(key)) return; deferred.reject(reason); }); }); if (counter === 0) { deferred.resolve(results); } return deferred.promise; } return { defer: defer, reject: reject, when: when, all: all }; } /** * @ngdoc object * @name ng.$routeProvider * @function * * @description * * Used for configuring routes. See {@link ng.$route $route} for an example. */ function $RouteProvider(){ var routes = {}; /** * @ngdoc method * @name ng.$routeProvider#when * @methodOf ng.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon (`:name`). All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a star (`*name`). All characters are * eagerly stored in `$routeParams` under the given `name` when the route matches. * * For example, routes like `/color/:color/largecode/*largecode/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly * created scope or the name of a {@link angular.Module#controller registered controller} * if passed as a string. * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or function that returns * an html template as a string which should be used by {@link ng.directive:ngView ngView} or * {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ng.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, they will be * resolved and converted to a value before the controller is instantiated and the * `$routeChangeSuccess` event is fired. The map object is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is resolved * before its value is injected into the controller. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search() * changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = extend({reloadOnSearch: true, caseInsensitiveMatch: false}, route); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = {redirectTo: path}; } return this; }; /** * @ngdoc method * @name ng.$routeProvider#otherwise * @methodOf ng.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) { /** * @ngdoc object * @name ng.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * Is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * You can define routes through {@link ng.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView} * directive and the {@link ng.$routeParams $routeParams} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngView"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); sleep(2); // promises are not part of scenario waiting content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.$route#$routeChangeStart * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occurs. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ng.$route#$routeChangeSuccess * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ng.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered. */ /** * @ngdoc event * @name ng.$route#$routeChangeError * @eventOf ng.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ng.$route#$routeUpdate * @eventOf ng.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ng.$route#reload * @methodOf ng.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ng.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param when {string} route when template to match the url against * @param whenProperties {Object} properties to define when's matching behavior * @return {?Object} */ function switchRouteMatcher(on, when, whenProperties) { // TODO(i): this code is convoluted and inefficient, we should construct the route matching // regex only once and then reuse it // Escape regexp special characters. when = '^' + when.replace(/[-\/\\^$:*+?.()|[\]{}]/g, "\\$&") + '$'; var regex = '', params = [], dst = {}; var re = /\\([:*])(\w+)/g, paramMatch, lastMatchedIndex = 0; while ((paramMatch = re.exec(when)) !== null) { // Find each :param in `when` and replace it with a capturing group. // Append all other sections of when unchanged. regex += when.slice(lastMatchedIndex, paramMatch.index); switch(paramMatch[1]) { case ':': regex += '([^\\/]*)'; break; case '*': regex += '(.*)'; break; } params.push(paramMatch[2]); lastMatchedIndex = re.lastIndex; } // Append trailing path part. regex += when.substr(lastMatchedIndex); var match = on.match(new RegExp(regex, whenProperties.caseInsensitiveMatch ? 'i' : '')); if (match) { forEach(params, function(name, index) { dst[name] = match[index + 1]; }); } return match ? dst : null; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = extend({}, next.resolve), template; forEach(locals, function(value, key) { locals[key] = isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (isDefined(template = next.template)) { if (isFunction(template)) { template = template(next.params); } } else if (isDefined(template = next.templateUrl)) { if (isFunction(template)) { template = template(next.params); } if (isDefined(template)) { next.loadedTemplateUrl = template; template = $http.get(template, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), path, route))) { match = inherit(route, { params: extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; forEach((string||'').split(':'), function(segment, i) { if (i == 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } /** * @ngdoc object * @name ng.$routeParams * @requires $route * * @description * Current set of route parameters. The route parameters are a combination of the * {@link ng.$location $location} `search()`, and `path()`. The `path` parameters * are extracted when the {@link ng.$route $route} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = valueFn({}); } /** * DESIGN NOTES * * The design decisions behind the scope are heavily favored for speed and memory consumption. * * The typical use of scope is to watch the expressions, which most of the time return the same * value as last time so we optimize the operation. * * Closures construction is expensive in terms of speed as well as memory: * - No closures, instead use prototypical inheritance for API * - Internal state needs to be stored on scope directly, which means that private state is * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } * - this means that in order to keep the same order of execution as addition we have to add * items to the array at the beginning (shift) instead of at the end (push) * * Child scopes are created and removed often * - Using an array would be slow since inserts in middle are expensive so we use linked list * * There are few watches then a lot of observers. This is why you don't want the observer to be * implemented in the same way as watch. Watch requires return of initialization function which * are expensive to construct. */ /** * @ngdoc object * @name ng.$rootScopeProvider * @description * * Provider for the $rootScope service. */ /** * @ngdoc function * @name ng.$rootScopeProvider#digestTtl * @methodOf ng.$rootScopeProvider * @description * * Sets the number of digest iterations the scope should attempt to execute before giving up and * assuming that the model is unstable. * * The current default is 10 iterations. * * @param {number} limit The number of digest iterations. */ /** * @ngdoc object * @name ng.$rootScope * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide * event processing life-cycle. See {@link guide/scope developer guide on scopes}. */ function $RootScopeProvider(){ var TTL = 10; this.digestTtl = function(value) { if (arguments.length) { TTL = value; } return TTL; }; this.$get = ['$injector', '$exceptionHandler', '$parse', function( $injector, $exceptionHandler, $parse) { /** * @ngdoc function * @name ng.$rootScope.Scope * * @description * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link AUTO.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when * compiled HTML template is executed.) * * Here is a simple scope snippet to show how you can interact with the scope. * <pre> * <file src="./test/ng/rootScopeSpec.js" tag="docs1" /> * </pre> * * # Inheritance * A scope can inherit from a parent scope, as in this example: * <pre> var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; expect(child.salutation).toEqual('Welcome'); expect(parent.salutation).toEqual('Hello'); * </pre> * * * @param {Object.<string, function()>=} providers Map of service factory which need to be provided * for the current scope. Defaults to {@link ng}. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should * append/override services provided by `providers`. This is handy when unit-testing and having * the need to override a default service. * @returns {Object} Newly created scope. * */ function Scope() { this.$id = nextUid(); this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; this['this'] = this.$root = this; this.$$destroyed = false; this.$$asyncQueue = []; this.$$listeners = {}; this.$$isolateBindings = {}; } /** * @ngdoc property * @name ng.$rootScope.Scope#$id * @propertyOf ng.$rootScope.Scope * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for * debugging. */ Scope.prototype = { /** * @ngdoc function * @name ng.$rootScope.Scope#$new * @methodOf ng.$rootScope.Scope * @function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope * hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * * @param {boolean} isolate if true then the scope does not prototypically inherit from the * parent scope. The scope is isolated, as it can not see parent scope properties. * When creating widgets it is useful for the widget to not accidentally read parent * state. * * @returns {Object} The newly created child scope. * */ $new: function(isolate) { var Child, child; if (isFunction(isolate)) { // TODO: remove at some point throw Error('API-CHANGE: Use $controller to instantiate controllers.'); } if (isolate) { child = new Scope(); child.$root = this.$root; } else { Child = function() {}; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. These will then show up as class // name in the debugger. Child.prototype = this; child = new Child(); child.$id = nextUid(); } child['this'] = child; child.$$listeners = {}; child.$parent = this; child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; child.$$prevSibling = this.$$childTail; if (this.$$childHead) { this.$$childTail.$$nextSibling = child; this.$$childTail = child; } else { this.$$childHead = this.$$childTail = child; } return child; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$watch * @methodOf ng.$rootScope.Scope * @function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and * should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()} * reruns when it detects changes the `watchExpression` can execute multiple times per * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, * see below). The inequality is determined according to * {@link angular.equals} function. To save the value of the object for later comparison, the * {@link angular.copy} function is used. It also means that watching complex options will * have adverse memory and performance implications. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. This * is achieved by rerunning the watchers until no changes are detected. The rerun iteration * limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is * detected, be prepared for multiple calls to your listener.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the * watcher. In rare cases, this is undesirable because the listener is called when the result * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * * * # Example * <pre> // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * * * * @param {(function()|string)} watchExpression Expression that is evaluated on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a * call to the `listener`. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. * @param {(function()|string)=} listener Callback called whenever the return value of * the `watchExpression` changes. * * - `string`: Evaluated as {@link guide/expression expression} * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters. * * @param {boolean=} objectEquality Compare object for equality rather than for reference. * @returns {function()} Returns a deregistration function for this listener. */ $watch: function(watchExp, listener, objectEquality) { var scope = this, get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { fn: listener, last: initWatchVal, get: get, exp: watchExp, eq: !!objectEquality }; // in the case user pass string, we need to compile it, do we really need this ? if (!isFunction(listener)) { var listenFn = compileToFn(listener || noop, 'listener'); watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; } if (typeof watchExp == 'string' && get.constant) { var originalFn = watcher.fn; watcher.fn = function(newVal, oldVal, scope) { originalFn.call(this, newVal, oldVal, scope); arrayRemove(array, watcher); }; } if (!array) { array = scope.$$watchers = []; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); return function() { arrayRemove(array, watcher); }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$watchCollection * @methodOf ng.$rootScope.Scope * @function * * @description * Shallow watches the properties of an object and fires whenever any of the properties change * (for arrays this implies watching the array items, for object maps this implies watching the properties). * If a change is detected the `listener` callback is fired. * * - The `obj` collection is observed via standard $watch operation and is examined on every call to $digest() to * see if any items have been added, removed, or moved. * - The `listener` is called whenever anything within the `obj` has changed. Examples include adding new items * into the object or array, removing and moving items around. * * * # Example * <pre> $scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; $scope.$watchCollection('names', function(newNames, oldNames) { $scope.dataCount = newNames.length; }); expect($scope.dataCount).toEqual(4); $scope.$digest(); //still at 4 ... no changes expect($scope.dataCount).toEqual(4); $scope.names.pop(); $scope.$digest(); //now there's been a change expect($scope.dataCount).toEqual(3); * </pre> * * * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The expression value * should evaluate to an object or an array which is observed on each * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the collection will trigger * a call to the `listener`. * * @param {function(newCollection, oldCollection, scope)} listener a callback function that is fired with both * the `newCollection` and `oldCollection` as parameters. * The `newCollection` object is the newly modified data obtained from the `obj` expression and the * `oldCollection` object is a copy of the former collection data. * The `scope` refers to the current scope. * * @returns {function()} Returns a de-registration function for this listener. When the de-registration function is executed * then the internal watch operation is terminated. */ $watchCollection: function(obj, listener) { var self = this; var oldValue; var newValue; var changeDetected = 0; var objGetter = $parse(obj); var internalArray = []; var internalObject = {}; var oldLength = 0; function $watchCollectionWatch() { newValue = objGetter(self); var newLength, key; if (!isObject(newValue)) { if (oldValue !== newValue) { oldValue = newValue; changeDetected++; } } else if (isArrayLike(newValue)) { if (oldValue !== internalArray) { // we are transitioning from something which was not an array into array. oldValue = internalArray; oldLength = oldValue.length = 0; changeDetected++; } newLength = newValue.length; if (oldLength !== newLength) { // if lengths do not match we need to trigger change notification changeDetected++; oldValue.length = oldLength = newLength; } // copy the items to oldValue and look for changes. for (var i = 0; i < newLength; i++) { if (oldValue[i] !== newValue[i]) { changeDetected++; oldValue[i] = newValue[i]; } } } else { if (oldValue !== internalObject) { // we are transitioning from something which was not an object into object. oldValue = internalObject = {}; oldLength = 0; changeDetected++; } // copy the items to oldValue and look for changes. newLength = 0; for (key in newValue) { if (newValue.hasOwnProperty(key)) { newLength++; if (oldValue.hasOwnProperty(key)) { if (oldValue[key] !== newValue[key]) { changeDetected++; oldValue[key] = newValue[key]; } } else { oldLength++; oldValue[key] = newValue[key]; changeDetected++; } } } if (oldLength > newLength) { // we used to have more keys, need to find them and destroy them. changeDetected++; for(key in oldValue) { if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { oldLength--; delete oldValue[key]; } } } } return changeDetected; } function $watchCollectionAction() { listener(newValue, oldValue, self); } return this.$watch($watchCollectionWatch, $watchCollectionAction); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$digest * @methodOf ng.$rootScope.Scope * @function * * @description * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children. * Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the * `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are * firing. This means that it is possible to get into an infinite loop. This function will throw * `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10. * * Usually you don't call `$digest()` directly in * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a * {@link ng.$compileProvider#directive directives}) will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()} * with no `listener`. * * You may have a need to call `$digest()` from within unit-tests, to simulate the scope * life-cycle. * * # Example * <pre> var scope = ...; scope.name = 'misko'; scope.counter = 0; expect(scope.counter).toEqual(0); scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); expect(scope.counter).toEqual(0); scope.$digest(); // no variable change expect(scope.counter).toEqual(0); scope.name = 'adam'; scope.$digest(); expect(scope.counter).toEqual(1); * </pre> * */ $digest: function() { var watch, value, last, watchers, asyncQueue = this.$$asyncQueue, length, dirty, ttl = TTL, next, current, target = this, watchLog = [], logIdx, logMsg; beginPhase('$digest'); do { // "while dirty" loop dirty = false; current = target; while(asyncQueue.length) { try { current.$eval(asyncQueue.shift()); } catch (e) { $exceptionHandler(e); } } do { // "traverse the scopes" loop if ((watchers = current.$$watchers)) { // process our watches length = watchers.length; while (length--) { try { watch = watchers[length]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if ((value = watch.get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) : (typeof value == 'number' && typeof last == 'number' && isNaN(value) && isNaN(last)))) { dirty = true; watch.last = watch.eq ? copy(value) : value; watch.fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; logMsg = (isFunction(watch.exp)) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp; logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); watchLog[logIdx].push(logMsg); } } } catch (e) { $exceptionHandler(e); } } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); if(dirty && !(ttl--)) { clearPhase(); throw Error(TTL + ' $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: ' + toJson(watchLog)); } } while (dirty || asyncQueue.length); clearPhase(); }, /** * @ngdoc event * @name ng.$rootScope.Scope#$destroy * @eventOf ng.$rootScope.Scope * @eventType broadcast on scope being destroyed * * @description * Broadcasted when a scope and its children are being destroyed. */ /** * @ngdoc function * @name ng.$rootScope.Scope#$destroy * @methodOf ng.$rootScope.Scope * @function * * @description * Removes the current scope (and all of its children) from the parent scope. Removal implies * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer * propagate to the current scope and its children. Removal also implies that the current * scope is eligible for garbage collection. * * The `$destroy()` is usually used by directives such as * {@link ng.directive:ngRepeat ngRepeat} for managing the * unrolling of the loop. * * Just before a scope is destroyed a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it chance to * perform any necessary cleanup. */ $destroy: function() { // we can't destroy the root scope or a scope that has been already destroyed if ($rootScope == this || this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; // This is bogus code that works around Chrome's GC leak // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$eval * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating Angular expressions. * * # Example * <pre> var scope = ng.$rootScope.Scope(); scope.a = 1; scope.b = 2; expect(scope.$eval('a+b')).toEqual(3); expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * </pre> * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $eval: function(expr, locals) { return $parse(expr)(this, locals); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$evalAsync * @methodOf ng.$rootScope.Scope * @function * * @description * Executes the expression on the current scope at a later point in time. * * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that: * * - it will execute in the current script execution context (before any DOM rendering). * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after * `expression` execution. * * Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {(string|function())=} expression An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * */ $evalAsync: function(expr) { this.$$asyncQueue.push(expr); }, /** * @ngdoc function * @name ng.$rootScope.Scope#$apply * @methodOf ng.$rootScope.Scope * @function * * @description * `$apply()` is used to execute an expression in angular from outside of the angular framework. * (For example from browser DOM events, setTimeout, XHR or third party libraries). * Because we are calling into the angular framework we need to perform proper scope life-cycle * of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * * ## Life cycle * * # Pseudo-Code of `$apply()` * <pre> function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } } * </pre> * * * Scope's `$apply()` method transitions through the following stages: * * 1. The {@link guide/expression expression} is executed using the * {@link ng.$rootScope.Scope#$eval $eval()} method. * 2. Any exceptions from the execution of the expression are forwarded to the * {@link ng.$exceptionHandler $exceptionHandler} service. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression * was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * * @param {(string|function())=} exp An angular expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. * * @returns {*} The result of evaluating the expression. */ $apply: function(expr) { try { beginPhase('$apply'); return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } } }, /** * @ngdoc function * @name ng.$rootScope.Scope#$on * @methodOf ng.$rootScope.Scope * @function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of * event life cycle. * * The event listener function format is: `function(event, args...)`. The `event` object * passed into the listener has the following attributes: * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed. * - `currentScope` - `{Scope}`: the current scope which is handling the event. * - `name` - `{string}`: Name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event * propagation (available only for events that were `$emit`-ed). * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. * * @param {string} name Event name to listen on. * @param {function(event, args...)} listener Function to call when the event is emitted. * @returns {function()} Returns a deregistration function for this listener. */ $on: function(name, listener) { var namedListeners = this.$$listeners[name]; if (!namedListeners) { this.$$listeners[name] = namedListeners = []; } namedListeners.push(listener); return function() { namedListeners[indexOf(namedListeners, listener)] = null; }; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$emit * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$emit` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event traverses upwards toward the root scope and calls all registered * listeners along the way. The event will stop propagating if one of the listeners cancels it. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to emit. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $emit: function(name, args) { var empty = [], namedListeners, scope = this, stopPropagation = false, event = { name: name, targetScope: scope, stopPropagation: function() {stopPropagation = true;}, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), i, length; do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; for (i=0, length=namedListeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!namedListeners[i]) { namedListeners.splice(i, 1); i--; length--; continue; } try { namedListeners[i].apply(null, listenerArgs); if (stopPropagation) return event; } catch (e) { $exceptionHandler(e); } } //traverse upwards scope = scope.$parent; } while (scope); return event; }, /** * @ngdoc function * @name ng.$rootScope.Scope#$broadcast * @methodOf ng.$rootScope.Scope * @function * * @description * Dispatches an event `name` downwards to all child scopes (and their children) notifying the * registered {@link ng.$rootScope.Scope#$on} listeners. * * The event life cycle starts at the scope on which `$broadcast` was called. All * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified. * Afterwards, the event propagates to all direct and indirect scopes of the current scope and * calls all registered listeners along the way. The event cannot be canceled. * * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed * onto the {@link ng.$exceptionHandler $exceptionHandler} service. * * @param {string} name Event name to broadcast. * @param {...*} args Optional set of arguments which will be passed onto the event listeners. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} */ $broadcast: function(name, args) { var target = this, current = target, next = target, event = { name: name, targetScope: target, preventDefault: function() { event.defaultPrevented = true; }, defaultPrevented: false }, listenerArgs = concat([event], arguments, 1), listeners, i, length; //down while you can, then up and next sibling or up and next sibling until back at root do { current = next; event.currentScope = current; listeners = current.$$listeners[name] || []; for (i=0, length = listeners.length; i<length; i++) { // if listeners were deregistered, defragment the array if (!listeners[i]) { listeners.splice(i, 1); i--; length--; continue; } try { listeners[i].apply(null, listenerArgs); } catch(e) { $exceptionHandler(e); } } // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $digest if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) { while(current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } } while ((current = next)); return event; } }; var $rootScope = new Scope(); return $rootScope; function beginPhase(phase) { if ($rootScope.$$phase) { throw Error($rootScope.$$phase + ' already in progress'); } $rootScope.$$phase = phase; } function clearPhase() { $rootScope.$$phase = null; } function compileToFn(exp, name) { var fn = $parse(exp); assertArgFn(fn, name); return fn; } /** * function used as an initial value for watchers. * because it's unique we can easily tell it apart from other values */ function initWatchVal() {} }]; } /** * !!! This is an undocumented "private" service !!! * * @name ng.$sniffer * @requires $window * @requires $document * * @property {boolean} history Does the browser support html5 history api ? * @property {boolean} hashchange Does the browser support hashchange event ? * @property {boolean} transitions Does the browser support CSS transition events ? * @property {boolean} animations Does the browser support CSS animation events ? * * @description * This is very simple implementation of testing browser's features. */ function $SnifferProvider() { this.$get = ['$window', '$document', function($window, $document) { var eventSupport = {}, android = int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), document = $document[0] || {}, vendorPrefix, vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, bodyStyle = document.body && document.body.style, transitions = false, animations = false, match; if (bodyStyle) { for(var prop in bodyStyle) { if(match = vendorRegex.exec(prop)) { vendorPrefix = match[0]; vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); break; } } transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); } return { // Android has history.pushState, but it does not update location correctly // so let's not use the history API at all. // http://code.google.com/p/android/issues/detail?id=17471 // https://github.com/angular/angular.js/issues/904 history: !!($window.history && $window.history.pushState && !(android < 4)), hashchange: 'onhashchange' in $window && // IE8 compatible mode lies (!document.documentMode || document.documentMode > 7), hasEvent: function(event) { // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. if (event == 'input' && msie == 9) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); eventSupport[event] = 'on' + event in divElm; } return eventSupport[event]; }, csp: document.securityPolicy ? document.securityPolicy.isActive : false, vendorPrefix: vendorPrefix, transitions : transitions, animations : animations }; }]; } /** * @ngdoc object * @name ng.$window * * @description * A reference to the browser's `window` object. While `window` * is globally available in JavaScript, it causes testability problems, because * it is a global variable. In angular we always refer to it through the * `$window` service, so it may be overridden, removed or mocked for testing. * * All expressions are evaluated with respect to current scope so they don't * suffer from window globality. * * @example <doc:example> <doc:source> <script> function Ctrl($scope, $window) { $scope.$window = $window; $scope.greeting = 'Hello, World!'; } </script> <div ng-controller="Ctrl"> <input type="text" ng-model="greeting" /> <button ng-click="$window.alert(greeting)">ALERT</button> </div> </doc:source> <doc:scenario> it('should display the greeting in the input box', function() { input('greeting').enter('Hello, E2E Tests'); // If we click the button it will block the test runner // element(':button').click(); }); </doc:scenario> </doc:example> */ function $WindowProvider(){ this.$get = valueFn(window); } /** * Parse headers into key value object * * @param {string} headers Raw headers as a string * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = lowercase(trim(line.substr(0, i))); val = trim(line.substr(i + 1)); if (key) { if (parsed[key]) { parsed[key] += ', ' + val; } else { parsed[key] = val; } } }); return parsed; } var IS_SAME_DOMAIN_URL_MATCH = /^(([^:]+):)?\/\/(\w+:{0,1}\w*@)?([\w\.-]*)?(:([0-9]+))?(.*)$/; /** * Parse a request and location URL and determine whether this is a same-domain request. * * @param {string} requestUrl The url of the request. * @param {string} locationUrl The current browser location url. * @returns {boolean} Whether the request is for the same domain. */ function isSameDomain(requestUrl, locationUrl) { var match = IS_SAME_DOMAIN_URL_MATCH.exec(requestUrl); // if requestUrl is relative, the regex does not match. if (match == null) return true; var domain1 = { protocol: match[2], host: match[4], port: int(match[6]) || DEFAULT_PORTS[match[2]] || null, // IE8 sets unmatched groups to '' instead of undefined. relativeProtocol: match[2] === undefined || match[2] === '' }; match = SERVER_MATCH.exec(locationUrl); var domain2 = { protocol: match[1], host: match[3], port: int(match[5]) || DEFAULT_PORTS[match[1]] || null }; return (domain1.protocol == domain2.protocol || domain1.relativeProtocol) && domain1.host == domain2.host && (domain1.port == domain2.port || (domain1.relativeProtocol && domain2.port == DEFAULT_PORTS[domain2.protocol])); } /** * Returns a function that provides access to parsed headers. * * Headers are lazy parsed when first requested. * @see parseHeaders * * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * * - if called with single an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { var headersObj = isObject(headers) ? headers : undefined; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { return headersObj[lowercase(name)] || null; } return headersObj; }; } /** * Chain all given functions * * This function is used for both request and response transforming * * @param {*} data Data to transform. * @param {function(string=)} headers Http headers getter fn. * @param {(function|Array.<function>)} fns Function or an array of functions. * @returns {*} Transformed data. */ function transformData(data, headers, fns) { if (isFunction(fns)) return fns(data, headers); forEach(fns, function(fn) { data = fn(data, headers); }); return data; } function isSuccess(status) { return 200 <= status && status < 300; } function $HttpProvider() { var JSON_START = /^\s*(\[|\{[^\{])/, JSON_END = /[\}\]]\s*$/, PROTECTION_PREFIX = /^\)\]\}',?\n/, CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; var defaults = this.defaults = { // transform incoming response data transformResponse: [function(data) { if (isString(data)) { // strip json vulnerability protection prefix data = data.replace(PROTECTION_PREFIX, ''); if (JSON_START.test(data) && JSON_END.test(data)) data = fromJson(data, true); } return data; }], // transform outgoing request data transformRequest: [function(d) { return isObject(d) && !isFile(d) ? toJson(d) : d; }], // default headers headers: { common: { 'Accept': 'application/json, text/plain, */*' }, post: CONTENT_TYPE_APPLICATION_JSON, put: CONTENT_TYPE_APPLICATION_JSON, patch: CONTENT_TYPE_APPLICATION_JSON }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; /** * Are order by request. I.E. they are applied in the same order as * array on request, but revers order on response. */ var interceptorFactories = this.interceptors = []; /** * For historical reasons, response interceptors ordered by the order in which * they are applied to response. (This is in revers to interceptorFactories) */ var responseInterceptorFactories = this.responseInterceptors = []; this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { var defaultCache = $cacheFactory('$http'); /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the * server request. */ var reversedInterceptors = []; forEach(interceptorFactories, function(interceptorFactory) { reversedInterceptors.unshift(isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); forEach(responseInterceptorFactories, function(interceptorFactory, index) { var responseFn = isString(interceptorFactory) ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory); /** * Response interceptors go before "around" interceptors (no real reason, just * had to pick one.) But they are already revesed, so we can't use unshift, hence * the splice. */ reversedInterceptors.splice(index, 0, { response: function(response) { return responseFn($q.when(response)); }, responseError: function(response) { return responseFn($q.reject(response)); } }); }); /** * @ngdoc function * @name ng.$http * @requires $httpBackend * @requires $browser * @requires $cacheFactory * @requires $rootScope * @requires $q * @requires $injector * * @description * The `$http` service is a core Angular service that facilitates communication with the remote * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}. * * For unit testing applications that use `$http` service, see * {@link ngMock.$httpBackend $httpBackend mock}. * * For a higher level of abstraction, please check out the {@link ngResource.$resource * $resource} service. * * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage * it is important to familiarize yourself with these APIs and the guarantees they provide. * * * # General usage * The `$http` service is a function which takes a single argument — a configuration object — * that is used to generate an HTTP request and returns a {@link ng.$q promise} * with two $http specific methods: `success` and `error`. * * <pre> * $http({method: 'GET', url: '/someUrl'}). * success(function(data, status, headers, config) { * // this callback will be called asynchronously * // when the response is available * }). * error(function(data, status, headers, config) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * </pre> * * Since the returned value of calling the $http function is a `promise`, you can also use * the `then` method to register callbacks, and these callbacks will receive a single argument – * an object representing the response. See the API signature and type info below for more * details. * * A response status code between 200 and 299 is considered a success status and * will result in the success callback being called. Note that if the response is a redirect, * XMLHttpRequest will transparently follow it, meaning that the error callback will not be * called for such responses. * * # Shortcut methods * * Since all invocations of the $http service require passing in an HTTP method and URL, and * POST/PUT requests require request data to be provided as well, shortcut methods * were created: * * <pre> * $http.get('/someUrl').success(successCallback); * $http.post('/someUrl', data).success(successCallback); * </pre> * * Complete list of shortcut methods: * * - {@link ng.$http#get $http.get} * - {@link ng.$http#head $http.head} * - {@link ng.$http#post $http.post} * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} * * * # Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): * - `Accept: application/json, text/plain, * / *` * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) * - `Content-Type: application/json` * * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. * `$httpProvider.defaults.headers.get['My-Header']='value'`. * * Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same * fashion. * * * # Transforming Requests and Responses * * Both requests and responses can be transformed using transform functions. By default, Angular * applies these transformations: * * Request transformations: * * - If the `data` property of the request configuration object contains an object, serialize it into * JSON format. * * Response transformations: * * - If XSRF prefix is detected, strip it (see Security Considerations section below). * - If JSON response is detected, deserialize it using a JSON parser. * * To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and * `$httpProvider.defaults.transformResponse` properties. These properties are by default an * array of transform functions, which allows you to `push` or `unshift` a new transformation function into the * transformation chain. You can also decide to completely override any default transformations by assigning your * transformation functions to these properties directly without the array wrapper. * * Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or * `transformResponse` properties of the configuration object passed into `$http`. * * * # Caching * * To enable caching, set the configuration property `cache` to `true`. When the cache is * enabled, `$http` stores the response from the server in local cache. Next time the * response is served from the cache without sending a request to the server. * * Note that even if the response is served from cache, delivery of the data is asynchronous in * the same way that real requests are. * * If there are multiple GET requests for the same URL that should be cached using the same * cache, but the cache is not populated yet, only one request to the server will be made and * the remaining requests will be fulfilled using the response from the first request. * * A custom default cache built with $cacheFactory can be provided in $http.defaults.cache. * To skip it, set configuration property `cache` to `false`. * * * # Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication, or any kind of synchronous or * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be * able to intercept requests before they are handed to the server and * responses before they are handed over to the application code that * initiated these requests. The interceptors leverage the {@link ng.$q * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing. * * The interceptors are service factories that are registered with the `$httpProvider` by * adding them to the `$httpProvider.interceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor. * * There are two kinds of interceptors (and two kinds of rejection interceptors): * * * `request`: interceptors get called with http `config` object. The function is free to modify * the `config` or create a new one. The function needs to return the `config` directly or as a * promise. * * `requestError`: interceptor gets called when a previous interceptor threw an error or resolved * with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to modify * the `response` or create a new one. The function needs to return the `response` directly or as a * promise. * * `responseError`: interceptor gets called when a previous interceptor threw an error or resolved * with a rejection. * * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return { * // optional method * 'request': function(config) { * // do something on success * return config || $q.when(config); * }, * * // optional method * 'requestError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }, * * * * // optional method * 'response': function(response) { * // do something on success * return response || $q.when(response); * }, * * // optional method * 'responseError': function(rejection) { * // do something on error * if (canRecover(rejection)) { * return responseOrNewPromise * } * return $q.reject(rejection); * }; * } * }); * * $httpProvider.interceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.interceptors.push(function($q, dependency1, dependency2) { * return { * 'request': function(config) { * // same as above * }, * 'response': function(response) { * // same as above * } * }); * </pre> * * # Response interceptors (DEPRECATED) * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. * * For purposes of global error handling, authentication or any kind of synchronous or * asynchronous preprocessing of received responses, it is desirable to be able to intercept * responses for http requests before they are handed over to the application code that * initiated these requests. The response interceptors leverage the {@link ng.$q * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. * * The interceptors are service factories that are registered with the $httpProvider by * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and * injected with dependencies (if specified) and returns the interceptor — a function that * takes a {@link ng.$q promise} and returns the original or a new promise. * * <pre> * // register the interceptor as a service * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { * return function(promise) { * return promise.then(function(response) { * // do something on success * }, function(response) { * // do something on error * if (canRecover(response)) { * return responseOrNewPromise * } * return $q.reject(response); * }); * } * }); * * $httpProvider.responseInterceptors.push('myHttpInterceptor'); * * * // register the interceptor via an anonymous factory * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { * return function(promise) { * // same as above * } * }); * </pre> * * * # Security Considerations * * When designing web applications, consider security threats from: * * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON vulnerability} * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} * * Both server and the client must cooperate in order to eliminate these threats. Angular comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * * ## JSON Vulnerability Protection * * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx * JSON vulnerability} allows third party website to turn your JSON resource URL into * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. * Angular will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * <pre> * ['one','two'] * </pre> * * which is vulnerable to attack, your server can return: * <pre> * )]}', * ['one','two'] * </pre> * * Angular will strip the prefix, before processing the JSON. * * * ## Cross Site Request Forgery (XSRF) Protection * * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which * an unauthorized site can gain your user's private data. Angular provides a mechanism * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only * JavaScript that runs on your domain could read the cookie, your server can be assured that * the XHR came from JavaScript running on your domain. The header will not be set for * cross-domain requests. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure * that only JavaScript running on your domain could have sent the request. The token must be * unique for each user and must be verifiable by the server (to prevent the JavaScript from making * up its own tokens). We recommend that the token is a digest of your site's authentication * cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security. * * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName * properties of either $httpProvider.defaults, or the per-request config object. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. * - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – * transform function or an array of such functions. The transform function takes the http * response body and headers and returns its transformed (typically deserialized) version. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the * GET request, otherwise if a cache instance built with * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for * caching. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5 * requests with credentials} for more information. * - **responseType** - `{string}` - see {@link * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}. * * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the * standard `then` method and two http specific methods: `success` and `error`. The `then` * method takes two arguments a success and an error callback which will be called with a * response object. The `success` and `error` methods take a single argument - a function that * will be called when the request succeeds or fails respectively. The arguments passed into * these functions are destructured representation of the response object passed into the * `then` method. The response object has these properties: * * - **data** – `{string|Object}` – The response body transformed with the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. * - **config** – `{Object}` – The configuration object that was used to generate the request. * * @property {Array.<Object>} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example <example> <file name="index.html"> <div ng-controller="FetchCtrl"> <select ng-model="method"> <option>GET</option> <option>JSONP</option> </select> <input type="text" ng-model="url" size="80"/> <button ng-click="fetch()">fetch</button><br> <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button> <button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button> <pre>http status code: {{status}}</pre> <pre>http response data: {{data}}</pre> </div> </file> <file name="script.js"> function FetchCtrl($scope, $http, $templateCache) { $scope.method = 'GET'; $scope.url = 'http-hello.html'; $scope.fetch = function() { $scope.code = null; $scope.response = null; $http({method: $scope.method, url: $scope.url, cache: $templateCache}). success(function(data, status) { $scope.status = status; $scope.data = data; }). error(function(data, status) { $scope.data = data || "Request failed"; $scope.status = status; }); }; $scope.updateModel = function(method, url) { $scope.method = method; $scope.url = url; }; } </file> <file name="http-hello.html"> Hello, $http! </file> <file name="scenario.js"> it('should make an xhr GET request', function() { element(':button:contains("Sample GET")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Hello, \$http!/); }); it('should make a JSONP request to angularjs.org', function() { element(':button:contains("Sample JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('200'); expect(binding('data')).toMatch(/Super Hero!/); }); it('should make JSONP request to invalid URL and invoke the error handler', function() { element(':button:contains("Invalid JSONP")').click(); element(':button:contains("fetch")').click(); expect(binding('status')).toBe('0'); expect(binding('data')).toBe('Request failed'); }); </file> </example> */ function $http(requestConfig) { var config = { transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }; var headers = {}; extend(config, requestConfig); config.headers = headers; config.method = uppercase(config.method); extend(headers, defaults.headers.common, defaults.headers[lowercase(config.method)], requestConfig.headers); var xsrfValue = isSameDomain(config.url, $browser.url()) ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] : undefined; if (xsrfValue) { headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; } var serverRequest = function(config) { var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); // strip content-type if data is undefined if (isUndefined(config.data)) { delete headers['Content-Type']; } if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { config.withCredentials = defaults.withCredentials; } // send request return sendReq(config, reqData, headers).then(transformResponse, transformResponse); }; var chain = [serverRequest, undefined]; var promise = $q.when(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { chain.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { chain.push(interceptor.response, interceptor.responseError); } }); while(chain.length) { var thenFn = chain.shift(); var rejectFn = chain.shift(); promise = promise.then(thenFn, rejectFn); } promise.success = function(fn) { promise.then(function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; promise.error = function(fn) { promise.then(null, function(response) { fn(response.data, response.status, response.headers, config); }); return promise; }; return promise; function transformResponse(response) { // make a copy since the response must be cacheable var resp = extend({}, response, { data: transformData(response.data, response.headers, config.transformResponse) }); return (isSuccess(response.status)) ? resp : $q.reject(resp); } } $http.pendingRequests = []; /** * @ngdoc method * @name ng.$http#get * @methodOf ng.$http * * @description * Shortcut method to perform `GET` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#delete * @methodOf ng.$http * * @description * Shortcut method to perform `DELETE` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#head * @methodOf ng.$http * * @description * Shortcut method to perform `HEAD` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#jsonp * @methodOf ng.$http * * @description * Shortcut method to perform `JSONP` request. * * @param {string} url Relative or absolute URL specifying the destination of the request. * Should contain `JSON_CALLBACK` string. * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethods('get', 'delete', 'head', 'jsonp'); /** * @ngdoc method * @name ng.$http#post * @methodOf ng.$http * * @description * Shortcut method to perform `POST` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ /** * @ngdoc method * @name ng.$http#put * @methodOf ng.$http * * @description * Shortcut method to perform `PUT` request. * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content * @param {Object=} config Optional configuration object * @returns {HttpPromise} Future object */ createShortMethodsWithData('post', 'put'); /** * @ngdoc property * @name ng.$http#defaults * @propertyOf ng.$http * * @description * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of * default headers, withCredentials as well as request and response transformations. * * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above. */ $http.defaults = defaults; return $http; function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { return $http(extend(config || {}, { method: name, url: url })); }; }); } function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { return $http(extend(config || {}, { method: name, url: url, data: data })); }; }); } /** * Makes the request. * * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ function sendReq(config, reqData, reqHeaders) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, url = buildUrl(config.url, config.params); $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { cache = isObject(config.cache) ? config.cache : isObject(defaults.cache) ? defaults.cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (cachedResp) { if (cachedResp.then) { // cached request has already been sent, but there is no response yet cachedResp.then(removePendingReq, removePendingReq); return cachedResp; } else { // serving from cache if (isArray(cachedResp)) { resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2])); } else { resolvePromise(cachedResp, 200, {}); } } } else { // put the promise for the non-transformed response into cache as a placeholder cache.put(url, promise); } } // if we won't have the response in cache, send the request to the backend if (!cachedResp) { $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, config.withCredentials, config.responseType); } return promise; /** * Callback registered to $httpBackend(): * - caches the response if desired * - resolves the raw $http promise * - calls $apply */ function done(status, response, headersString) { if (cache) { if (isSuccess(status)) { cache.put(url, [status, response, parseHeaders(headersString)]); } else { // remove promise from the cache cache.remove(url); } } resolvePromise(response, status, headersString); if (!$rootScope.$$phase) $rootScope.$apply(); } /** * Resolves the raw $http promise. */ function resolvePromise(response, status, headers) { // normalize internal statuses to 0 status = Math.max(status, 0); (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config }); } function removePendingReq() { var idx = indexOf($http.pendingRequests, config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } function buildUrl(url, params) { if (!params) return url; var parts = []; forEachSorted(params, function(value, key) { if (value == null || value == undefined) return; if (!isArray(value)) value = [value]; forEach(value, function(v) { if (isObject(v)) { v = toJson(v); } parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(v)); }); }); return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); } }]; } var XHR = window.XMLHttpRequest || function() { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {} throw new Error("This browser does not support XMLHttpRequest."); }; /** * @ngdoc object * @name ng.$httpBackend * @requires $browser * @requires $window * @requires $document * * @description * HTTP backend used by the {@link ng.$http service} that delegates to * XMLHttpRequest object or JSONP and deals with browser incompatibilities. * * You should never need to use this service directly, instead use the higher-level abstractions: * {@link ng.$http $http} or {@link ngResource.$resource $resource}. * * During testing this implementation is swapped with {@link ngMock.$httpBackend mock * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0], $window.location.protocol.replace(':', '')); }]; } function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) { // TODO(vojta): fix the signature return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { var status; $browser.$$incOutstandingRequestCount(); url = url || $browser.url(); if (lowercase(method) == 'jsonp') { var callbackId = '_' + (callbacks.counter++).toString(36); callbacks[callbackId] = function(data) { callbacks[callbackId].data = data; }; var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), function() { if (callbacks[callbackId].data) { completeRequest(callback, 200, callbacks[callbackId].data); } else { completeRequest(callback, status || -2); } delete callbacks[callbackId]; }); } else { var xhr = new XHR(); xhr.open(method, url, true); forEach(headers, function(value, key) { if (value) xhr.setRequestHeader(key, value); }); // In IE6 and 7, this might be called synchronously when xhr.send below is called and the // response is in the cache. the promise api will ensure that to the app code the api is // always async xhr.onreadystatechange = function() { if (xhr.readyState == 4) { var responseHeaders = xhr.getAllResponseHeaders(); // TODO(vojta): remove once Firefox 21 gets released. // begin: workaround to overcome Firefox CORS http response headers bug // https://bugzilla.mozilla.org/show_bug.cgi?id=608735 // Firefox already patched in nightly. Should land in Firefox 21. // CORS "simple response headers" http://www.w3.org/TR/cors/ var value, simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"]; if (!responseHeaders) { responseHeaders = ""; forEach(simpleHeaders, function (header) { var value = xhr.getResponseHeader(header); if (value) { responseHeaders += header + ": " + value + "\n"; } }); } // end of the workaround. // responseText is the old-school way of retrieving response (supported by IE8 & 9) // response and responseType properties were introduced in XHR Level2 spec (supported by IE10) completeRequest(callback, status || xhr.status, (xhr.responseType ? xhr.response : xhr.responseText), responseHeaders); } }; if (withCredentials) { xhr.withCredentials = true; } if (responseType) { xhr.responseType = responseType; } xhr.send(post || ''); } if (timeout > 0) { var timeoutId = $browserDefer(timeoutRequest, timeout); } else if (timeout && timeout.then) { timeout.then(timeoutRequest); } function timeoutRequest() { status = -1; jsonpDone && jsonpDone(); xhr && xhr.abort(); } function completeRequest(callback, status, response, headersString) { // URL_MATCH is defined in src/service/location.js var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1]; // cancel timeout and subsequent timeout promise resolution timeoutId && $browserDefer.cancel(timeoutId); jsonpDone = xhr = null; // fix status code for file protocol (it's always 0) status = (protocol == 'file') ? (response ? 200 : 404) : status; // normalize IE bug (http://bugs.jquery.com/ticket/1450) status = status == 1223 ? 204 : status; callback(status, response, headersString); $browser.$$completeOutstandingRequest(noop); } }; function jsonpReq(url, done) { // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document var script = rawDocument.createElement('script'), doneWrapper = function() { rawDocument.body.removeChild(script); if (done) done(); }; script.type = 'text/javascript'; script.src = url; if (msie) { script.onreadystatechange = function() { if (/loaded|complete/.test(script.readyState)) doneWrapper(); }; } else { script.onload = script.onerror = doneWrapper; } rawDocument.body.appendChild(script); return doneWrapper; } } /** * @ngdoc object * @name ng.$locale * * @description * $locale service provides localization rules for various Angular components. As of right now the * only public api is: * * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) */ function $LocaleProvider(){ this.$get = function() { return { id: 'en-us', NUMBER_FORMATS: { DECIMAL_SEP: '.', GROUP_SEP: ',', PATTERNS: [ { // Decimal Pattern minInt: 1, minFrac: 0, maxFrac: 3, posPre: '', posSuf: '', negPre: '-', negSuf: '', gSize: 3, lgSize: 3 },{ //Currency Pattern minInt: 1, minFrac: 2, maxFrac: 2, posPre: '\u00A4', posSuf: '', negPre: '(\u00A4', negSuf: ')', gSize: 3, lgSize: 3 } ], CURRENCY_SYM: '$' }, DATETIME_FORMATS: { MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December' .split(','), SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), AMPMS: ['AM','PM'], medium: 'MMM d, y h:mm:ss a', short: 'M/d/yy h:mm a', fullDate: 'EEEE, MMMM d, y', longDate: 'MMMM d, y', mediumDate: 'MMM d, y', shortDate: 'M/d/yy', mediumTime: 'h:mm:ss a', shortTime: 'h:mm a' }, pluralCat: function(num) { if (num === 1) { return 'one'; } return 'other'; } }; }; } function $TimeoutProvider() { this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', function($rootScope, $browser, $q, $exceptionHandler) { var deferreds = {}; /** * @ngdoc function * @name ng.$timeout * @requires $browser * * @description * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch * block and delegates any exceptions to * {@link ng.$exceptionHandler $exceptionHandler} service. * * The return value of registering a timeout function is a promise, which will be resolved when * the timeout is reached and the timeout function is executed. * * To cancel a timeout request, call `$timeout.cancel(promise)`. * * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to * synchronously flush the queue of deferred functions. * * @param {function()} fn A function, whose execution should be delayed. * @param {number=} [delay=0] Delay in milliseconds. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this * promise will be resolved with is the return value of the `fn` function. */ function timeout(fn, delay, invokeApply) { var deferred = $q.defer(), promise = deferred.promise, skipApply = (isDefined(invokeApply) && !invokeApply), timeoutId, cleanup; timeoutId = $browser.defer(function() { try { deferred.resolve(fn()); } catch(e) { deferred.reject(e); $exceptionHandler(e); } if (!skipApply) $rootScope.$apply(); }, delay); cleanup = function() { delete deferreds[promise.$$timeoutId]; }; promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; promise.then(cleanup, cleanup); return promise; } /** * @ngdoc function * @name ng.$timeout#cancel * @methodOf ng.$timeout * * @description * Cancels a task associated with the `promise`. As a result of this, the promise will be * resolved with a rejection. * * @param {Promise=} promise Promise returned by the `$timeout` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ timeout.cancel = function(promise) { if (promise && promise.$$timeoutId in deferreds) { deferreds[promise.$$timeoutId].reject('canceled'); return $browser.defer.cancel(promise.$$timeoutId); } return false; }; return timeout; }]; } /** * @ngdoc object * @name ng.$filterProvider * @description * * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To * achieve this a filter definition consists of a factory function which is annotated with dependencies and is * responsible for creating a filter function. * * <pre> * // Filter registration * function MyModule($provide, $filterProvider) { * // create a service to demonstrate injection (not always needed) * $provide.value('greet', function(name){ * return 'Hello ' + name + '!'; * }); * * // register a filter factory which uses the * // greet service to demonstrate DI. * $filterProvider.register('greet', function(greet){ * // return the filter function which uses the greet service * // to generate salutation * return function(text) { * // filters need to be forgiving so check input validity * return text && greet(text) || text; * }; * }); * } * </pre> * * The filter function is registered with the `$injector` under the filter name suffixe with `Filter`. * <pre> * it('should be the same instance', inject( * function($filterProvider) { * $filterProvider.register('reverse', function(){ * return ...; * }); * }, * function($filter, reverseFilter) { * expect($filter('reverse')).toBe(reverseFilter); * }); * </pre> * * * For more information about how angular filters work, and how to create your own filters, see * {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer * Guide. */ /** * @ngdoc method * @name ng.$filterProvider#register * @methodOf ng.$filterProvider * @description * Register filter factory function. * * @param {String} name Name of the filter. * @param {function} fn The filter factory function which is injectable. */ /** * @ngdoc function * @name ng.$filter * @function * @description * Filters are used for formatting data displayed to the user. * * The general syntax in templates is as follows: * * {{ expression [| filter_name[:parameter_value] ... ] }} * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function */ $FilterProvider.$inject = ['$provide']; function $FilterProvider($provide) { var suffix = 'Filter'; function register(name, factory) { return $provide.factory(name + suffix, factory); } this.register = register; this.$get = ['$injector', function($injector) { return function(name) { return $injector.get(name + suffix); } }]; //////////////////////////////////////// register('currency', currencyFilter); register('date', dateFilter); register('filter', filterFilter); register('json', jsonFilter); register('limitTo', limitToFilter); register('lowercase', lowercaseFilter); register('number', numberFilter); register('orderBy', orderByFilter); register('uppercase', uppercaseFilter); } /** * @ngdoc filter * @name ng.filter:filter * @function * * @description * Selects a subset of items from `array` and returns it as a new array. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array The source array. * @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * * - `string`: Predicate that results in a substring match using the value of `expression` * string. All strings or objects with string properties in `array` that contain this string * will be returned. The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special * property name `$` can be used (as in `{$:"text"}`) to accept a match against any * property of the object. That's equivalent to the simple substring match with a `string` * as described above. * * - `function`: A predicate function can be used to write arbitrary filters. The function is * called for each element of `array`. The final result is an array of those elements that * the predicate returned true for. * * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in * determining if the expected value (from the filter expression) and actual value (from * the object in the array) should be considered a match. * * Can be one of: * * - `function(expected, actual)`: * The function will be given the object value and the predicate value to compare and * should return true if the item should be included in filtered result. * * - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`. * this is essentially strict comparison of expected and actual. * * - `false|undefined`: A short hand for a function which will look for a substring match in case * insensitive way. * * @example <doc:example> <doc:source> <div ng-init="friends = [{name:'John', phone:'555-1276'}, {name:'Mary', phone:'800-BIG-MARY'}, {name:'Mike', phone:'555-4321'}, {name:'Adam', phone:'555-5678'}, {name:'Julie', phone:'555-8765'}, {name:'Juliette', phone:'555-5678'}]"></div> Search: <input ng-model="searchText"> <table id="searchTextResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:searchText"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> <hr> Any: <input ng-model="search.$"> <br> Name only <input ng-model="search.name"><br> Phone only <input ng-model="search.phone"><br> Equality <input type="checkbox" ng-model="strict"><br> <table id="searchObjResults"> <tr><th>Name</th><th>Phone</th></tr> <tr ng-repeat="friend in friends | filter:search:strict"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> </tr> </table> </doc:source> <doc:scenario> it('should search across all fields when filtering with a string', function() { input('searchText').enter('m'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Adam']); input('searchText').enter('76'); expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')). toEqual(['John', 'Julie']); }); it('should search in specific fields when filtering with a predicate object', function() { input('search.$').enter('i'); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Mike', 'Julie', 'Juliette']); }); it('should use a equal comparison when comparator is true', function() { input('search.name').enter('Julie'); input('strict').check(); expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')). toEqual(['Julie']); }); </doc:scenario> </doc:example> */ function filterFilter() { return function(array, expression, comperator) { if (!isArray(array)) return array; var predicates = []; predicates.check = function(value) { for (var j = 0; j < predicates.length; j++) { if(!predicates[j](value)) { return false; } } return true; }; switch(typeof comperator) { case "function": break; case "boolean": if(comperator == true) { comperator = function(obj, text) { return angular.equals(obj, text); } break; } default: comperator = function(obj, text) { text = (''+text).toLowerCase(); return (''+obj).toLowerCase().indexOf(text) > -1 }; } var search = function(obj, text){ if (typeof text == 'string' && text.charAt(0) === '!') { return !search(obj, text.substr(1)); } switch (typeof obj) { case "boolean": case "number": case "string": return comperator(obj, text); case "object": switch (typeof text) { case "object": return comperator(obj, text); break; default: for ( var objKey in obj) { if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { return true; } } break; } return false; case "array": for ( var i = 0; i < obj.length; i++) { if (search(obj[i], text)) { return true; } } return false; default: return false; } }; switch (typeof expression) { case "boolean": case "number": case "string": expression = {$:expression}; case "object": for (var key in expression) { if (key == '$') { (function() { if (!expression[key]) return; var path = key predicates.push(function(value) { return search(value, expression[path]); }); })(); } else { (function() { if (!expression[key]) return; var path = key; predicates.push(function(value) { return search(getter(value,path), expression[path]); }); })(); } } break; case 'function': predicates.push(expression); break; default: return array; } var filtered = []; for ( var j = 0; j < array.length; j++) { var value = array[j]; if (predicates.check(value)) { filtered.push(value); } } return filtered; } } /** * @ngdoc filter * @name ng.filter:currency * @function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default * symbol for current locale is used. * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. * @returns {string} Formatted number. * * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.amount = 1234.56; } </script> <div ng-controller="Ctrl"> <input type="number" ng-model="amount"> <br> default currency symbol ($): {{amount | currency}}<br> custom currency identifier (USD$): {{amount | currency:"USD$"}} </div> </doc:source> <doc:scenario> it('should init with 1234.56', function() { expect(binding('amount | currency')).toBe('$1,234.56'); expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56'); }); it('should update', function() { input('amount').enter('-1234'); expect(binding('amount | currency')).toBe('($1,234.00)'); expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)'); }); </doc:scenario> </doc:example> */ currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(amount, currencySymbol){ if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). replace(/\u00A4/g, currencySymbol); }; } /** * @ngdoc filter * @name ng.filter:number * @function * * @description * Formats a number as text. * * If the input is not a number an empty string is returned. * * @param {number|string} number Number to format. * @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.val = 1234.56789; } </script> <div ng-controller="Ctrl"> Enter number: <input ng-model='val'><br> Default formatting: {{val | number}}<br> No fractions: {{val | number:0}}<br> Negative number: {{-val | number:4}} </div> </doc:source> <doc:scenario> it('should format numbers', function() { expect(binding('val | number')).toBe('1,234.568'); expect(binding('val | number:0')).toBe('1,235'); expect(binding('-val | number:4')).toBe('-1,234.5679'); }); it('should update', function() { input('val').enter('3374.333'); expect(binding('val | number')).toBe('3,374.333'); expect(binding('val | number:0')).toBe('3,374'); expect(binding('-val | number:4')).toBe('-3,374.3330'); }); </doc:scenario> </doc:example> */ numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize); }; } var DECIMAL_SEP = '.'; function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { if (isNaN(number) || !isFinite(number)) return ''; var isNegative = number < 0; number = Math.abs(number); var numStr = number + '', formatedText = '', parts = []; var hasExponent = false; if (numStr.indexOf('e') !== -1) { var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); if (match && match[2] == '-' && match[3] > fractionSize + 1) { numStr = '0'; } else { formatedText = numStr; hasExponent = true; } } if (!hasExponent) { var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; // determine fractionSize if it is not specified if (isUndefined(fractionSize)) { fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); } var pow = Math.pow(10, fractionSize); number = Math.round(number * pow) / pow; var fraction = ('' + number).split(DECIMAL_SEP); var whole = fraction[0]; fraction = fraction[1] || ''; var pos = 0, lgroup = pattern.lgSize, group = pattern.gSize; if (whole.length >= (lgroup + group)) { pos = whole.length - lgroup; for (var i = 0; i < pos; i++) { if ((pos - i)%group === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } } for (i = pos; i < whole.length; i++) { if ((whole.length - i)%lgroup === 0 && i !== 0) { formatedText += groupSep; } formatedText += whole.charAt(i); } // format fraction part. while(fraction.length < fractionSize) { fraction += '0'; } if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); } parts.push(isNegative ? pattern.negPre : pattern.posPre); parts.push(formatedText); parts.push(isNegative ? pattern.negSuf : pattern.posSuf); return parts.join(''); } function padNumber(num, digits, trim) { var neg = ''; if (num < 0) { neg = '-'; num = -num; } num = '' + num; while(num.length < digits) num = '0' + num; if (trim) num = num.substr(num.length - digits); return neg + num; } function dateGetter(name, size, offset, trim) { offset = offset || 0; return function(date) { var value = date['get' + name](); if (offset > 0 || value > -offset) value += offset; if (value === 0 && offset == -12 ) value = 12; return padNumber(value, size, trim); }; } function dateStrGetter(name, shortForm) { return function(date, formats) { var value = date['get' + name](); var get = uppercase(shortForm ? ('SHORT' + name) : name); return formats[get][value]; }; } function timeZoneGetter(date) { var zone = -1 * date.getTimezoneOffset(); var paddedZone = (zone >= 0) ? "+" : ""; paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2); return paddedZone; } function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } var DATE_FORMATS = { yyyy: dateGetter('FullYear', 4), yy: dateGetter('FullYear', 2, 0, true), y: dateGetter('FullYear', 1), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), H: dateGetter('Hours', 1), hh: dateGetter('Hours', 2, -12), h: dateGetter('Hours', 1, -12), mm: dateGetter('Minutes', 2), m: dateGetter('Minutes', 1), ss: dateGetter('Seconds', 2), s: dateGetter('Seconds', 1), // while ISO 8601 requires fractions to be prefixed with `.` or `,` // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions sss: dateGetter('Milliseconds', 3), EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, Z: timeZoneGetter }; var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, NUMBER_STRING = /^\d+$/; /** * @ngdoc filter * @name ng.filter:date * @function * * @description * Formats `date` to a string based on the requested `format`. * * `format` string can be composed of the following elements: * * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) * * `'MMMM'`: Month in year (January-December) * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) * * `'hh'`: Hour in am/pm, padded (01-12) * * `'h'`: Hour in am/pm, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) * * `'a'`: am/pm marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale * (e.g. Sep 3, 2010 12:05:08 pm) * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010 * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) * * `format` string can contain literal values. These need to be quoted with single quotes (e.g. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence * (e.g. `"h o''clock"`). * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example <doc:example> <doc:source> <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>: {{1288323623006 | date:'medium'}}<br> <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>: {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br> <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br> </doc:source> <doc:scenario> it('should format date', function() { expect(binding("1288323623006 | date:'medium'")). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")). toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); }); </doc:scenario> </doc:example> */ dateFilter.$inject = ['$locale']; function dateFilter($locale) { var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; // 1 2 3 4 5 6 7 8 9 10 11 function jsonStringToDate(string) { var match; if (match = string.match(R_ISO8601_STR)) { var date = new Date(0), tzHour = 0, tzMin = 0, dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, timeSetter = match[8] ? date.setUTCHours : date.setHours; if (match[9]) { tzHour = int(match[9] + match[10]); tzMin = int(match[9] + match[11]); } dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); var h = int(match[4]||0) - tzHour; var m = int(match[5]||0) - tzMin var s = int(match[6]||0); var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } return string; } return function(date, format) { var text = '', parts = [], fn, match; format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { if (NUMBER_STRING.test(date)) { date = int(date); } else { date = jsonStringToDate(date); } } if (isNumber(date)) { date = new Date(date); } if (!isDate(date)) { return date; } while(format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); format = parts.pop(); } else { parts.push(format); format = null; } } forEach(parts, function(value){ fn = DATE_FORMATS[value]; text += fn ? fn(date, $locale.DATETIME_FORMATS) : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); }); return text; }; } /** * @ngdoc filter * @name ng.filter:json * @function * * @description * Allows you to convert a JavaScript object into JSON string. * * This filter is mostly useful for debugging. When using the double curly {{value}} notation * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. * @returns {string} JSON string. * * * @example: <doc:example> <doc:source> <pre>{{ {'name':'value'} | json }}</pre> </doc:source> <doc:scenario> it('should jsonify filtered objects', function() { expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/); }); </doc:scenario> </doc:example> * */ function jsonFilter() { return function(object) { return toJson(object, true); }; } /** * @ngdoc filter * @name ng.filter:lowercase * @function * @description * Converts string to lowercase. * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name ng.filter:uppercase * @function * @description * Converts string to uppercase. * @see angular.uppercase */ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive or negative) of `limit`. * * Note: This function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array|string} input Source array or string to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.numLimit = 3; $scope.letterLimit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="integer" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> </div> </doc:source> <doc:scenario> it('should limit the number array to first three items', function() { expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3'); expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3'); expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]'); expect(binding('letters | limitTo:letterLimit')).toEqual('abc'); }); it('should update the output when -3 is entered', function() { input('numLimit').enter(-3); input('letterLimit').enter(-3); expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]'); expect(binding('letters | limitTo:letterLimit')).toEqual('ghi'); }); it('should not exceed the maximum size of input array', function() { input('numLimit').enter(100); input('letterLimit').enter(100); expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]'); expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi'); }); </doc:scenario> </doc:example> */ function limitToFilter(){ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; limit = int(limit); if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; } } var out = [], i, n; // if abs(limit) exceeds maximum length, trim it if (limit > input.length) limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i<n; i++) { out.push(input[i]); } return out; } } /** * @ngdoc function * @name ng.filter:orderBy * @function * * @description * Orders a specified `array` by the `expression` predicate. * * Note: this function is used to augment the `Array` type in Angular expressions. See * {@link ng.$filter} for more information about Angular arrays. * * @param {Array} array The array to sort. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be * used by the comparator to determine the order of elements. * * Can be one of: * * - `function`: Getter function. The result of this function will be sorted using the * `<`, `=`, `>` operator. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control * ascending or descending sort order (for example, +name or -name). * - `Array`: An array of function or string predicates. The first predicate in the array * is used for sorting, but when two items are equivalent, the next predicate is used. * * @param {boolean=} reverse Reverse the order the array. * @returns {Array} Sorted copy of the source array. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.friends = [{name:'John', phone:'555-1212', age:10}, {name:'Mary', phone:'555-9876', age:19}, {name:'Mike', phone:'555-4321', age:21}, {name:'Adam', phone:'555-5678', age:35}, {name:'Julie', phone:'555-8765', age:29}] $scope.predicate = '-age'; } </script> <div ng-controller="Ctrl"> <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre> <hr/> [ <a href="" ng-click="predicate=''">unsorted</a> ] <table class="friend"> <tr> <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a> (<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th> <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th> <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th> </tr> <tr ng-repeat="friend in friends | orderBy:predicate:reverse"> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <td>{{friend.age}}</td> </tr> </table> </div> </doc:source> <doc:scenario> it('should be reverse ordered by aged', function() { expect(binding('predicate')).toBe('-age'); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '29', '21', '19', '10']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']); }); it('should reorder the table when user selects different predicate', function() { element('.doc-example-live a:contains("Name")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']); expect(repeater('table.friend', 'friend in friends').column('friend.age')). toEqual(['35', '10', '29', '19', '21']); element('.doc-example-live a:contains("Phone")').click(); expect(repeater('table.friend', 'friend in friends').column('friend.phone')). toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']); expect(repeater('table.friend', 'friend in friends').column('friend.name')). toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']); }); </doc:scenario> </doc:example> */ orderByFilter.$inject = ['$parse']; function orderByFilter($parse){ return function(array, sortPredicate, reverseOrder) { if (!isArray(array)) return array; if (!sortPredicate) return array; sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; sortPredicate = map(sortPredicate, function(predicate){ var descending = false, get = predicate || identity; if (isString(predicate)) { if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { descending = predicate.charAt(0) == '-'; predicate = predicate.substring(1); } get = $parse(predicate); } return reverseComparator(function(a,b){ return compare(get(a),get(b)); }, descending); }); var arrayCopy = []; for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); function comparator(o1, o2){ for ( var i = 0; i < sortPredicate.length; i++) { var comp = sortPredicate[i](o1, o2); if (comp !== 0) return comp; } return 0; } function reverseComparator(comp, descending) { return toBoolean(descending) ? function(a,b){return comp(b,a);} : comp; } function compare(v1, v2){ var t1 = typeof v1; var t2 = typeof v2; if (t1 == t2) { if (t1 == "string") v1 = v1.toLowerCase(); if (t1 == "string") v2 = v2.toLowerCase(); if (v1 === v2) return 0; return v1 < v2 ? -1 : 1; } else { return t1 < t2 ? -1 : 1; } } } } function ngDirective(directive) { if (isFunction(directive)) { directive = { link: directive } } directive.restrict = directive.restrict || 'AC'; return valueFn(directive); } /** * @ngdoc directive * @name ng.directive:a * @restrict E * * @description * Modifies the default behavior of html A tag, so that the default action is prevented when href * attribute is empty. * * The reasoning for this change is to allow easy creation of action links with `ngClick` directive * without changing the location or causing page reloads, e.g.: * `<a href="" ng-click="model.$save()">Save</a>` */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { if (msie <= 8) { // turn <a href ng-click="..">link</a> into a stylable link in IE // but only if it doesn't have name attribute, in which case it's an anchor if (!attr.href && !attr.name) { attr.$set('href', ''); } // add a comment node to anchors to workaround IE bug that causes element content to be reset // to new attribute content if attribute is updated with value containing @ and element also // contains value with @ // see issue #1949 element.append(document.createComment('IE fix')); } return function(scope, element) { element.bind('click', function(event){ // if we have no href url, then don't navigate anywhere. if (!element.attr('href')) { event.preventDefault(); } }); } } }); /** * @ngdoc directive * @name ng.directive:ngHref * @restrict A * * @description * Using Angular markup like {{hash}} in an href attribute makes * the page open to a wrong URL, if the user clicks that link before * angular has a chance to replace the {{hash}} with actual URL, the * link will be broken and will most likely return a 404 error. * The `ngHref` directive solves this problem. * * The buggy way to write it: * <pre> * <a href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element A * @param {template} ngHref any string which can contain `{{}}` markup. * * @example * This example uses `link` variable inside `href` attribute: <doc:example> <doc:source> <input ng-model="value" /><br /> <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br /> <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br /> <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br /> <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br /> <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br /> <a id="link-6" ng-href="{{value}}">link</a> (link, change location) </doc:source> <doc:scenario> it('should execute ng-click but not reload when href without value', function() { element('#link-1').click(); expect(input('value').val()).toEqual('1'); expect(element('#link-1').attr('href')).toBe(""); }); it('should execute ng-click but not reload when href empty string', function() { element('#link-2').click(); expect(input('value').val()).toEqual('2'); expect(element('#link-2').attr('href')).toBe(""); }); it('should execute ng-click and change url when ng-href specified', function() { expect(element('#link-3').attr('href')).toBe("/123"); element('#link-3').click(); expect(browser().window().path()).toEqual('/123'); }); it('should execute ng-click but not reload when href empty string and name specified', function() { element('#link-4').click(); expect(input('value').val()).toEqual('4'); expect(element('#link-4').attr('href')).toBe(''); }); it('should execute ng-click but not reload when no href but name specified', function() { element('#link-5').click(); expect(input('value').val()).toEqual('5'); expect(element('#link-5').attr('href')).toBe(undefined); }); it('should only change url when only ng-href', function() { input('value').enter('6'); expect(element('#link-6').attr('href')).toBe('6'); element('#link-6').click(); expect(browser().location().url()).toEqual('/6'); }); </doc:scenario> </doc:example> */ /** * @ngdoc directive * @name ng.directive:ngSrc * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * <pre> * <img src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * The correct way to write it: * <pre> * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/> * </pre> * * @element IMG * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ng.directive:ngSrcset * @restrict A * * @description * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't * work right: The browser will fetch from the URL with the literal * text `{{hash}}` until Angular replaces the expression inside * `{{hash}}`. The `ngSrcset` directive solves this problem. * * The buggy way to write it: * <pre> * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * </pre> * * The correct way to write it: * <pre> * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/> * </pre> * * @element IMG * @param {template} ngSrcset any string which can contain `{{}}` markup. */ /** * @ngdoc directive * @name ng.directive:ngDisabled * @restrict A * * @description * * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: * <pre> * <div ng-init="scope = { isDisabled: false }"> * <button disabled="{{scope.isDisabled}}">Disabled</button> * </div> * </pre> * * The HTML specs do not require browsers to preserve the special attributes such as disabled. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngDisabled` directive. * * @example <doc:example> <doc:source> Click me to toggle: <input type="checkbox" ng-model="checked"><br/> <button ng-model="button" ng-disabled="checked">Button</button> </doc:source> <doc:scenario> it('should toggle button', function() { expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngDisabled Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngChecked * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as checked. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngChecked` directive. * @example <doc:example> <doc:source> Check me to check both: <input type="checkbox" ng-model="master"><br/> <input id="checkSlave" type="checkbox" ng-checked="master"> </doc:source> <doc:scenario> it('should check both checkBoxes', function() { expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy(); input('master').check(); expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {expression} ngChecked Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngMultiple * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as multiple. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngMultiple` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="checked"><br/> <select id="select" ng-multiple="checked"> <option>Misko</option> <option>Igor</option> <option>Vojta</option> <option>Di</option> </select> </doc:source> <doc:scenario> it('should toggle multiple', function() { expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element SELECT * @param {expression} ngMultiple Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngReadonly * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as readonly. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngReadonly` directive. * @example <doc:example> <doc:source> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </doc:source> <doc:scenario> it('should toggle readonly attr', function() { expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy(); input('checked').check(); expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element INPUT * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngSelected * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as selected. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduced the `ngSelected` directive. * @example <doc:example> <doc:source> Check me to select: <input type="checkbox" ng-model="selected"><br/> <select> <option>Hello!</option> <option id="greet" ng-selected="selected">Greetings!</option> </select> </doc:source> <doc:scenario> it('should select Greetings!', function() { expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy(); input('selected').check(); expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element OPTION * @param {string} expression Angular expression that will be evaluated. */ /** * @ngdoc directive * @name ng.directive:ngOpen * @restrict A * * @description * The HTML specs do not require browsers to preserve the special attributes such as open. * (The presence of them means true and absence means false) * This prevents the angular compiler from correctly retrieving the binding expression. * To solve this problem, we introduce the `ngOpen` directive. * * @example <doc:example> <doc:source> Check me check multiple: <input type="checkbox" ng-model="open"><br/> <details id="details" ng-open="open"> <summary>Show/Hide me</summary> </details> </doc:source> <doc:scenario> it('should toggle open', function() { expect(element('#details').prop('open')).toBeFalsy(); input('open').check(); expect(element('#details').prop('open')).toBeTruthy(); }); </doc:scenario> </doc:example> * * @element DETAILS * @param {string} expression Angular expression that will be evaluated. */ var ngAttributeAliasDirectives = {}; // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 100, compile: function() { return function(scope, element, attr) { scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { attr.$set(attrName, !!value); }); }; } }; }; }); // ng-src, ng-srcset, ng-href are interpolated forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); ngAttributeAliasDirectives[normalized] = function() { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { attr.$observe(normalized, function(value) { if (!value) return; attr.$set(attrName, value); // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. // we use attr[attrName] value since $set can sanitize the url. if (msie) element.prop(attrName, attr[attrName]); }); } }; }; }); var nullFormCtrl = { $addControl: noop, $removeControl: noop, $setValidity: noop, $setDirty: noop, $setPristine: noop }; /** * @ngdoc object * @name ng.directive:form.FormController * * @property {boolean} $pristine True if user has not interacted with the form yet. * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containing forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. * * @property {Object} $error Is an object hash, containing references to all invalid controls or * forms, where: * * - keys are validation tokens (error names) — such as `required`, `url` or `email`), * - values are arrays of controls or forms that are invalid with given error. * * @description * `FormController` keeps track of all its controls and nested forms as well as state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance * of `FormController`. * */ //asks for $scope to fool the BC controller module FormController.$inject = ['$element', '$attrs', '$scope']; function FormController(element, attrs) { var form = this, parentForm = element.parent().controller('form') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid errors = form.$error = {}, controls = []; // init state form.$name = attrs.name; form.$dirty = false; form.$pristine = true; form.$valid = true; form.$invalid = false; parentForm.$addControl(form); // Setup initial state of the control element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } form.$addControl = function(control) { controls.push(control); if (control.$name && !form.hasOwnProperty(control.$name)) { form[control.$name] = control; } }; form.$removeControl = function(control) { if (control.$name && form[control.$name] === control) { delete form[control.$name]; } forEach(errors, function(queue, validationToken) { form.$setValidity(validationToken, true, control); }); arrayRemove(controls, control); }; form.$setValidity = function(validationToken, isValid, control) { var queue = errors[validationToken]; if (isValid) { if (queue) { arrayRemove(queue, control); if (!queue.length) { invalidCount--; if (!invalidCount) { toggleValidCss(isValid); form.$valid = true; form.$invalid = false; } errors[validationToken] = false; toggleValidCss(true, validationToken); parentForm.$setValidity(validationToken, true, form); } } } else { if (!invalidCount) { toggleValidCss(isValid); } if (queue) { if (includes(queue, control)) return; } else { errors[validationToken] = queue = []; invalidCount++; toggleValidCss(false, validationToken); parentForm.$setValidity(validationToken, false, form); } queue.push(control); form.$valid = false; form.$invalid = true; } }; form.$setDirty = function() { element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); form.$dirty = true; form.$pristine = false; parentForm.$setDirty(); }; /** * @ngdoc function * @name ng.directive:form.FormController#$setPristine * @methodOf ng.directive:form.FormController * * @description * Sets the form to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the form to its pristine * state (ng-pristine class). This method will also propagate to all the controls contained * in this form. * * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after * saving or resetting it. */ form.$setPristine = function () { element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); form.$dirty = false; form.$pristine = true; forEach(controls, function(control) { control.$setPristine(); }); }; } /** * @ngdoc directive * @name ng.directive:ngForm * @restrict EAC * * @description * Nestable alias of {@link ng.directive:form `form`} directive. HTML * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a * sub-group of controls needs to be determined. * * @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into * related scope, under this name. * */ /** * @ngdoc directive * @name ng.directive:form * @restrict E * * @description * Directive that instantiates * {@link ng.directive:form.FormController FormController}. * * If `name` attribute is specified, the form controller is published onto the current scope under * this name. * * # Alias: {@link ng.directive:ngForm `ngForm`} * * In angular forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this * reason angular provides {@link ng.directive:ngForm `ngForm`} alias * which behaves identical to `<form>` but allows form nesting. * * * # CSS classes * - `ng-valid` Is set if the form is valid. * - `ng-invalid` Is set if the form is invalid. * - `ng-pristine` Is set if the form is pristine. * - `ng-dirty` Is set if the form is dirty. * * * # Submitting a form and preventing default action * * Since the role of forms in client-side Angular applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in application specific way. * * For this reason, Angular prevents the default action (form submission to the server) unless the * `<form>` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when * a form is submitted: * * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element * - {@link ng.directive:ngClick ngClick} directive on the first * button or input field of type submit (input[type=submit]) * * To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This * is because of the following form submission rules coming from the html spec: * * - If a form has only one input field then hitting enter in this field triggers form submit * (`ngSubmit`) * - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter * doesn't trigger submit * - if a form has one or more input fields and one or more buttons or input[type=submit] then * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * * @param {string=} name Name of the form. If specified, the form controller will be published into * related scope, under this name. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.userType = 'guest'; } </script> <form name="myForm" ng-controller="Ctrl"> userType: <input name="input" ng-model="userType" required> <span class="error" ng-show="myForm.input.$error.required">Required!</span><br> <tt>userType = {{userType}}</tt><br> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('userType')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('userType').enter(''); expect(binding('userType')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var formDirectiveFactory = function(isNgForm) { return ['$timeout', function($timeout) { var formDirective = { name: 'form', restrict: 'E', controller: FormController, compile: function() { return { pre: function(scope, formElement, attr, controller) { if (!attr.action) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. var preventDefaultListener = function(event) { event.preventDefault ? event.preventDefault() : event.returnValue = false; // IE }; addEventListenerFn(formElement[0], 'submit', preventDefaultListener); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.bind('$destroy', function() { $timeout(function() { removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); }, 0, false); }); } var parentFormCtrl = formElement.parent().controller('form'), alias = attr.name || attr.ngForm; if (alias) { scope[alias] = controller; } if (parentFormCtrl) { formElement.bind('$destroy', function() { parentFormCtrl.$removeControl(controller); if (alias) { scope[alias] = undefined; } extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards }); } } }; } }; return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective; }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/; var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; var inputType = { /** * @ngdoc inputType * @name ng.directive:input.text * * @description * Standard HTML text input with angular data binding. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Adds `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trimming the * input. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'guest'; $scope.word = /^\s*\w*\s*$/; } </script> <form name="myForm" ng-controller="Ctrl"> Single word: <input type="text" name="input" ng-model="text" ng-pattern="word" required ng-trim="false"> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.pattern"> Single word only!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('guest'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if multi word', function() { input('text').enter('hello world'); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should not be trimmed', function() { input('text').enter('untrimmed '); expect(binding('text')).toEqual('untrimmed '); expect(binding('myForm.input.$valid')).toEqual('true'); }); </doc:scenario> </doc:example> */ 'text': textInputType, /** * @ngdoc inputType * @name ng.directive:input.number * * @description * Text input with number validation and transformation. Sets the `number` validation * error if not a valid number. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value = 12; } </script> <form name="myForm" ng-controller="Ctrl"> Number: <input type="number" name="input" ng-model="value" min="0" max="99" required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <span class="error" ng-show="myForm.list.$error.number"> Not valid number!</span> <tt>value = {{value}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('value')).toEqual('12'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('value').enter(''); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if over max', function() { input('value').enter('123'); expect(binding('value')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'number': numberInputType, /** * @ngdoc inputType * @name ng.directive:input.url * * @description * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'http://google.com'; } </script> <form name="myForm" ng-controller="Ctrl"> URL: <input type="url" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.url"> Not valid url!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('http://google.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not url', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'url': urlInputType, /** * @ngdoc inputType * @name ng.directive:input.email * * @description * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.text = 'me@example.com'; } </script> <form name="myForm" ng-controller="Ctrl"> Email: <input type="email" name="input" ng-model="text" required> <span class="error" ng-show="myForm.input.$error.required"> Required!</span> <span class="error" ng-show="myForm.input.$error.email"> Not valid email!</span> <tt>text = {{text}}</tt><br/> <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/> <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('text')).toEqual('me@example.com'); expect(binding('myForm.input.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('text').enter(''); expect(binding('text')).toEqual(''); expect(binding('myForm.input.$valid')).toEqual('false'); }); it('should be invalid if not email', function() { input('text').enter('xxx'); expect(binding('myForm.input.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ 'email': emailInputType, /** * @ngdoc inputType * @name ng.directive:input.radio * * @description * HTML radio button. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string} value The value to which the expression should be set when selected. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.color = 'blue'; } </script> <form name="myForm" ng-controller="Ctrl"> <input type="radio" ng-model="color" value="red"> Red <br/> <input type="radio" ng-model="color" value="green"> Green <br/> <input type="radio" ng-model="color" value="blue"> Blue <br/> <tt>color = {{color}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('color')).toEqual('blue'); input('color').select('red'); expect(binding('color')).toEqual('red'); }); </doc:scenario> </doc:example> */ 'radio': radioInputType, /** * @ngdoc inputType * @name ng.directive:input.checkbox * * @description * HTML checkbox. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} ngTrueValue The value to which the expression should be set when selected. * @param {string=} ngFalseValue The value to which the expression should be set when not selected. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.value1 = true; $scope.value2 = 'YES' } </script> <form name="myForm" ng-controller="Ctrl"> Value1: <input type="checkbox" ng-model="value1"> <br/> Value2: <input type="checkbox" ng-model="value2" ng-true-value="YES" ng-false-value="NO"> <br/> <tt>value1 = {{value1}}</tt><br/> <tt>value2 = {{value2}}</tt><br/> </form> </doc:source> <doc:scenario> it('should change state', function() { expect(binding('value1')).toEqual('true'); expect(binding('value2')).toEqual('YES'); input('value1').check(); input('value2').check(); expect(binding('value1')).toEqual('false'); expect(binding('value2')).toEqual('NO'); }); </doc:scenario> </doc:example> */ 'checkbox': checkboxInputType, 'hidden': noop, 'button': noop, 'submit': noop, 'reset': noop }; function isEmpty(value) { return isUndefined(value) || value === '' || value === null || value !== value; } function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { var listener = function() { var value = element.val(); // By default we will trim the value // If the attribute ng-trim exists we will avoid trimming // e.g. <input ng-model="foo" ng-trim="false"> if (toBoolean(attr.ngTrim || 'T')) { value = trim(value); } if (ctrl.$viewValue !== value) { scope.$apply(function() { ctrl.$setViewValue(value); }); } }; // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the // input event on backspace, delete or cut if ($sniffer.hasEvent('input')) { element.bind('input', listener); } else { var timeout; var deferListener = function() { if (!timeout) { timeout = $browser.defer(function() { listener(); timeout = null; }); } }; element.bind('keydown', function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; deferListener(); }); // if user paste into input using mouse, we need "change" event to catch it element.bind('change', listener); // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it if ($sniffer.hasEvent('paste')) { element.bind('paste cut', deferListener); } } ctrl.$render = function() { element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); }; // pattern validator var pattern = attr.ngPattern, patternValidator, match; var validate = function(regexp, value) { if (isEmpty(value) || regexp.test(value)) { ctrl.$setValidity('pattern', true); return value; } else { ctrl.$setValidity('pattern', false); return undefined; } }; if (pattern) { match = pattern.match(/^\/(.*)\/([gim]*)$/); if (match) { pattern = new RegExp(match[1], match[2]); patternValidator = function(value) { return validate(pattern, value) }; } else { patternValidator = function(value) { var patternObj = scope.$eval(pattern); if (!patternObj || !patternObj.test) { throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj); } return validate(patternObj, value); }; } ctrl.$formatters.push(patternValidator); ctrl.$parsers.push(patternValidator); } // min length validator if (attr.ngMinlength) { var minlength = int(attr.ngMinlength); var minLengthValidator = function(value) { if (!isEmpty(value) && value.length < minlength) { ctrl.$setValidity('minlength', false); return undefined; } else { ctrl.$setValidity('minlength', true); return value; } }; ctrl.$parsers.push(minLengthValidator); ctrl.$formatters.push(minLengthValidator); } // max length validator if (attr.ngMaxlength) { var maxlength = int(attr.ngMaxlength); var maxLengthValidator = function(value) { if (!isEmpty(value) && value.length > maxlength) { ctrl.$setValidity('maxlength', false); return undefined; } else { ctrl.$setValidity('maxlength', true); return value; } }; ctrl.$parsers.push(maxLengthValidator); ctrl.$formatters.push(maxLengthValidator); } } function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); ctrl.$parsers.push(function(value) { var empty = isEmpty(value); if (empty || NUMBER_REGEXP.test(value)) { ctrl.$setValidity('number', true); return value === '' ? null : (empty ? value : parseFloat(value)); } else { ctrl.$setValidity('number', false); return undefined; } }); ctrl.$formatters.push(function(value) { return isEmpty(value) ? '' : '' + value; }); if (attr.min) { var min = parseFloat(attr.min); var minValidator = function(value) { if (!isEmpty(value) && value < min) { ctrl.$setValidity('min', false); return undefined; } else { ctrl.$setValidity('min', true); return value; } }; ctrl.$parsers.push(minValidator); ctrl.$formatters.push(minValidator); } if (attr.max) { var max = parseFloat(attr.max); var maxValidator = function(value) { if (!isEmpty(value) && value > max) { ctrl.$setValidity('max', false); return undefined; } else { ctrl.$setValidity('max', true); return value; } }; ctrl.$parsers.push(maxValidator); ctrl.$formatters.push(maxValidator); } ctrl.$formatters.push(function(value) { if (isEmpty(value) || isNumber(value)) { ctrl.$setValidity('number', true); return value; } else { ctrl.$setValidity('number', false); return undefined; } }); } function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var urlValidator = function(value) { if (isEmpty(value) || URL_REGEXP.test(value)) { ctrl.$setValidity('url', true); return value; } else { ctrl.$setValidity('url', false); return undefined; } }; ctrl.$formatters.push(urlValidator); ctrl.$parsers.push(urlValidator); } function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { textInputType(scope, element, attr, ctrl, $sniffer, $browser); var emailValidator = function(value) { if (isEmpty(value) || EMAIL_REGEXP.test(value)) { ctrl.$setValidity('email', true); return value; } else { ctrl.$setValidity('email', false); return undefined; } }; ctrl.$formatters.push(emailValidator); ctrl.$parsers.push(emailValidator); } function radioInputType(scope, element, attr, ctrl) { // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } element.bind('click', function() { if (element[0].checked) { scope.$apply(function() { ctrl.$setViewValue(attr.value); }); } }); ctrl.$render = function() { var value = attr.value; element[0].checked = (value == ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } function checkboxInputType(scope, element, attr, ctrl) { var trueValue = attr.ngTrueValue, falseValue = attr.ngFalseValue; if (!isString(trueValue)) trueValue = true; if (!isString(falseValue)) falseValue = false; element.bind('click', function() { scope.$apply(function() { ctrl.$setViewValue(element[0].checked); }); }); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; ctrl.$formatters.push(function(value) { return value === trueValue; }); ctrl.$parsers.push(function(value) { return value ? trueValue : falseValue; }); } /** * @ngdoc directive * @name ng.directive:textarea * @restrict E * * @description * HTML textarea element control with angular data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. */ /** * @ngdoc directive * @name ng.directive:input * @restrict E * * @description * HTML input element control with angular data-binding. Input control follows HTML5 input types * and polyfills the HTML5 validation behavior for older browsers. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {boolean=} ngRequired Sets `required` attribute if set to true * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than * maxlength. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for * patterns defined as scope expressions. * @param {string=} ngChange Angular expression to be executed when input changes due to user * interaction with the input element. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.user = {name: 'guest', last: 'visitor'}; } </script> <div ng-controller="Ctrl"> <form name="myForm"> User name: <input type="text" name="userName" ng-model="user.name" required> <span class="error" ng-show="myForm.userName.$error.required"> Required!</span><br> Last name: <input type="text" name="lastName" ng-model="user.last" ng-minlength="3" ng-maxlength="10"> <span class="error" ng-show="myForm.lastName.$error.minlength"> Too short!</span> <span class="error" ng-show="myForm.lastName.$error.maxlength"> Too long!</span><br> </form> <hr> <tt>user = {{user}}</tt><br/> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br> <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br> <tt>myForm.$valid = {{myForm.$valid}}</tt><br> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br> </div> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if empty when required', function() { input('user.name').enter(''); expect(binding('user')).toEqual('{"last":"visitor"}'); expect(binding('myForm.userName.$valid')).toEqual('false'); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be valid if empty when min length is set', function() { input('user.last').enter(''); expect(binding('user')).toEqual('{"name":"guest","last":""}'); expect(binding('myForm.lastName.$valid')).toEqual('true'); expect(binding('myForm.$valid')).toEqual('true'); }); it('should be invalid if less than required min length', function() { input('user.last').enter('xx'); expect(binding('user')).toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/minlength/); expect(binding('myForm.$valid')).toEqual('false'); }); it('should be invalid if longer than max length', function() { input('user.last').enter('some ridiculously long name'); expect(binding('user')) .toEqual('{"name":"guest"}'); expect(binding('myForm.lastName.$valid')).toEqual('false'); expect(binding('myForm.lastName.$error')).toMatch(/maxlength/); expect(binding('myForm.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) { return { restrict: 'E', require: '?ngModel', link: function(scope, element, attr, ctrl) { if (ctrl) { (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer, $browser); } } }; }]; var VALID_CLASS = 'ng-valid', INVALID_CLASS = 'ng-invalid', PRISTINE_CLASS = 'ng-pristine', DIRTY_CLASS = 'ng-dirty'; /** * @ngdoc object * @name ng.directive:ngModel.NgModelController * * @property {string} $viewValue Actual string value in the view. * @property {*} $modelValue The value in the model, that the control is bound to. * @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes * all of these functions to sanitize / convert the value as well as validate. * * @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of * these functions to convert the value as well as validate. * * @property {Object} $error An object hash with all errors as keys. * * @property {boolean} $pristine True if user has not interacted with the control yet. * @property {boolean} $dirty True if user has already interacted with the control. * @property {boolean} $valid True if there is no error. * @property {boolean} $invalid True if at least one error on the control. * * @description * * `NgModelController` provides API for the `ng-model` directive. The controller contains * services for data-binding, validation, CSS update, value formatting and parsing. It * specifically does not contain any logic which deals with DOM rendering or listening to * DOM events. The `NgModelController` is meant to be extended by other directives where, the * directive provides DOM manipulation and the `NgModelController` provides the data-binding. * * This example shows how to use `NgModelController` with a custom control to achieve * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) * collaborate together to achieve the desired result. * * <example module="customControl"> <file name="style.css"> [contenteditable] { border: 1px solid black; background-color: white; min-height: 20px; } .ng-invalid { border: 1px solid red; } </file> <file name="script.js"> angular.module('customControl', []). directive('contenteditable', function() { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html(ngModel.$viewValue || ''); }; // Listen for change events to enable binding element.bind('blur keyup change', function() { scope.$apply(read); }); read(); // initialize // Write data to the model function read() { ngModel.$setViewValue(element.html()); } } }; }); </file> <file name="index.html"> <form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form> </file> <file name="scenario.js"> it('should data-bind and become invalid', function() { var contentEditable = element('[contenteditable]'); expect(contentEditable.text()).toEqual('Change me!'); input('userContent').enter(''); expect(contentEditable.text()).toEqual(''); expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/); }); </file> * </example> * */ var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', function($scope, $exceptionHandler, $attr, $element, $parse) { this.$viewValue = Number.NaN; this.$modelValue = Number.NaN; this.$parsers = []; this.$formatters = []; this.$viewChangeListeners = []; this.$pristine = true; this.$dirty = false; this.$valid = true; this.$invalid = false; this.$name = $attr.name; var ngModelGet = $parse($attr.ngModel), ngModelSet = ngModelGet.assign; if (!ngModelSet) { throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel + ' (' + startingTag($element) + ')'); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$render * @methodOf ng.directive:ngModel.NgModelController * * @description * Called when the view needs to be updated. It is expected that the user of the ng-model * directive will implement this method. */ this.$render = noop; var parentForm = $element.inheritedData('$formController') || nullFormCtrl, invalidCount = 0, // used to easily determine if we are valid $error = this.$error = {}; // keep invalid keys here // Setup initial state of the control $element.addClass(PRISTINE_CLASS); toggleValidCss(true); // convenience method for easy toggling of classes function toggleValidCss(isValid, validationErrorKey) { validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; $element. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey). addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); } /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setValidity * @methodOf ng.directive:ngModel.NgModelController * * @description * Change the validity state, and notifies the form when the control changes validity. (i.e. it * does not notify form if given validator is already marked as invalid). * * This method should be called by validators - i.e. the parser or formatter functions. * * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. * The `validationErrorKey` should be in camelCase and will get converted into dash-case * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` * class and can be bound to as `{{someForm.someControl.$error.myError}}` . * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). */ this.$setValidity = function(validationErrorKey, isValid) { if ($error[validationErrorKey] === !isValid) return; if (isValid) { if ($error[validationErrorKey]) invalidCount--; if (!invalidCount) { toggleValidCss(true); this.$valid = true; this.$invalid = false; } } else { toggleValidCss(false); this.$invalid = true; this.$valid = false; invalidCount++; } $error[validationErrorKey] = !isValid; toggleValidCss(isValid, validationErrorKey); parentForm.$setValidity(validationErrorKey, isValid, this); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setPristine * @methodOf ng.directive:ngModel.NgModelController * * @description * Sets the control to its pristine state. * * This method can be called to remove the 'ng-dirty' class and set the control to its pristine * state (ng-pristine class). */ this.$setPristine = function () { this.$dirty = false; this.$pristine = true; $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS); }; /** * @ngdoc function * @name ng.directive:ngModel.NgModelController#$setViewValue * @methodOf ng.directive:ngModel.NgModelController * * @description * Read a value from view. * * This method should be called from within a DOM event handler. * For example {@link ng.directive:input input} or * {@link ng.directive:select select} directives call it. * * It internally calls all `parsers` and if resulted value is valid, updates the model and * calls all registered change listeners. * * @param {string} value Value from the view. */ this.$setViewValue = function(value) { this.$viewValue = value; // change to dirty if (this.$pristine) { this.$dirty = true; this.$pristine = false; $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS); parentForm.$setDirty(); } forEach(this.$parsers, function(fn) { value = fn(value); }); if (this.$modelValue !== value) { this.$modelValue = value; ngModelSet($scope, value); forEach(this.$viewChangeListeners, function(listener) { try { listener(); } catch(e) { $exceptionHandler(e); } }) } }; // model -> value var ctrl = this; $scope.$watch(function ngModelWatch() { var value = ngModelGet($scope); // if scope model value and ngModel value are out of sync if (ctrl.$modelValue !== value) { var formatters = ctrl.$formatters, idx = formatters.length; ctrl.$modelValue = value; while(idx--) { value = formatters[idx](value); } if (ctrl.$viewValue !== value) { ctrl.$viewValue = value; ctrl.$render(); } } }); }]; /** * @ngdoc directive * @name ng.directive:ngModel * * @element input * * @description * Is directive that tells Angular to do two-way data binding. It works together with `input`, * `select`, `textarea`. You can easily write your own directives to use `ngModel` as well. * * `ngModel` is responsible for: * * - binding the view into the model, which other directives such as `input`, `textarea` or `select` * require, * - providing validation behavior (i.e. required, number, email, url), * - keeping state of the control (valid/invalid, dirty/pristine, validation errors), * - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`), * - register the control with parent {@link ng.directive:form form}. * * For basic examples, how to use `ngModel`, see: * * - {@link ng.directive:input input} * - {@link ng.directive:input.text text} * - {@link ng.directive:input.checkbox checkbox} * - {@link ng.directive:input.radio radio} * - {@link ng.directive:input.number number} * - {@link ng.directive:input.email email} * - {@link ng.directive:input.url url} * - {@link ng.directive:select select} * - {@link ng.directive:textarea textarea} * */ var ngModelDirective = function() { return { require: ['ngModel', '^?form'], controller: NgModelController, link: function(scope, element, attr, ctrls) { // notify others, especially parent forms var modelCtrl = ctrls[0], formCtrl = ctrls[1] || nullFormCtrl; formCtrl.$addControl(modelCtrl); element.bind('$destroy', function() { formCtrl.$removeControl(modelCtrl); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngChange * @restrict E * * @description * Evaluate given expression when user changes the input. * The expression is not evaluated when the value change is coming from the model. * * Note, this directive requires `ngModel` to be present. * * @element input * * @example * <doc:example> * <doc:source> * <script> * function Controller($scope) { * $scope.counter = 0; * $scope.change = function() { * $scope.counter++; * }; * } * </script> * <div ng-controller="Controller"> * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" /> * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" /> * <label for="ng-change-example2">Confirmed</label><br /> * debug = {{confirmed}}<br /> * counter = {{counter}} * </div> * </doc:source> * <doc:scenario> * it('should evaluate the expression if changing from view', function() { * expect(binding('counter')).toEqual('0'); * element('#ng-change-example1').click(); * expect(binding('counter')).toEqual('1'); * expect(binding('confirmed')).toEqual('true'); * }); * * it('should not evaluate the expression if changing from model', function() { * element('#ng-change-example2').click(); * expect(binding('counter')).toEqual('0'); * expect(binding('confirmed')).toEqual('true'); * }); * </doc:scenario> * </doc:example> */ var ngChangeDirective = valueFn({ require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { scope.$eval(attr.ngChange); }); } }); var requiredDirective = function() { return { require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; attr.required = true; // force truthy in case we are on non input element var validator = function(value) { if (attr.required && (isEmpty(value) || value === false)) { ctrl.$setValidity('required', false); return; } else { ctrl.$setValidity('required', true); return value; } }; ctrl.$formatters.push(validator); ctrl.$parsers.unshift(validator); attr.$observe('required', function() { validator(ctrl.$viewValue); }); } }; }; /** * @ngdoc directive * @name ng.directive:ngList * * @description * Text input that converts between comma-separated string into an array of strings. * * @element input * @param {string=} ngList optional delimiter that should be used to split the value. If * specified in form `/something/` then the value will be converted into a regular expression. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.names = ['igor', 'misko', 'vojta']; } </script> <form name="myForm" ng-controller="Ctrl"> List: <input name="namesInput" ng-model="names" ng-list required> <span class="error" ng-show="myForm.list.$error.required"> Required!</span> <tt>names = {{names}}</tt><br/> <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/> <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/> <tt>myForm.$valid = {{myForm.$valid}}</tt><br/> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/> </form> </doc:source> <doc:scenario> it('should initialize to model', function() { expect(binding('names')).toEqual('["igor","misko","vojta"]'); expect(binding('myForm.namesInput.$valid')).toEqual('true'); }); it('should be invalid if empty', function() { input('names').enter(''); expect(binding('names')).toEqual('[]'); expect(binding('myForm.namesInput.$valid')).toEqual('false'); }); </doc:scenario> </doc:example> */ var ngListDirective = function() { return { require: 'ngModel', link: function(scope, element, attr, ctrl) { var match = /\/(.*)\//.exec(attr.ngList), separator = match && new RegExp(match[1]) || attr.ngList || ','; var parse = function(viewValue) { var list = []; if (viewValue) { forEach(viewValue.split(separator), function(value) { if (value) list.push(trim(value)); }); } return list; }; ctrl.$parsers.push(parse); ctrl.$formatters.push(function(value) { if (isArray(value)) { return value.join(', '); } return undefined; }); } }; }; var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; var ngValueDirective = function() { return { priority: 100, compile: function(tpl, tplAttr) { if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { return function(scope, elm, attr) { attr.$set('value', scope.$eval(attr.ngValue)); }; } else { return function(scope, elm, attr) { scope.$watch(attr.ngValue, function valueWatchAction(value) { attr.$set('value', value, false); }); }; } } }; }; /** * @ngdoc directive * @name ng.directive:ngBind * * @description * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element * with the value of a given expression, and to update the text content when the value of that * expression changes. * * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like * `{{ expression }}` which is similar but less verbose. * * One scenario in which the use of `ngBind` is preferred over `{{ expression }}` binding is when * it's desirable to put bindings into template that is momentarily displayed by the browser in its * raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the * bindings invisible to the user while the page is loading. * * An alternative solution to this problem would be using the * {@link ng.directive:ngCloak ngCloak} directive. * * * @element ANY * @param {expression} ngBind {@link guide/expression Expression} to evaluate. * * @example * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.name = 'Whirled'; } </script> <div ng-controller="Ctrl"> Enter name: <input type="text" ng-model="name"><br> Hello <span ng-bind="name"></span>! </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('name')).toBe('Whirled'); using('.doc-example-live').input('name').enter('world'); expect(using('.doc-example-live').binding('name')).toBe('world'); }); </doc:scenario> </doc:example> */ var ngBindDirective = ngDirective(function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBind); scope.$watch(attr.ngBind, function ngBindWatchAction(value) { element.text(value == undefined ? '' : value); }); }); /** * @ngdoc directive * @name ng.directive:ngBindTemplate * * @description * The `ngBindTemplate` directive specifies that the element * text should be replaced with the template in ngBindTemplate. * Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}` * expressions. (This is required since some HTML elements * can not have SPAN elements such as TITLE, or OPTION to name a few.) * * @element ANY * @param {string} ngBindTemplate template of form * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval. * * @example * Try it here: enter text in text box and watch the greeting change. <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.salutation = 'Hello'; $scope.name = 'World'; } </script> <div ng-controller="Ctrl"> Salutation: <input type="text" ng-model="salutation"><br> Name: <input type="text" ng-model="name"><br> <pre ng-bind-template="{{salutation}} {{name}}!"></pre> </div> </doc:source> <doc:scenario> it('should check ng-bind', function() { expect(using('.doc-example-live').binding('salutation')). toBe('Hello'); expect(using('.doc-example-live').binding('name')). toBe('World'); using('.doc-example-live').input('salutation').enter('Greetings'); using('.doc-example-live').input('name').enter('user'); expect(using('.doc-example-live').binding('salutation')). toBe('Greetings'); expect(using('.doc-example-live').binding('name')). toBe('user'); }); </doc:scenario> </doc:example> */ var ngBindTemplateDirective = ['$interpolate', function($interpolate) { return function(scope, element, attr) { // TODO: move this to scenario runner var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); element.addClass('ng-binding').data('$binding', interpolateFn); attr.$observe('ngBindTemplate', function(value) { element.text(value); }); } }]; /** * @ngdoc directive * @name ng.directive:ngBindHtmlUnsafe * * @description * Creates a binding that will innerHTML the result of evaluating the `expression` into the current * element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if * {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too * restrictive and when you absolutely trust the source of the content you are binding to. * * See {@link ngSanitize.$sanitize $sanitize} docs for examples. * * @element ANY * @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate. */ var ngBindHtmlUnsafeDirective = [function() { return function(scope, element, attr) { element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe); scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) { element.html(value || ''); }); }; }]; function classDirective(name, selector) { name = 'ngClass' + name; return ngDirective(function(scope, element, attr) { var oldVal = undefined; scope.$watch(attr[name], ngClassWatchAction, true); attr.$observe('class', function(value) { var ngClass = scope.$eval(attr[name]); ngClassWatchAction(ngClass, ngClass); }); if (name !== 'ngClass') { scope.$watch('$index', function($index, old$index) { var mod = $index & 1; if (mod !== old$index & 1) { if (mod === selector) { addClass(scope.$eval(attr[name])); } else { removeClass(scope.$eval(attr[name])); } } }); } function ngClassWatchAction(newVal) { if (selector === true || scope.$index % 2 === selector) { if (oldVal && !equals(newVal,oldVal)) { removeClass(oldVal); } addClass(newVal); } oldVal = copy(newVal); } function removeClass(classVal) { if (isObject(classVal) && !isArray(classVal)) { classVal = map(classVal, function(v, k) { if (v) return k }); } element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal); } function addClass(classVal) { if (isObject(classVal) && !isArray(classVal)) { classVal = map(classVal, function(v, k) { if (v) return k }); } if (classVal) { element.addClass(isArray(classVal) ? classVal.join(' ') : classVal); } } }); } /** * @ngdoc directive * @name ng.directive:ngClass * * @description * The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an * expression that represents all classes to be added. * * The directive won't add duplicate classes if a particular class was already set. * * When the expression changes, the previously added classes are removed and only then the * new classes are added. * * @element ANY * @param {expression} ngClass {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class * names, an array, or a map of class names to boolean values. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myVar='my-class'"> <input type="button" value="clear" ng-click="myVar=''"> <br> <span ng-class="myVar">Sample Text</span> </file> <file name="style.css"> .my-class { color: red; } </file> <file name="scenario.js"> it('should check ng-class', function() { expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); using('.doc-example-live').element(':button:first').click(); expect(element('.doc-example-live span').prop('className')). toMatch(/my-class/); using('.doc-example-live').element(':button:last').click(); expect(element('.doc-example-live span').prop('className')).not(). toMatch(/my-class/); }); </file> </example> */ var ngClassDirective = classDirective('', true); /** * @ngdoc directive * @name ng.directive:ngClassOdd * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result * of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassOddDirective = classDirective('Odd', 0); /** * @ngdoc directive * @name ng.directive:ngClassEven * * @description * The `ngClassOdd` and `ngClassEven` directives work exactly as * {@link ng.directive:ngClass ngClass}, except it works in * conjunction with `ngRepeat` and takes affect only on odd (even) rows. * * This directive can be applied only within a scope of an * {@link ng.directive:ngRepeat ngRepeat}. * * @element ANY * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The * result of the evaluation can be a string representing space delimited class names or an array. * * @example <example> <file name="index.html"> <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']"> <li ng-repeat="name in names"> <span ng-class-odd="'odd'" ng-class-even="'even'"> {{name}} &nbsp; &nbsp; &nbsp; </span> </li> </ol> </file> <file name="style.css"> .odd { color: red; } .even { color: blue; } </file> <file name="scenario.js"> it('should check ng-class-odd and ng-class-even', function() { expect(element('.doc-example-live li:first span').prop('className')). toMatch(/odd/); expect(element('.doc-example-live li:last span').prop('className')). toMatch(/even/); }); </file> </example> */ var ngClassEvenDirective = classDirective('Even', 1); /** * @ngdoc directive * @name ng.directive:ngCloak * * @description * The `ngCloak` directive is used to prevent the Angular html template from being briefly * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this * directive to avoid the undesirable flicker effect caused by the html template display. * * The directive can be applied to the `<body>` element, but typically a fine-grained application is * preferred in order to benefit from progressive rendering of the browser view. * * `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and * `angular.min.js` files. Following is the css rule: * * <pre> * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { * display: none; * } * </pre> * * When this css rule is loaded by the browser, all html elements (including their children) that * are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive * during the compilation of the template it deletes the `ngCloak` element attribute, which * makes the compiled element visible. * * For the best result, `angular.js` script must be loaded in the head section of the html file; * alternatively, the css rule (above) must be included in the external stylesheet of the * application. * * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css * class `ngCloak` in addition to `ngCloak` directive as shown in the example below. * * @element ANY * * @example <doc:example> <doc:source> <div id="template1" ng-cloak>{{ 'hello' }}</div> <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div> </doc:source> <doc:scenario> it('should remove the template directive and css class', function() { expect(element('.doc-example-live #template1').attr('ng-cloak')). not().toBeDefined(); expect(element('.doc-example-live #template2').attr('ng-cloak')). not().toBeDefined(); }); </doc:scenario> </doc:example> * */ var ngCloakDirective = ngDirective({ compile: function(element, attr) { attr.$set('ngCloak', undefined); element.removeClass('ng-cloak'); } }); /** * @ngdoc directive * @name ng.directive:ngController * * @description * The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular * supports the principles behind the Model-View-Controller design pattern. * * MVC components in angular: * * * Model — The Model is data in scope properties; scopes are attached to the DOM. * * View — The template (HTML with data bindings) is rendered into the View. * * Controller — The `ngController` directive specifies a Controller class; the class has * methods that typically express the business logic behind the application. * * Note that an alternative way to define controllers is via the {@link ng.$route $route} service. * * @element ANY * @scope * @param {expression} ngController Name of a globally accessible constructor function or an * {@link guide/expression expression} that on the current scope evaluates to a * constructor function. The controller instance can further be published into the scope * by adding `as localName` the controller name attribute. * * @example * Here is a simple form for editing user contact information. Adding, removing, clearing, and * greeting are methods declared on the controller (see source tab). These methods can * easily be called from the angular markup. Notice that the scope becomes the `this` for the * controller's instance. This allows for easy access to the view data from the controller. Also * notice that any changes to the data are automatically reflected in the View without the need * for a manual update. The example is included in two different declaration styles based on * your style preferences. <doc:example> <doc:source> <script> function SettingsController() { this.name = "John Smith"; this.contacts = [ {type: 'phone', value: '408 555 1212'}, {type: 'email', value: 'john.smith@example.org'} ]; }; SettingsController.prototype.greet = function() { alert(this.name); }; SettingsController.prototype.addContact = function() { this.contacts.push({type: 'email', value: 'yourname@example.org'}); }; SettingsController.prototype.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; SettingsController.prototype.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; </script> <div ng-controller="SettingsController as settings"> Name: <input type="text" ng-model="settings.name"/> [ <a href="" ng-click="settings.greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in settings.contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="settings.clearContact(contact)">clear</a> | <a href="" ng-click="settings.removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('yourname@example.org'); }); </doc:scenario> </doc:example> <doc:example> <doc:source> <script> function SettingsController($scope) { $scope.name = "John Smith"; $scope.contacts = [ {type:'phone', value:'408 555 1212'}, {type:'email', value:'john.smith@example.org'} ]; $scope.greet = function() { alert(this.name); }; $scope.addContact = function() { this.contacts.push({type:'email', value:'yourname@example.org'}); }; $scope.removeContact = function(contactToRemove) { var index = this.contacts.indexOf(contactToRemove); this.contacts.splice(index, 1); }; $scope.clearContact = function(contact) { contact.type = 'phone'; contact.value = ''; }; } </script> <div ng-controller="SettingsController"> Name: <input type="text" ng-model="name"/> [ <a href="" ng-click="greet()">greet</a> ]<br/> Contact: <ul> <li ng-repeat="contact in contacts"> <select ng-model="contact.type"> <option>phone</option> <option>email</option> </select> <input type="text" ng-model="contact.value"/> [ <a href="" ng-click="clearContact(contact)">clear</a> | <a href="" ng-click="removeContact(contact)">X</a> ] </li> <li>[ <a href="" ng-click="addContact()">add</a> ]</li> </ul> </div> </doc:source> <doc:scenario> it('should check controller', function() { expect(element('.doc-example-live div>:input').val()).toBe('John Smith'); expect(element('.doc-example-live li:nth-child(1) input').val()) .toBe('408 555 1212'); expect(element('.doc-example-live li:nth-child(2) input').val()) .toBe('john.smith@example.org'); element('.doc-example-live li:first a:contains("clear")').click(); expect(element('.doc-example-live li:first input').val()).toBe(''); element('.doc-example-live li:last a:contains("add")').click(); expect(element('.doc-example-live li:nth-child(3) input').val()) .toBe('yourname@example.org'); }); </doc:scenario> </doc:example> */ var ngControllerDirective = [function() { return { scope: true, controller: '@' }; }]; /** * @ngdoc directive * @name ng.directive:ngCsp * @priority 1000 * * @element html * @description * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. * * This is necessary when developing things like Google Chrome Extensions. * * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). * For us to be compatible, we just need to implement the "getterFn" in $parse without violating * any of these restrictions. * * AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp` * it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will * be raised. * * In order to use this feature put `ngCsp` directive on the root element of the application. * * @example * This example shows how to apply the `ngCsp` directive to the `html` tag. <pre> <!doctype html> <html ng-app ng-csp> ... ... </html> </pre> */ var ngCspDirective = ['$sniffer', function($sniffer) { return { priority: 1000, compile: function() { $sniffer.csp = true; } }; }]; /** * @ngdoc directive * @name ng.directive:ngClick * * @description * The ngClick allows you to specify custom behavior when * element is clicked. * * @element ANY * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon * click. (Event object is available as `$event`) * * @example <doc:example> <doc:source> <button ng-click="count = count + 1" ng-init="count=0"> Increment </button> count: {{count}} </doc:source> <doc:scenario> it('should check ng-click', function() { expect(binding('count')).toBe('0'); element('.doc-example-live :button').click(); expect(binding('count')).toBe('1'); }); </doc:scenario> </doc:example> */ /* * A directive that allows creation of custom onclick handlers that are defined as angular * expressions and are compiled and executed within the current scope. * * Events that are handled via these handler are always configured not to propagate further. */ var ngEventDirectives = {}; forEach( 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress'.split(' '), function(name) { var directiveName = directiveNormalize('ng-' + name); ngEventDirectives[directiveName] = ['$parse', function($parse) { return function(scope, element, attr) { var fn = $parse(attr[directiveName]); element.bind(lowercase(name), function(event) { scope.$apply(function() { fn(scope, {$event:event}); }); }); }; }]; } ); /** * @ngdoc directive * @name ng.directive:ngDblclick * * @description * The `ngDblclick` directive allows you to specify custom behavior on dblclick event. * * @element ANY * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon * dblclick. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousedown * * @description * The ngMousedown directive allows you to specify custom behavior on mousedown event. * * @element ANY * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon * mousedown. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseup * * @description * Specify custom behavior on mouseup event. * * @element ANY * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon * mouseup. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseover * * @description * Specify custom behavior on mouseover event. * * @element ANY * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon * mouseover. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseenter * * @description * Specify custom behavior on mouseenter event. * * @element ANY * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon * mouseenter. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMouseleave * * @description * Specify custom behavior on mouseleave event. * * @element ANY * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon * mouseleave. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngMousemove * * @description * Specify custom behavior on mousemove event. * * @element ANY * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon * mousemove. (Event object is available as `$event`) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeydown * * @description * Specify custom behavior on keydown event. * * @element ANY * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeyup * * @description * Specify custom behavior on keyup event. * * @element ANY * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngKeypress * * @description * Specify custom behavior on keypress event. * * @element ANY * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) * * @example * See {@link ng.directive:ngClick ngClick} */ /** * @ngdoc directive * @name ng.directive:ngSubmit * * @description * Enables binding angular expressions to onsubmit events. * * Additionally it prevents the default action (which for form means sending the request to the * server and reloading the current page). * * @element form * @param {expression} ngSubmit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.list = []; $scope.text = 'hello'; $scope.submit = function() { if (this.text) { this.list.push(this.text); this.text = ''; } }; } </script> <form ng-submit="submit()" ng-controller="Ctrl"> Enter text and hit enter: <input type="text" ng-model="text" name="text" /> <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre> </form> </doc:source> <doc:scenario> it('should check ng-submit', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); expect(input('text').val()).toBe(''); }); it('should ignore empty strings', function() { expect(binding('list')).toBe('[]'); element('.doc-example-live #submit').click(); element('.doc-example-live #submit').click(); expect(binding('list')).toBe('["hello"]'); }); </doc:scenario> </doc:example> */ var ngSubmitDirective = ngDirective(function(scope, element, attrs) { element.bind('submit', function() { scope.$apply(attrs.ngSubmit); }); }); /** * @ngdoc directive * @name ng.directive:ngIf * @restrict A * * @description * The `ngIf` directive removes and recreates a portion of the DOM tree (HTML) * conditionally based on **"falsy"** and **"truthy"** values, respectively, evaluated within * an {expression}. In other words, if the expression assigned to **ngIf evaluates to a false * value** then **the element is removed from the DOM** and **if true** then **a clone of the * element is reinserted into the DOM**. * * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the * element in the DOM rather than changing its visibility via the `display` css property. A common * case when this difference is significant is when using css selectors that rely on an element's * position within the DOM (HTML), such as the `:first-child` or `:last-child` pseudo-classes. * * Note that **when an element is removed using ngIf its scope is destroyed** and **a new scope * is created when the element is restored**. The scope created within `ngIf` inherits from * its parent scope using * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}. * An important implication of this is if `ngModel` is used within `ngIf` to bind to * a javascript primitive defined in the parent scope. In this case any modifications made to the * variable within the child scope will override (hide) the value in the parent scope. * * Also, `ngIf` recreates elements using their compiled state. An example scenario of this behavior * is if an element's class attribute is directly modified after it's compiled, using something like * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element * the added class will be lost because the original compiled state is used to regenerate the element. * * Additionally, you can provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container * leave - happens just before the ngIf contents are removed from the DOM * * @element ANY * @scope * @param {expression} ngIf If the {@link guide/expression expression} is falsy then * the element is removed from the DOM tree (HTML). * * @example <example animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/> Show when checked: <span ng-if="checked" ng-animate="'example'"> I'm removed when the checkbox is unchecked. </span> </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; } .example-enter { opacity:0; } .example-enter.example-enter-active { opacity:1; } .example-leave { opacity:1; } .example-leave.example-leave-active { opacity:0; } </file> </example> */ var ngIfDirective = ['$animator', function($animator) { return { transclude: 'element', priority: 1000, terminal: true, restrict: 'A', compile: function (element, attr, transclude) { return function ($scope, $element, $attr) { var animate = $animator($scope, $attr); var childElement, childScope; $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { if (childElement) { animate.leave(childElement); childElement = undefined; } if (childScope) { childScope.$destroy(); childScope = undefined; } if (toBoolean(value)) { childScope = $scope.$new(); transclude(childScope, function (clone) { childElement = clone; animate.enter(clone, $element.parent(), $element); }); } }); } } } }]; /** * @ngdoc directive * @name ng.directive:ngInclude * @restrict ECA * * @description * Fetches, compiles and includes an external HTML fragment. * * Keep in mind that Same Origin Policy applies to included resources * (e.g. ngInclude won't work for cross-domain requests on all browsers and for * file:// access on some browsers). * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens just after the ngInclude contents change and a new DOM element is created and injected into the ngInclude container * leave - happens just after the ngInclude contents change and just before the former contents are removed from the DOM * * @scope * * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant, * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`. * @param {string=} onload Expression to evaluate when a new partial is loaded. * * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the content is loaded. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the expression evaluates to truthy value. * * @example <example animations="true"> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> <hr/> <div class="example-animate-container" ng-include="template.url" ng-animate="{enter: 'example-enter', leave: 'example-leave'}"></div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.templates = [ { name: 'template1.html', url: 'template1.html'} , { name: 'template2.html', url: 'template2.html'} ]; $scope.template = $scope.templates[0]; } </file> <file name="template1.html"> <div>Content of template1.html</div> </file> <file name="template2.html"> <div>Content of template2.html</div> </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .example-animate-container > * { display:block; padding:10px; } .example-enter { top:-50px; } .example-enter.example-enter-active { top:0; } .example-leave { top:0; } .example-leave.example-leave-active { top:50px; } </file> <file name="scenario.js"> it('should load template1.html', function() { expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template1.html/); }); it('should load template2.html', function() { select('template').option('1'); expect(element('.doc-example-live [ng-include]').text()). toMatch(/Content of template2.html/); }); it('should change to blank', function() { select('template').option(''); expect(element('.doc-example-live [ng-include]').text()).toEqual(''); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentRequested * @eventOf ng.directive:ngInclude * @eventType emit on the scope ngInclude was declared in * @description * Emitted every time the ngInclude content is requested. */ /** * @ngdoc event * @name ng.directive:ngInclude#$includeContentLoaded * @eventOf ng.directive:ngInclude * @eventType emit on the current ngInclude scope * @description * Emitted every time the ngInclude content is reloaded. */ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator', function($http, $templateCache, $anchorScroll, $compile, $animator) { return { restrict: 'ECA', terminal: true, compile: function(element, attr) { var srcExp = attr.ngInclude || attr.src, onloadExp = attr.onload || '', autoScrollExp = attr.autoscroll; return function(scope, element, attr) { var animate = $animator(scope, attr); var changeCounter = 0, childScope; var clearContent = function() { if (childScope) { childScope.$destroy(); childScope = null; } animate.leave(element.contents(), element); }; scope.$watch(srcExp, function ngIncludeWatchAction(src) { var thisChangeId = ++changeCounter; if (src) { $http.get(src, {cache: $templateCache}).success(function(response) { if (thisChangeId !== changeCounter) return; if (childScope) childScope.$destroy(); childScope = scope.$new(); animate.leave(element.contents(), element); var contents = jqLite('<div/>').html(response).contents(); animate.enter(contents, element); $compile(contents)(childScope); if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } childScope.$emit('$includeContentLoaded'); scope.$eval(onloadExp); }).error(function() { if (thisChangeId === changeCounter) clearContent(); }); scope.$emit('$includeContentRequested'); } else { clearContent(); } }); }; } }; }]; /** * @ngdoc directive * @name ng.directive:ngInit * * @description * The `ngInit` directive specifies initialization tasks to be executed * before the template enters execution mode during bootstrap. * * @element ANY * @param {expression} ngInit {@link guide/expression Expression} to eval. * * @example <doc:example> <doc:source> <div ng-init="greeting='Hello'; person='World'"> {{greeting}} {{person}}! </div> </doc:source> <doc:scenario> it('should check greeting', function() { expect(binding('greeting')).toBe('Hello'); expect(binding('person')).toBe('World'); }); </doc:scenario> </doc:example> */ var ngInitDirective = ngDirective({ compile: function() { return { pre: function(scope, element, attrs) { scope.$eval(attrs.ngInit); } } } }); /** * @ngdoc directive * @name ng.directive:ngNonBindable * @priority 1000 * * @description * Sometimes it is necessary to write code which looks like bindings but which should be left alone * by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML. * * @element ANY * * @example * In this example there are two location where a simple binding (`{{}}`) is present, but the one * wrapped in `ngNonBindable` is left alone. * * @example <doc:example> <doc:source> <div>Normal: {{1 + 2}}</div> <div ng-non-bindable>Ignored: {{1 + 2}}</div> </doc:source> <doc:scenario> it('should check ng-non-bindable', function() { expect(using('.doc-example-live').binding('1 + 2')).toBe('3'); expect(using('.doc-example-live').element('div:last').text()). toMatch(/1 \+ 2/); }); </doc:scenario> </doc:example> */ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); /** * @ngdoc directive * @name ng.directive:ngPluralize * @restrict EA * * @description * # Overview * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js and the rules can be overridden * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} and the strings to be displayed. * * # Plural categories and explicit number rules * There are two * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html * plural categories} in Angular's default en-US locale: "one" and "other". * * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. You will see the use of plural categories * and explicit number rules throughout later parts of this documentation. * * # Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression * Angular expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object so that Angular * can interpret it correctly. * * The following example shows how to configure ngPluralize: * * <pre> * <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', * 'one': '1 person is viewing.', * 'other': '{} people are viewing.'}"> * </ng-pluralize> *</pre> * * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not * specify this rule, 0 would be matched to the "other" category and "0 people are viewing" * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for * other numbers, for example 12, so that instead of showing "12 people are viewing", you can * show "a dozen people are viewing". * * You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted * into pluralized strings. In the previous example, Angular will replace `{}` with * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder * for <span ng-non-bindable>{{numberExpression}}</span>. * * # Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". * The offset attribute allows you to offset a number by any desired value. * Let's take a look at an example: * * <pre> * <ng-pluralize count="personCount" offset=2 * when="{'0': 'Nobody is viewing.', * '1': '{{person1}} is viewing.', * '2': '{{person1}} and {{person2}} are viewing.', * 'one': '{{person1}}, {{person2}} and one other person are viewing.', * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> * </ng-pluralize> * </pre> * * Notice that we are still using two plural categories(one, other), but we added * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing" * is shown. * * Note that when you specify offsets, you must provide explicit number rules for * numbers from 0 up to and including the offset. If you use an offset of 3, for example, * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for * plural categories "one" and "other". * * @param {string|expression} count The variable to be bounded to. * @param {string} when The mapping between plural category to its corresponding strings. * @param {number=} offset Offset to deduct from the total number. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.person1 = 'Igor'; $scope.person2 = 'Misko'; $scope.personCount = 1; } </script> <div ng-controller="Ctrl"> Person 1:<input type="text" ng-model="person1" value="Igor" /><br/> Person 2:<input type="text" ng-model="person2" value="Misko" /><br/> Number of People:<input type="text" ng-model="personCount" value="1" /><br/> <!--- Example with simple pluralization rules for en locale ---> Without Offset: <ng-pluralize count="personCount" when="{'0': 'Nobody is viewing.', 'one': '1 person is viewing.', 'other': '{} people are viewing.'}"> </ng-pluralize><br> <!--- Example with offset ---> With Offset(2): <ng-pluralize count="personCount" offset=2 when="{'0': 'Nobody is viewing.', '1': '{{person1}} is viewing.', '2': '{{person1}} and {{person2}} are viewing.', 'one': '{{person1}}, {{person2}} and one other person are viewing.', 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}"> </ng-pluralize> </div> </doc:source> <doc:scenario> it('should show correct pluralized string', function() { expect(element('.doc-example-live ng-pluralize:first').text()). toBe('1 person is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor is viewing.'); using('.doc-example-live').input('personCount').enter('0'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('Nobody is viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Nobody is viewing.'); using('.doc-example-live').input('personCount').enter('2'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('2 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor and Misko are viewing.'); using('.doc-example-live').input('personCount').enter('3'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('3 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and one other person are viewing.'); using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:first').text()). toBe('4 people are viewing.'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); }); it('should show data-binded names', function() { using('.doc-example-live').input('personCount').enter('4'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Igor, Misko and 2 other people are viewing.'); using('.doc-example-live').input('person1').enter('Di'); using('.doc-example-live').input('person2').enter('Vojta'); expect(element('.doc-example-live ng-pluralize:last').text()). toBe('Di, Vojta and 2 other people are viewing.'); }); </doc:scenario> </doc:example> */ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { var BRACE = /{}/g; return { restrict: 'EA', link: function(scope, element, attr) { var numberExp = attr.count, whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs offset = attr.offset || 0, whens = scope.$eval(whenExp), whensExpFns = {}, startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(); forEach(whens, function(expression, key) { whensExpFns[key] = $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' + offset + endSymbol)); }); scope.$watch(function ngPluralizeWatch() { var value = parseFloat(scope.$eval(numberExp)); if (!isNaN(value)) { //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise, //check it against pluralization rules in $locale service if (!(value in whens)) value = $locale.pluralCat(value - offset); return whensExpFns[value](scope, element, true); } else { return ''; } }, function ngPluralizeWatchAction(newVal) { element.text(newVal); }); } }; }]; /** * @ngdoc directive * @name ng.directive:ngRepeat * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template * instance gets its own scope, where the given loop variable is set to the current collection item, * and `$index` is set to the item index or key. * * Special properties are exposed on the local scope of each template instance, including: * * * `$index` – `{number}` – iterator offset of the repeated element (0..length-1) * * `$first` – `{boolean}` – true if the repeated element is first in the iterator. * * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator. * * `$last` – `{boolean}` – true if the repeated element is last in the iterator. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**, * **leave** and **move** effects. * * @animations * enter - when a new item is added to the list or when an item is revealed after a filter * leave - when an item is removed from the list or when an item is filtered out * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered * * @element ANY * @scope * @priority 1000 * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These * formats are currently supported: * * * `variable in expression` – where variable is the user defined loop variable and `expression` * is a scope expression giving the collection to enumerate. * * For example: `track in cd.tracks`. * * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers, * and `expression` is the scope expression giving the collection to enumerate. * * For example: `(name, age) in {'adam':10, 'amalie':12}`. * * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function * which can be used to associate the objects in the collection with the DOM elements. If no tractking function * is specified the ng-repeat associates elements by identity in the collection. It is an error to have * more then one tractking function to resolve to the same key. (This would mean that two distinct objects are * mapped to the same DOM element, which is not possible.) * * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements * will be associated by item identity in the array. * * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements * with the corresponding item in the array by identity. Moving the same object in array would move the DOM * element in the same way ian the DOM. * * For example: `item in items track by item.id` Is a typical pattern when the items come from the database. In this * case the object identity does not matter. Two objects are considered equivalent as long as their `id` * property is same. * * @example * This example initializes the scope to a list of names and * then uses `ngRepeat` to display every person: <example animations="true"> <file name="index.html"> <div ng-init="friends = [ {name:'John', age:25, gender:'boy'}, {name:'Jessie', age:30, gender:'girl'}, {name:'Johanna', age:28, gender:'girl'}, {name:'Joy', age:15, gender:'girl'}, {name:'Mary', age:28, gender:'girl'}, {name:'Peter', age:95, gender:'boy'}, {name:'Sebastian', age:50, gender:'boy'}, {name:'Erika', age:27, gender:'girl'}, {name:'Patrick', age:40, gender:'boy'}, {name:'Samantha', age:60, gender:'girl'} ]"> I have {{friends.length}} friends. They are: <input type="search" ng-model="q" placeholder="filter friends..." /> <ul> <li ng-repeat="friend in friends | filter:q" ng-animate="{enter: 'example-repeat-enter', leave: 'example-repeat-leave', move: 'example-repeat-move'}"> [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old. </li> </ul> </div> </file> <file name="animations.css"> .example-repeat-enter, .example-repeat-leave, .example-repeat-move { -webkit-transition:all linear 0.5s; -moz-transition:all linear 0.5s; -ms-transition:all linear 0.5s; -o-transition:all linear 0.5s; transition:all linear 0.5s; } .example-repeat-enter { line-height:0; opacity:0; } .example-repeat-enter.example-repeat-enter-active { line-height:20px; opacity:1; } .example-repeat-leave { opacity:1; line-height:20px; } .example-repeat-leave.example-repeat-leave-active { opacity:0; line-height:0; } .example-repeat-move { } .example-repeat-move.example-repeat-move-active { } </file> <file name="scenario.js"> it('should render initial data set', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(10); expect(r.row(0)).toEqual(["1","John","25"]); expect(r.row(1)).toEqual(["2","Jessie","30"]); expect(r.row(9)).toEqual(["10","Samantha","60"]); expect(binding('friends.length')).toBe("10"); }); it('should update repeater when filter predicate changes', function() { var r = using('.doc-example-live').repeater('ul li'); expect(r.count()).toBe(10); input('q').enter('ma'); expect(r.count()).toBe(2); expect(r.row(0)).toEqual(["1","Mary","28"]); expect(r.row(1)).toEqual(["2","Samantha","60"]); }); </file> </example> */ var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) { var NG_REMOVED = '$$NG_REMOVED'; return { transclude: 'element', priority: 1000, terminal: true, compile: function(element, attr, linker) { return function($scope, $element, $attr){ var animate = $animator($scope, $attr); var expression = $attr.ngRepeat; var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/), trackByExp, trackByExpGetter, trackByIdFn, lhs, rhs, valueIdentifier, keyIdentifier, hashFnLocals = {$id: hashKey}; if (!match) { throw Error("Expected ngRepeat in form of '_item_ in _collection_[ track by _id_]' but got '" + expression + "'."); } lhs = match[1]; rhs = match[2]; trackByExp = match[4]; if (trackByExp) { trackByExpGetter = $parse(trackByExp); trackByIdFn = function(key, value, index) { // assign key, value, and $index to the locals so that they can be used in hash functions if (keyIdentifier) hashFnLocals[keyIdentifier] = key; hashFnLocals[valueIdentifier] = value; hashFnLocals.$index = index; return trackByExpGetter($scope, hashFnLocals); }; } else { trackByIdFn = function(key, value) { return hashKey(value); } } match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); if (!match) { throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" + lhs + "'."); } valueIdentifier = match[3] || match[1]; keyIdentifier = match[2]; // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is objects with following properties. // - scope: bound scope // - element: previous element. // - index: position var lastBlockMap = {}; //watch props $scope.$watchCollection(rhs, function ngRepeatAction(collection){ var index, length, cursor = $element, // current position of the node nextCursor, // Same as lastBlockMap but it has the current state. It will become the // lastBlockMap on the next iteration. nextBlockMap = {}, arrayLength, childScope, key, value, // key/value of iteration trackById, collectionKeys, block, // last object information {scope, element, id} nextBlockOrder = []; if (isArrayLike(collection)) { collectionKeys = collection; } else { // if object, extract keys, sort them and use to determine order of iteration over obj props collectionKeys = []; for (key in collection) { if (collection.hasOwnProperty(key) && key.charAt(0) != '$') { collectionKeys.push(key); } } collectionKeys.sort(); } arrayLength = collectionKeys.length; // locate existing items length = nextBlockOrder.length = collectionKeys.length; for(index = 0; index < length; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; trackById = trackByIdFn(key, value, index); if(lastBlockMap.hasOwnProperty(trackById)) { block = lastBlockMap[trackById] delete lastBlockMap[trackById]; nextBlockMap[trackById] = block; nextBlockOrder[index] = block; } else if (nextBlockMap.hasOwnProperty(trackById)) { // restore lastBlockMap forEach(nextBlockOrder, function(block) { if (block && block.element) lastBlockMap[block.id] = block; }); // This is a duplicate and we need to throw an error throw new Error('Duplicates in a repeater are not allowed. Repeater: ' + expression + ' key: ' + trackById); } else { // new never before seen block nextBlockOrder[index] = { id: trackById }; nextBlockMap[trackById] = false; } } // remove existing items for (key in lastBlockMap) { if (lastBlockMap.hasOwnProperty(key)) { block = lastBlockMap[key]; animate.leave(block.element); block.element[0][NG_REMOVED] = true; block.scope.$destroy(); } } // we are not using forEach for perf reasons (trying to avoid #call) for (index = 0, length = collectionKeys.length; index < length; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; block = nextBlockOrder[index]; if (block.element) { // if we have already seen this object, then we need to reuse the // associated scope/element childScope = block.scope; nextCursor = cursor[0]; do { nextCursor = nextCursor.nextSibling; } while(nextCursor && nextCursor[NG_REMOVED]); if (block.element[0] == nextCursor) { // do nothing cursor = block.element; } else { // existing item which got moved animate.move(block.element, null, cursor); cursor = block.element; } } else { // new item which we don't know about childScope = $scope.$new(); } childScope[valueIdentifier] = value; if (keyIdentifier) childScope[keyIdentifier] = key; childScope.$index = index; childScope.$first = (index === 0); childScope.$last = (index === (arrayLength - 1)); childScope.$middle = !(childScope.$first || childScope.$last); if (!block.element) { linker(childScope, function(clone) { animate.enter(clone, null, cursor); cursor = clone; block.scope = childScope; block.element = clone; nextBlockMap[block.id] = block; }); } } lastBlockMap = nextBlockMap; }); }; } }; }]; /** * @ngdoc directive * @name ng.directive:ngShow * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally based on **"truthy"** values evaluated within an {expression}. In other * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible** * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none). * With ngHide this is the reverse whereas true values cause the element itself to become * hidden. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show** * and **hide** effects. * * @animations * show - happens after the ngShow expression evaluates to a truthy value and the contents are set to visible * hide - happens before the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngShow If the {@link guide/expression expression} is truthy * then the element is shown or hidden respectively. * * @example <example animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <span class="check-element" ng-show="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-up"></span> I show up when your checkbox is checked. </span> </div> <div> Hide: <span class="check-element" ng-hide="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-down"></span> I hide when your checkbox is checked. </span> </div> </file> <file name="animations.css"> .example-show, .example-hide { -webkit-transition:all linear 0.5s; -moz-transition:all linear 0.5s; -ms-transition:all linear 0.5s; -o-transition:all linear 0.5s; transition:all linear 0.5s; } .example-show { line-height:0; opacity:0; padding:0 10px; } .example-show-active.example-show-active { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide-active.example-hide-active { line-height:0; opacity:0; padding:0 10px; } .check-element { padding:10px; border:1px solid black; background:white; } </file> <file name="scenario.js"> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live span:first:hidden').count()).toEqual(1); expect(element('.doc-example-live span:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live span:first:visible').count()).toEqual(1); expect(element('.doc-example-live span:last:hidden').count()).toEqual(1); }); </file> </example> */ //TODO(misko): refactor to remove element from the DOM var ngShowDirective = ['$animator', function($animator) { return function(scope, element, attr) { var animate = $animator(scope, attr); scope.$watch(attr.ngShow, function ngShowWatchAction(value){ animate[toBoolean(value) ? 'show' : 'hide'](element); }); }; }]; /** * @ngdoc directive * @name ng.directive:ngHide * * @description * The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML) * conditionally based on **"truthy"** values evaluated within an {expression}. In other * words, if the expression assigned to **ngShow evaluates to a true value** then **the element is set to visible** * (via `display:block` in css) and **if false** then **the element is set to hidden** (so display:none). * With ngHide this is the reverse whereas true values cause the element itself to become * hidden. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **show** * and **hide** effects. * * @animations * show - happens after the ngHide expression evaluates to a non truthy value and the contents are set to visible * hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden * * @element ANY * @param {expression} ngHide If the {@link guide/expression expression} is truthy then * the element is shown or hidden respectively. * * @example <example animations="true"> <file name="index.html"> Click me: <input type="checkbox" ng-model="checked"><br/> <div> Show: <span class="check-element" ng-show="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-up"></span> I show up when your checkbox is checked. </span> </div> <div> Hide: <span class="check-element" ng-hide="checked" ng-animate="{show: 'example-show', hide: 'example-hide'}"> <span class="icon-thumbs-down"></span> I hide when your checkbox is checked. </span> </div> </file> <file name="animations.css"> .example-show, .example-hide { -webkit-transition:all linear 0.5s; -moz-transition:all linear 0.5s; -ms-transition:all linear 0.5s; -o-transition:all linear 0.5s; transition:all linear 0.5s; } .example-show { line-height:0; opacity:0; padding:0 10px; } .example-show.example-show-active { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide { line-height:20px; opacity:1; padding:10px; border:1px solid black; background:white; } .example-hide.example-hide-active { line-height:0; opacity:0; padding:0 10px; } .check-element { padding:10px; border:1px solid black; background:white; } </file> <file name="scenario.js"> it('should check ng-show / ng-hide', function() { expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1); expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1); input('checked').check(); expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1); expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1); }); </file> </example> */ //TODO(misko): refactor to remove element from the DOM var ngHideDirective = ['$animator', function($animator) { return function(scope, element, attr) { var animate = $animator(scope, attr); scope.$watch(attr.ngHide, function ngHideWatchAction(value){ animate[toBoolean(value) ? 'hide' : 'show'](element); }); }; }]; /** * @ngdoc directive * @name ng.directive:ngStyle * * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * * @element ANY * @param {expression} ngStyle {@link guide/expression Expression} which evals to an * object whose keys are CSS style names and values are corresponding values for those CSS * keys. * * @example <example> <file name="index.html"> <input type="button" value="set" ng-click="myStyle={color:'red'}"> <input type="button" value="clear" ng-click="myStyle={}"> <br/> <span ng-style="myStyle">Sample Text</span> <pre>myStyle={{myStyle}}</pre> </file> <file name="style.css"> span { color: black; } </file> <file name="scenario.js"> it('should check ng-style', function() { expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); element('.doc-example-live :button[value=set]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)'); element('.doc-example-live :button[value=clear]').click(); expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)'); }); </file> </example> */ var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { forEach(oldStyles, function(val, style) { element.css(style, '');}); } if (newStyles) element.css(newStyles); }, true); }); /** * @ngdoc directive * @name ng.directive:ngSwitch * @restrict EA * * @description * The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression. * Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location * as specified in the template. * * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it * from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element * matches the value obtained from the evaluated expression. In other words, you define a container element * (where you place the directive), place an expression on the **on="..." attribute** * (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default * attribute is displayed. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens after the ngSwtich contents change and the matched child element is placed inside the container * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM * * @usage * <ANY ng-switch="expression"> * <ANY ng-switch-when="matchValue1">...</ANY> * <ANY ng-switch-when="matchValue2">...</ANY> * <ANY ng-switch-default>...</ANY> * </ANY> * * @scope * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>. * @paramDescription * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the * elements will be displayed. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * * @example <example animations="true"> <file name="index.html"> <div ng-controller="Ctrl"> <select ng-model="selection" ng-options="item for item in items"> </select> <tt>selection={{selection}}</tt> <hr/> <div class="example-animate-container" ng-switch on="selection" ng-animate="{enter: 'example-enter', leave: 'example-leave'}"> <div ng-switch-when="settings">Settings Div</div> <div ng-switch-when="home">Home Span</div> <div ng-switch-default>default</div> </div> </div> </file> <file name="script.js"> function Ctrl($scope) { $scope.items = ['settings', 'home', 'other']; $scope.selection = $scope.items[0]; } </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; position:absolute; top:0; left:0; right:0; bottom:0; } .example-animate-container > * { display:block; padding:10px; } .example-enter { top:-50px; } .example-enter.example-enter-active { top:0; } .example-leave { top:0; } .example-leave.example-leave-active { top:50px; } </file> <file name="scenario.js"> it('should start in settings', function() { expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/); }); it('should change to home', function() { select('selection').option('home'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/); }); it('should select default', function() { select('selection').option('other'); expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/); }); </file> </example> */ var ngSwitchDirective = ['$animator', function($animator) { return { restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module controller: ['$scope', function ngSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ngSwitchController) { var animate = $animator(scope, attr); var watchExpr = attr.ngSwitch || attr.on, selectedTranscludes, selectedElements, selectedScopes = []; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { for (var i= 0, ii=selectedScopes.length; i<ii; i++) { selectedScopes[i].$destroy(); animate.leave(selectedElements[i]); } selectedElements = []; selectedScopes = []; if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) { scope.$eval(attr.change); forEach(selectedTranscludes, function(selectedTransclude) { var selectedScope = scope.$new(); selectedScopes.push(selectedScope); selectedTransclude.transclude(selectedScope, function(caseElement) { var anchor = selectedTransclude.element; selectedElements.push(caseElement); animate.enter(caseElement, anchor.parent(), anchor); }); }); } }); } } }]; var ngSwitchWhenDirective = ngDirective({ transclude: 'element', priority: 500, require: '^ngSwitch', compile: function(element, attrs, transclude) { return function(scope, element, attr, ctrl) { ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: transclude, element: element }); }; } }); var ngSwitchDefaultDirective = ngDirective({ transclude: 'element', priority: 500, require: '^ngSwitch', compile: function(element, attrs, transclude) { return function(scope, element, attr, ctrl) { ctrl.cases['?'] = (ctrl.cases['?'] || []); ctrl.cases['?'].push({ transclude: transclude, element: element }); }; } }); /** * @ngdoc directive * @name ng.directive:ngTransclude * * @description * Insert the transcluded DOM here. * * @element ANY * * @example <doc:example module="transclude"> <doc:source> <script> function Ctrl($scope) { $scope.title = 'Lorem Ipsum'; $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; } angular.module('transclude', []) .directive('pane', function(){ return { restrict: 'E', transclude: true, scope: 'isolate', locals: { title:'bind' }, template: '<div style="border: 1px solid black;">' + '<div style="background-color: gray">{{title}}</div>' + '<div ng-transclude></div>' + '</div>' }; }); </script> <div ng-controller="Ctrl"> <input ng-model="title"><br> <textarea ng-model="text"></textarea> <br/> <pane title="{{title}}">{{text}}</pane> </div> </doc:source> <doc:scenario> it('should have transcluded', function() { input('title').enter('TITLE'); input('text').enter('TEXT'); expect(binding('title')).toEqual('TITLE'); expect(binding('text')).toEqual('TEXT'); }); </doc:scenario> </doc:example> * */ var ngTranscludeDirective = ngDirective({ controller: ['$transclude', '$element', function($transclude, $element) { $transclude(function(clone) { $element.append(clone); }); }] }); /** * @ngdoc directive * @name ng.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ng.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter** * and **leave** effects. * * @animations * enter - happens just after the ngView contents are changed (when the new view DOM element is inserted into the DOM) * leave - happens just after the current ngView contents change and just before the former contents are removed from the DOM * * @scope * @example <example module="ngView" animations="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view class="example-animate-container" ng-animate="{enter: 'example-enter', leave: 'example-leave'}"></div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .example-leave, .example-enter { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -moz-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -ms-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; -o-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; } .example-animate-container { position:relative; height:100px; } .example-animate-container > * { display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .example-enter { left:100%; } .example-enter.example-enter-active { left:0; } .example-leave { } .example-leave.example-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngView', [], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="scenario.js"> it('should load and compile correct template', function() { element('a:contains("Moby: Ch1")').click(); var content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element('a:contains("Scarlet")').click(); content = element('.doc-example-live [ng-view]').text(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ng.directive:ngView#$viewContentLoaded * @eventOf ng.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile', '$controller', '$animator', function($http, $templateCache, $route, $anchorScroll, $compile, $controller, $animator) { return { restrict: 'ECA', terminal: true, link: function(scope, element, attr) { var lastScope, onloadExp = attr.onload || '', animate = $animator(scope, attr); scope.$on('$routeChangeSuccess', update); update(); function destroyLastScope() { if (lastScope) { lastScope.$destroy(); lastScope = null; } } function clearContent() { animate.leave(element.contents(), element); destroyLastScope(); } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (template) { clearContent(); var enterElements = jqLite('<div></div>').html(template).contents(); animate.enter(enterElements, element); var link = $compile(enterElements), current = $route.current, controller; lastScope = current.scope = scope.$new(); if (current.controller) { locals.$scope = lastScope; controller = $controller(current.controller, locals); if (current.controllerAs) { lastScope[current.controllerAs] = controller; } element.children().data('$ngControllerController', controller); } link(lastScope); lastScope.$emit('$viewContentLoaded'); lastScope.$eval(onloadExp); // $anchorScroll might listen on event... $anchorScroll(); } else { clearContent(); } } } }; }]; /** * @ngdoc directive * @name ng.directive:script * * @description * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the * template can be used by `ngInclude`, `ngView` or directive templates. * * @restrict E * @param {'text/ng-template'} type must be set to `'text/ng-template'` * * @example <doc:example> <doc:source> <script type="text/ng-template" id="/tpl.html"> Content of the template. </script> <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a> <div id="tpl-content" ng-include src="currentTpl"></div> </doc:source> <doc:scenario> it('should load template defined inside script tag', function() { element('#tpl-link').click(); expect(element('#tpl-content').text()).toMatch(/Content of the template/); }); </doc:scenario> </doc:example> */ var scriptDirective = ['$templateCache', function($templateCache) { return { restrict: 'E', terminal: true, compile: function(element, attr) { if (attr.type == 'text/ng-template') { var templateUrl = attr.id, // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent text = element[0].text; $templateCache.put(templateUrl, text); } } }; }]; /** * @ngdoc directive * @name ng.directive:select * @restrict E * * @description * HTML `SELECT` element with angular data-binding. * * # `ngOptions` * * Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>` * elements for a `<select>` element using an array or an object obtained by evaluating the * `ngOptions` expression. *˝˝ * When an item in the select menu is select, the value of array element or object property * represented by the selected option will be bound to the model identified by the `ngModel` * directive of the parent select element. * * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can * be nested into the `<select>` element. This element will then represent `null` or "not selected" * option. See example below for demonstration. * * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead * of {@link ng.directive:ngRepeat ngRepeat} when you want the * `select` model to be bound to a non-string value. This is because an option element can currently * be bound to string values only. * * @param {string} ngModel Assignable angular expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required The control is considered valid only if value is entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of * `required` when you want to data-bind to the `required` attribute. * @param {comprehension_expression=} ngOptions in one of the following forms: * * * for array data sources: * * `label` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`for`** `value` **`in`** `array` * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr` * * for object data sources: * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object` * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object` * * `select` **`as`** `label` **`group by`** `group` * **`for` `(`**`key`**`,`** `value`**`) in`** `object` * * Where: * * * `array` / `object`: an expression which evaluates to an array / object to iterate over. * * `value`: local variable which will refer to each item in the `array` or each property value * of `object` during iteration. * * `key`: local variable which will refer to a property name in `object` during iteration. * * `label`: The result of this expression will be the label for `<option>` element. The * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`). * * `select`: The result of this expression will be bound to the model of the parent `<select>` * element. If not specified, `select` expression will default to `value`. * * `group`: The result of this expression will be used to group options using the `<optgroup>` * DOM element. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be * used to identify the objects in the array. The `trackexpr` will most likely refer to the * `value` variable (e.g. `value.propertyName`). * * @example <doc:example> <doc:source> <script> function MyCntrl($scope) { $scope.colors = [ {name:'black', shade:'dark'}, {name:'white', shade:'light'}, {name:'red', shade:'dark'}, {name:'blue', shade:'dark'}, {name:'yellow', shade:'light'} ]; $scope.color = $scope.colors[2]; // red } </script> <div ng-controller="MyCntrl"> <ul> <li ng-repeat="color in colors"> Name: <input ng-model="color.name"> [<a href ng-click="colors.splice($index, 1)">X</a>] </li> <li> [<a href ng-click="colors.push({})">add</a>] </li> </ul> <hr/> Color (null not allowed): <select ng-model="color" ng-options="c.name for c in colors"></select><br> Color (null allowed): <span class="nullable"> <select ng-model="color" ng-options="c.name for c in colors"> <option value="">-- chose color --</option> </select> </span><br/> Color grouped by shade: <select ng-model="color" ng-options="c.name group by c.shade for c in colors"> </select><br/> Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br> <hr/> Currently selected: {{ {selected_color:color} }} <div style="border:solid 1px black; height:20px" ng-style="{'background-color':color.name}"> </div> </div> </doc:source> <doc:scenario> it('should check ng-options', function() { expect(binding('{selected_color:color}')).toMatch('red'); select('color').option('0'); expect(binding('{selected_color:color}')).toMatch('black'); using('.nullable').select('color').option(''); expect(binding('{selected_color:color}')).toMatch('null'); }); </doc:scenario> </doc:example> */ var ngOptionsDirective = valueFn({ terminal: true }); var selectDirective = ['$compile', '$parse', function($compile, $parse) { //0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000007777000000000000000000088888 var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/, nullModelCtrl = {$setViewValue: noop}; return { restrict: 'E', require: ['select', '?ngModel'], controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) { var self = this, optionsMap = {}, ngModelCtrl = nullModelCtrl, nullOption, unknownOption; self.databound = $attrs.ngModel; self.init = function(ngModelCtrl_, nullOption_, unknownOption_) { ngModelCtrl = ngModelCtrl_; nullOption = nullOption_; unknownOption = unknownOption_; } self.addOption = function(value) { optionsMap[value] = true; if (ngModelCtrl.$viewValue == value) { $element.val(value); if (unknownOption.parent()) unknownOption.remove(); } }; self.removeOption = function(value) { if (this.hasOption(value)) { delete optionsMap[value]; if (ngModelCtrl.$viewValue == value) { this.renderUnknownOption(value); } } }; self.renderUnknownOption = function(val) { var unknownVal = '? ' + hashKey(val) + ' ?'; unknownOption.val(unknownVal); $element.prepend(unknownOption); $element.val(unknownVal); unknownOption.prop('selected', true); // needed for IE } self.hasOption = function(value) { return optionsMap.hasOwnProperty(value); } $scope.$on('$destroy', function() { // disable unknown option so that we don't do work when the whole select is being destroyed self.renderUnknownOption = noop; }); }], link: function(scope, element, attr, ctrls) { // if ngModel is not defined, we don't need to do anything if (!ctrls[1]) return; var selectCtrl = ctrls[0], ngModelCtrl = ctrls[1], multiple = attr.multiple, optionsExp = attr.ngOptions, nullOption = false, // if false, user will not be able to select it (used by ngOptions) emptyOption, // we can't just jqLite('<option>') since jqLite is not smart enough // to create it in <select> and IE barfs otherwise. optionTemplate = jqLite(document.createElement('option')), optGroupTemplate =jqLite(document.createElement('optgroup')), unknownOption = optionTemplate.clone(); // find "null" option for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) { if (children[i].value == '') { emptyOption = nullOption = children.eq(i); break; } } selectCtrl.init(ngModelCtrl, nullOption, unknownOption); // required validator if (multiple && (attr.required || attr.ngRequired)) { var requiredValidator = function(value) { ngModelCtrl.$setValidity('required', !attr.required || (value && value.length)); return value; }; ngModelCtrl.$parsers.push(requiredValidator); ngModelCtrl.$formatters.unshift(requiredValidator); attr.$observe('required', function() { requiredValidator(ngModelCtrl.$viewValue); }); } if (optionsExp) Options(scope, element, ngModelCtrl); else if (multiple) Multiple(scope, element, ngModelCtrl); else Single(scope, element, ngModelCtrl, selectCtrl); //////////////////////////// function Single(scope, selectElement, ngModelCtrl, selectCtrl) { ngModelCtrl.$render = function() { var viewValue = ngModelCtrl.$viewValue; if (selectCtrl.hasOption(viewValue)) { if (unknownOption.parent()) unknownOption.remove(); selectElement.val(viewValue); if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy } else { if (isUndefined(viewValue) && emptyOption) { selectElement.val(''); } else { selectCtrl.renderUnknownOption(viewValue); } } }; selectElement.bind('change', function() { scope.$apply(function() { if (unknownOption.parent()) unknownOption.remove(); ngModelCtrl.$setViewValue(selectElement.val()); }); }); } function Multiple(scope, selectElement, ctrl) { var lastView; ctrl.$render = function() { var items = new HashMap(ctrl.$viewValue); forEach(selectElement.find('option'), function(option) { option.selected = isDefined(items.get(option.value)); }); }; // we have to do it on each watch since ngModel watches reference, but // we need to work of an array, so we need to see if anything was inserted/removed scope.$watch(function selectMultipleWatch() { if (!equals(lastView, ctrl.$viewValue)) { lastView = copy(ctrl.$viewValue); ctrl.$render(); } }); selectElement.bind('change', function() { scope.$apply(function() { var array = []; forEach(selectElement.find('option'), function(option) { if (option.selected) { array.push(option.value); } }); ctrl.$setViewValue(array); }); }); } function Options(scope, selectElement, ctrl) { var match; if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) { throw Error( "Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_ (track by _expr_)?'" + " but got '" + optionsExp + "'."); } var displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]), track = match[8], trackFn = track ? $parse(match[8]) : null, // This is an array of array of existing option groups in DOM. We try to reuse these if possible // optionGroupsCache[0] is the options with no option group // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element optionGroupsCache = [[{element: selectElement, label:''}]]; if (nullOption) { // compile the element since there might be bindings in it $compile(nullOption)(scope); // remove the class, which is added automatically because we recompile the element and it // becomes the compilation root nullOption.removeClass('ng-scope'); // we need to remove it before calling selectElement.html('') because otherwise IE will // remove the label from the element. wtf? nullOption.remove(); } // clear contents, we'll add what's needed based on the model selectElement.html(''); selectElement.bind('change', function() { scope.$apply(function() { var optionGroup, collection = valuesFn(scope) || [], locals = {}, key, value, optionElement, index, groupIndex, length, groupLength; if (multiple) { value = []; for (groupIndex = 0, groupLength = optionGroupsCache.length; groupIndex < groupLength; groupIndex++) { // list of options for that group. (first item has the parent) optionGroup = optionGroupsCache[groupIndex]; for(index = 1, length = optionGroup.length; index < length; index++) { if ((optionElement = optionGroup[index].element)[0].selected) { key = optionElement.val(); if (keyName) locals[keyName] = key; if (trackFn) { for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) { locals[valueName] = collection[trackIndex]; if (trackFn(scope, locals) == key) break; } } else { locals[valueName] = collection[key]; } value.push(valueFn(scope, locals)); } } } } else { key = selectElement.val(); if (key == '?') { value = undefined; } else if (key == ''){ value = null; } else { if (trackFn) { for (var trackIndex = 0; trackIndex < collection.length; trackIndex++) { locals[valueName] = collection[trackIndex]; if (trackFn(scope, locals) == key) { value = valueFn(scope, locals); break; } } } else { locals[valueName] = collection[key]; if (keyName) locals[keyName] = key; value = valueFn(scope, locals); } } } ctrl.$setViewValue(value); }); }); ctrl.$render = render; // TODO(vojta): can't we optimize this ? scope.$watch(render); function render() { var optionGroups = {'':[]}, // Temporary location for the option groups before we render them optionGroupNames = [''], optionGroupName, optionGroup, option, existingParent, existingOptions, existingOption, modelValue = ctrl.$modelValue, values = valuesFn(scope) || [], keys = keyName ? sortedKeys(values) : values, groupLength, length, groupIndex, index, locals = {}, selected, selectedSet = false, // nothing is selected yet lastElement, element, label; if (multiple) { if (trackFn && isArray(modelValue)) { selectedSet = new HashMap([]); for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) { locals[valueName] = modelValue[trackIndex]; selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]); } } else { selectedSet = new HashMap(modelValue); } } // We now build up the list of options we need (we merge later) for (index = 0; length = keys.length, index < length; index++) { locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index]; optionGroupName = groupByFn(scope, locals) || ''; if (!(optionGroup = optionGroups[optionGroupName])) { optionGroup = optionGroups[optionGroupName] = []; optionGroupNames.push(optionGroupName); } if (multiple) { selected = selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals)) != undefined; } else { if (trackFn) { var modelCast = {}; modelCast[valueName] = modelValue; selected = trackFn(scope, modelCast) === trackFn(scope, locals); } else { selected = modelValue === valueFn(scope, locals); } selectedSet = selectedSet || selected; // see if at least one item is selected } label = displayFn(scope, locals); // what will be seen by the user label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values optionGroup.push({ id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index), // either the index into array or key from object label: label, selected: selected // determine if we should be selected }); } if (!multiple) { if (nullOption || modelValue === null) { // insert null option if we have a placeholder, or the model is null optionGroups[''].unshift({id:'', label:'', selected:!selectedSet}); } else if (!selectedSet) { // option could not be found, we have to insert the undefined item optionGroups[''].unshift({id:'?', label:'', selected:true}); } } // Now we need to update the list of DOM nodes to match the optionGroups we computed above for (groupIndex = 0, groupLength = optionGroupNames.length; groupIndex < groupLength; groupIndex++) { // current option group name or '' if no group optionGroupName = optionGroupNames[groupIndex]; // list of options for that group. (first item has the parent) optionGroup = optionGroups[optionGroupName]; if (optionGroupsCache.length <= groupIndex) { // we need to grow the optionGroups existingParent = { element: optGroupTemplate.clone().attr('label', optionGroupName), label: optionGroup.label }; existingOptions = [existingParent]; optionGroupsCache.push(existingOptions); selectElement.append(existingParent.element); } else { existingOptions = optionGroupsCache[groupIndex]; existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element // update the OPTGROUP label if not the same. if (existingParent.label != optionGroupName) { existingParent.element.attr('label', existingParent.label = optionGroupName); } } lastElement = null; // start at the beginning for(index = 0, length = optionGroup.length; index < length; index++) { option = optionGroup[index]; if ((existingOption = existingOptions[index+1])) { // reuse elements lastElement = existingOption.element; if (existingOption.label !== option.label) { lastElement.text(existingOption.label = option.label); } if (existingOption.id !== option.id) { lastElement.val(existingOption.id = option.id); } // lastElement.prop('selected') provided by jQuery has side-effects if (lastElement[0].selected !== option.selected) { lastElement.prop('selected', (existingOption.selected = option.selected)); } } else { // grow elements // if it's a null option if (option.id === '' && nullOption) { // put back the pre-compiled element element = nullOption; } else { // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but // in this version of jQuery on some browser the .text() returns a string // rather then the element. (element = optionTemplate.clone()) .val(option.id) .attr('selected', option.selected) .text(option.label); } existingOptions.push(existingOption = { element: element, label: option.label, id: option.id, selected: option.selected }); if (lastElement) { lastElement.after(element); } else { existingParent.element.append(element); } lastElement = element; } } // remove any excessive OPTIONs in a group index++; // increment since the existingOptions[0] is parent element not OPTION while(existingOptions.length > index) { existingOptions.pop().element.remove(); } } // remove any excessive OPTGROUPs from select while(optionGroupsCache.length > groupIndex) { optionGroupsCache.pop()[0].element.remove(); } } } } } }]; var optionDirective = ['$interpolate', function($interpolate) { var nullSelectCtrl = { addOption: noop, removeOption: noop }; return { restrict: 'E', priority: 100, compile: function(element, attr) { if (isUndefined(attr.value)) { var interpolateFn = $interpolate(element.text(), true); if (!interpolateFn) { attr.$set('value', element.text()); } } return function (scope, element, attr) { var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup if (selectCtrl && selectCtrl.databound) { // For some reason Opera defaults to true and if not overridden this messes up the repeater. // We don't want the view to drive the initialization of the model anyway. element.prop('selected', false); } else { selectCtrl = nullSelectCtrl; } if (interpolateFn) { scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { attr.$set('value', newVal); if (newVal !== oldVal) selectCtrl.removeOption(oldVal); selectCtrl.addOption(newVal); }); } else { selectCtrl.addOption(attr.value); } element.bind('$destroy', function() { selectCtrl.removeOption(attr.value); }); }; } } }]; var styleDirective = valueFn({ restrict: 'E', terminal: true }); /** * Setup file for the Scenario. * Must be first in the compilation/bootstrap list. */ // Public namespace angular.scenario = angular.scenario || {}; /** * Defines a new output format. * * @param {string} name the name of the new output format * @param {function()} fn function(context, runner) that generates the output */ angular.scenario.output = angular.scenario.output || function(name, fn) { angular.scenario.output[name] = fn; }; /** * Defines a new DSL statement. If your factory function returns a Future * it's returned, otherwise the result is assumed to be a map of functions * for chaining. Chained functions are subject to the same rules. * * Note: All functions on the chain are bound to the chain scope so values * set on "this" in your statement function are available in the chained * functions. * * @param {string} name The name of the statement * @param {function()} fn Factory function(), return a function for * the statement. */ angular.scenario.dsl = angular.scenario.dsl || function(name, fn) { angular.scenario.dsl[name] = function() { function executeStatement(statement, args) { var result = statement.apply(this, args); if (angular.isFunction(result) || result instanceof angular.scenario.Future) return result; var self = this; var chain = angular.extend({}, result); angular.forEach(chain, function(value, name) { if (angular.isFunction(value)) { chain[name] = function() { return executeStatement.call(self, value, arguments); }; } else { chain[name] = value; } }); return chain; } var statement = fn.apply(this, arguments); return function() { return executeStatement.call(this, statement, arguments); }; }; }; /** * Defines a new matcher for use with the expects() statement. The value * this.actual (like in Jasmine) is available in your matcher to compare * against. Your function should return a boolean. The future is automatically * created for you. * * @param {string} name The name of the matcher * @param {function()} fn The matching function(expected). */ angular.scenario.matcher = angular.scenario.matcher || function(name, fn) { angular.scenario.matcher[name] = function(expected) { var prefix = 'expect ' + this.future.name + ' '; if (this.inverse) { prefix += 'not '; } var self = this; this.addFuture(prefix + name + ' ' + angular.toJson(expected), function(done) { var error; self.actual = self.future.value; if ((self.inverse && fn.call(self, expected)) || (!self.inverse && !fn.call(self, expected))) { error = 'expected ' + angular.toJson(expected) + ' but was ' + angular.toJson(self.actual); } done(error); }); }; }; /** * Initialize the scenario runner and run ! * * Access global window and document object * Access $runner through closure * * @param {Object=} config Config options */ angular.scenario.setUpAndRun = function(config) { var href = window.location.href; var body = _jQuery(document.body); var output = []; var objModel = new angular.scenario.ObjectModel($runner); if (config && config.scenario_output) { output = config.scenario_output.split(','); } angular.forEach(angular.scenario.output, function(fn, name) { if (!output.length || indexOf(output,name) != -1) { var context = body.append('<div></div>').find('div:last'); context.attr('id', name); fn.call({}, context, $runner, objModel); } }); if (!/^http/.test(href) && !/^https/.test(href)) { body.append('<p id="system-error"></p>'); body.find('#system-error').text( 'Scenario runner must be run using http or https. The protocol ' + href.split(':')[0] + ':// is not supported.' ); return; } var appFrame = body.append('<div id="application"></div>').find('#application'); var application = new angular.scenario.Application(appFrame); $runner.on('RunnerEnd', function() { appFrame.css('display', 'none'); appFrame.find('iframe').attr('src', 'about:blank'); }); $runner.on('RunnerError', function(error) { if (window.console) { console.log(formatException(error)); } else { // Do something for IE alert(error); } }); $runner.run(application); }; /** * Iterates through list with iterator function that must call the * continueFunction to continue iterating. * * @param {Array} list list to iterate over * @param {function()} iterator Callback function(value, continueFunction) * @param {function()} done Callback function(error, result) called when * iteration finishes or an error occurs. */ function asyncForEach(list, iterator, done) { var i = 0; function loop(error, index) { if (index && index > i) { i = index; } if (error || i >= list.length) { done(error); } else { try { iterator(list[i++], loop); } catch (e) { done(e); } } } loop(); } /** * Formats an exception into a string with the stack trace, but limits * to a specific line length. * * @param {Object} error The exception to format, can be anything throwable * @param {Number=} [maxStackLines=5] max lines of the stack trace to include * default is 5. */ function formatException(error, maxStackLines) { maxStackLines = maxStackLines || 5; var message = error.toString(); if (error.stack) { var stack = error.stack.split('\n'); if (stack[0].indexOf(message) === -1) { maxStackLines++; stack.unshift(error.message); } message = stack.slice(0, maxStackLines).join('\n'); } return message; } /** * Returns a function that gets the file name and line number from a * location in the stack if available based on the call site. * * Note: this returns another function because accessing .stack is very * expensive in Chrome. * * @param {Number} offset Number of stack lines to skip */ function callerFile(offset) { var error = new Error(); return function() { var line = (error.stack || '').split('\n')[offset]; // Clean up the stack trace line if (line) { if (line.indexOf('@') !== -1) { // Firefox line = line.substring(line.indexOf('@')+1); } else { // Chrome line = line.substring(line.indexOf('(')+1).replace(')', ''); } } return line || ''; }; } /** * Don't use the jQuery trigger method since it works incorrectly. * * jQuery notifies listeners and then changes the state of a checkbox and * does not create a real browser event. A real click changes the state of * the checkbox and then notifies listeners. * * To work around this we instead use our own handler that fires a real event. */ (function(fn){ var parentTrigger = fn.trigger; fn.trigger = function(type) { if (/(click|change|keydown|blur|input|mousedown|mouseup)/.test(type)) { var processDefaults = []; this.each(function(index, node) { processDefaults.push(browserTrigger(node, type)); }); // this is not compatible with jQuery - we return an array of returned values, // so that scenario runner know whether JS code has preventDefault() of the event or not... return processDefaults; } return parentTrigger.apply(this, arguments); }; })(_jQuery.fn); /** * Finds all bindings with the substring match of name and returns an * array of their values. * * @param {string} bindExp The name to match * @return {Array.<string>} String of binding values */ _jQuery.fn.bindings = function(windowJquery, bindExp) { var result = [], match, bindSelector = '.ng-binding:visible'; if (angular.isString(bindExp)) { bindExp = bindExp.replace(/\s/g, ''); match = function (actualExp) { if (actualExp) { actualExp = actualExp.replace(/\s/g, ''); if (actualExp == bindExp) return true; if (actualExp.indexOf(bindExp) == 0) { return actualExp.charAt(bindExp.length) == '|'; } } } } else if (bindExp) { match = function(actualExp) { return actualExp && bindExp.exec(actualExp); } } else { match = function(actualExp) { return !!actualExp; }; } var selection = this.find(bindSelector); if (this.is(bindSelector)) { selection = selection.add(this); } function push(value) { if (value == undefined) { value = ''; } else if (typeof value != 'string') { value = angular.toJson(value); } result.push('' + value); } selection.each(function() { var element = windowJquery(this), binding; if (binding = element.data('$binding')) { if (typeof binding == 'string') { if (match(binding)) { push(element.scope().$eval(binding)); } } else { if (!angular.isArray(binding)) { binding = [binding]; } for(var fns, j=0, jj=binding.length; j<jj; j++) { fns = binding[j]; if (fns.parts) { fns = fns.parts; } else { fns = [fns]; } for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) { if(match((fn = fns[i]).exp)) { push(fn(scope = scope || element.scope())); } } } } } }); return result; }; (function() { var msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1], 10); function indexOf(array, obj) { if (array.indexOf) return array.indexOf(obj); for ( var i = 0; i < array.length; i++) { if (obj === array[i]) return i; } return -1; } /** * Triggers a browser event. Attempts to choose the right event if one is * not specified. * * @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement * @param {string} eventType Optional event type. * @param {Array.<string>=} keys Optional list of pressed keys * (valid values: 'alt', 'meta', 'shift', 'ctrl') * @param {number} x Optional x-coordinate for mouse/touch events. * @param {number} y Optional y-coordinate for mouse/touch events. */ window.browserTrigger = function browserTrigger(element, eventType, keys, x, y) { if (element && !element.nodeName) element = element[0]; if (!element) return; var inputType = (element.type) ? element.type.toLowerCase() : null, nodeName = element.nodeName.toLowerCase(); if (!eventType) { eventType = { 'text': 'change', 'textarea': 'change', 'hidden': 'change', 'password': 'change', 'button': 'click', 'submit': 'click', 'reset': 'click', 'image': 'click', 'checkbox': 'click', 'radio': 'click', 'select-one': 'change', 'select-multiple': 'change', '_default_': 'click' }[inputType || '_default_']; } if (nodeName == 'option') { element.parentNode.value = element.value; element = element.parentNode; eventType = 'change'; } keys = keys || []; function pressed(key) { return indexOf(keys, key) !== -1; } if (msie < 9) { if (inputType == 'radio' || inputType == 'checkbox') { element.checked = !element.checked; } // WTF!!! Error: Unspecified error. // Don't know why, but some elements when detached seem to be in inconsistent state and // calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error) // forcing the browser to compute the element position (by reading its CSS) // puts the element in consistent state. element.style.posLeft; // TODO(vojta): create event objects with pressed keys to get it working on IE<9 var ret = element.fireEvent('on' + eventType); if (inputType == 'submit') { while(element) { if (element.nodeName.toLowerCase() == 'form') { element.fireEvent('onsubmit'); break; } element = element.parentNode; } } return ret; } else { var evnt = document.createEvent('MouseEvents'), originalPreventDefault = evnt.preventDefault, appWindow = element.ownerDocument.defaultView, fakeProcessDefault = true, finalProcessDefault, angular = appWindow.angular || {}; // igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208 angular['ff-684208-preventDefault'] = false; evnt.preventDefault = function() { fakeProcessDefault = false; return originalPreventDefault.apply(evnt, arguments); }; x = x || 0; y = y || 0; evnt.initMouseEvent(eventType, true, true, window, 0, x, y, x, y, pressed('ctrl'), pressed('alt'), pressed('shift'), pressed('meta'), 0, element); element.dispatchEvent(evnt); finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault); delete angular['ff-684208-preventDefault']; return finalProcessDefault; } } }()); /** * Represents the application currently being tested and abstracts usage * of iframes or separate windows. * * @param {Object} context jQuery wrapper around HTML context. */ angular.scenario.Application = function(context) { this.context = context; context.append( '<h2>Current URL: <a href="about:blank">None</a></h2>' + '<div id="test-frames"></div>' ); }; /** * Gets the jQuery collection of frames. Don't use this directly because * frames may go stale. * * @private * @return {Object} jQuery collection */ angular.scenario.Application.prototype.getFrame_ = function() { return this.context.find('#test-frames iframe:last'); }; /** * Gets the window of the test runner frame. Always favor executeAction() * instead of this method since it prevents you from getting a stale window. * * @private * @return {Object} the window of the frame */ angular.scenario.Application.prototype.getWindow_ = function() { var contentWindow = this.getFrame_().prop('contentWindow'); if (!contentWindow) throw 'Frame window is not accessible.'; return contentWindow; }; /** * Changes the location of the frame. * * @param {string} url The URL. If it begins with a # then only the * hash of the page is changed. * @param {function()} loadFn function($window, $document) Called when frame loads. * @param {function()} errorFn function(error) Called if any error when loading. */ angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) { var self = this; var frame = self.getFrame_(); //TODO(esprehn): Refactor to use rethrow() errorFn = errorFn || function(e) { throw e; }; if (url === 'about:blank') { errorFn('Sandbox Error: Navigating to about:blank is not allowed.'); } else if (url.charAt(0) === '#') { url = frame.attr('src').split('#')[0] + url; frame.attr('src', url); self.executeAction(loadFn); } else { frame.remove(); self.context.find('#test-frames').append('<iframe>'); frame = self.getFrame_(); frame.load(function() { frame.unbind(); try { var $window = self.getWindow_(); if ($window.angular) { // Disable animations // TODO(i): this doesn't disable javascript animations // we don't need that for our tests, but it should be done $window.angular.resumeBootstrap([['$provide', function($provide) { $provide.decorator('$sniffer', function($delegate) { $delegate.transitions = false; $delegate.animations = false; return $delegate; }); }]]); } self.executeAction(loadFn); } catch (e) { errorFn(e); } }).attr('src', url); // for IE compatibility set the name *after* setting the frame url frame[0].contentWindow.name = "NG_DEFER_BOOTSTRAP!"; } self.context.find('> h2 a').attr('href', url).text(url); }; /** * Executes a function in the context of the tested application. Will wait * for all pending angular xhr requests before executing. * * @param {function()} action The callback to execute. function($window, $document) * $document is a jQuery wrapped document. */ angular.scenario.Application.prototype.executeAction = function(action) { var self = this; var $window = this.getWindow_(); if (!$window.document) { throw 'Sandbox Error: Application document not accessible.'; } if (!$window.angular) { return action.call(this, $window, _jQuery($window.document)); } angularInit($window.document, function(element) { var $injector = $window.angular.element(element).injector(); var $element = _jQuery(element); $element.injector = function() { return $injector; }; $injector.invoke(function($browser){ $browser.notifyWhenNoOutstandingRequests(function() { action.call(self, $window, $element); }); }); }); }; /** * The representation of define blocks. Don't used directly, instead use * define() in your tests. * * @param {string} descName Name of the block * @param {Object} parent describe or undefined if the root. */ angular.scenario.Describe = function(descName, parent) { this.only = parent && parent.only; this.beforeEachFns = []; this.afterEachFns = []; this.its = []; this.children = []; this.name = descName; this.parent = parent; this.id = angular.scenario.Describe.id++; /** * Calls all before functions. */ var beforeEachFns = this.beforeEachFns; this.setupBefore = function() { if (parent) parent.setupBefore.call(this); angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this); }; /** * Calls all after functions. */ var afterEachFns = this.afterEachFns; this.setupAfter = function() { angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this); if (parent) parent.setupAfter.call(this); }; }; // Shared Unique ID generator for every describe block angular.scenario.Describe.id = 0; // Shared Unique ID generator for every it (spec) angular.scenario.Describe.specId = 0; /** * Defines a block to execute before each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.beforeEach = function(body) { this.beforeEachFns.push(body); }; /** * Defines a block to execute after each it or nested describe. * * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.afterEach = function(body) { this.afterEachFns.push(body); }; /** * Creates a new describe block that's a child of this one. * * @param {string} name Name of the block. Appended to the parent block's name. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.describe = function(name, body) { var child = new angular.scenario.Describe(name, this); this.children.push(child); body.call(child); }; /** * Same as describe() but makes ddescribe blocks the only to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.ddescribe = function(name, body) { var child = new angular.scenario.Describe(name, this); child.only = true; this.children.push(child); body.call(child); }; /** * Use to disable a describe block. */ angular.scenario.Describe.prototype.xdescribe = angular.noop; /** * Defines a test. * * @param {string} name Name of the test. * @param {function()} vody Body of the block. */ angular.scenario.Describe.prototype.it = function(name, body) { this.its.push({ id: angular.scenario.Describe.specId++, definition: this, only: this.only, name: name, before: this.setupBefore, body: body, after: this.setupAfter }); }; /** * Same as it() but makes iit tests the only test to run. * * @param {string} name Name of the test. * @param {function()} body Body of the block. */ angular.scenario.Describe.prototype.iit = function(name, body) { this.it.apply(this, arguments); this.its[this.its.length-1].only = true; }; /** * Use to disable a test block. */ angular.scenario.Describe.prototype.xit = angular.noop; /** * Gets an array of functions representing all the tests (recursively). * that can be executed with SpecRunner's. * * @return {Array<Object>} Array of it blocks { * definition : Object // parent Describe * only: boolean * name: string * before: Function * body: Function * after: Function * } */ angular.scenario.Describe.prototype.getSpecs = function() { var specs = arguments[0] || []; angular.forEach(this.children, function(child) { child.getSpecs(specs); }); angular.forEach(this.its, function(it) { specs.push(it); }); var only = []; angular.forEach(specs, function(it) { if (it.only) { only.push(it); } }); return (only.length && only) || specs; }; /** * A future action in a spec. * * @param {string} name of the future action * @param {function()} future callback(error, result) * @param {function()} Optional. function that returns the file/line number. */ angular.scenario.Future = function(name, behavior, line) { this.name = name; this.behavior = behavior; this.fulfilled = false; this.value = undefined; this.parser = angular.identity; this.line = line || function() { return ''; }; }; /** * Executes the behavior of the closure. * * @param {function()} doneFn Callback function(error, result) */ angular.scenario.Future.prototype.execute = function(doneFn) { var self = this; this.behavior(function(error, result) { self.fulfilled = true; if (result) { try { result = self.parser(result); } catch(e) { error = e; } } self.value = error || result; doneFn(error, result); }); }; /** * Configures the future to convert it's final with a function fn(value) * * @param {function()} fn function(value) that returns the parsed value */ angular.scenario.Future.prototype.parsedWith = function(fn) { this.parser = fn; return this; }; /** * Configures the future to parse it's final value from JSON * into objects. */ angular.scenario.Future.prototype.fromJson = function() { return this.parsedWith(angular.fromJson); }; /** * Configures the future to convert it's final value from objects * into JSON. */ angular.scenario.Future.prototype.toJson = function() { return this.parsedWith(angular.toJson); }; /** * Maintains an object tree from the runner events. * * @param {Object} runner The scenario Runner instance to connect to. * * TODO(esprehn): Every output type creates one of these, but we probably * want one global shared instance. Need to handle events better too * so the HTML output doesn't need to do spec model.getSpec(spec.id) * silliness. * * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance */ angular.scenario.ObjectModel = function(runner) { var self = this; this.specMap = {}; this.listeners = []; this.value = { name: '', children: {} }; runner.on('SpecBegin', function(spec) { var block = self.value, definitions = []; angular.forEach(self.getDefinitionPath(spec), function(def) { if (!block.children[def.name]) { block.children[def.name] = { id: def.id, name: def.name, children: {}, specs: {} }; } block = block.children[def.name]; definitions.push(def.name); }); var it = self.specMap[spec.id] = block.specs[spec.name] = new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions); // forward the event self.emit('SpecBegin', it); }); runner.on('SpecError', function(spec, error) { var it = self.getSpec(spec.id); it.status = 'error'; it.error = error; // forward the event self.emit('SpecError', it, error); }); runner.on('SpecEnd', function(spec) { var it = self.getSpec(spec.id); complete(it); // forward the event self.emit('SpecEnd', it); }); runner.on('StepBegin', function(spec, step) { var it = self.getSpec(spec.id); var step = new angular.scenario.ObjectModel.Step(step.name); it.steps.push(step); // forward the event self.emit('StepBegin', it, step); }); runner.on('StepEnd', function(spec) { var it = self.getSpec(spec.id); var step = it.getLastStep(); if (step.name !== step.name) throw 'Events fired in the wrong order. Step names don\'t match.'; complete(step); // forward the event self.emit('StepEnd', it, step); }); runner.on('StepFailure', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('failure', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepFailure', it, modelStep, error); }); runner.on('StepError', function(spec, step, error) { var it = self.getSpec(spec.id), modelStep = it.getLastStep(); modelStep.setErrorStatus('error', error, step.line()); it.setStatusFromStep(modelStep); // forward the event self.emit('StepError', it, modelStep, error); }); runner.on('RunnerBegin', function() { self.emit('RunnerBegin'); }); runner.on('RunnerEnd', function() { self.emit('RunnerEnd'); }); function complete(item) { item.endTime = new Date().getTime(); item.duration = item.endTime - item.startTime; item.status = item.status || 'success'; } }; /** * Adds a listener for an event. * * @param {string} eventName Name of the event to add a handler for * @param {function()} listener Function that will be called when event is fired */ angular.scenario.ObjectModel.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.ObjectModel.prototype.emit = function(eventName) { var self = this, args = Array.prototype.slice.call(arguments, 1), eventName = eventName.toLowerCase(); if (this.listeners[eventName]) { angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); } }; /** * Computes the path of definition describe blocks that wrap around * this spec. * * @param spec Spec to compute the path for. * @return {Array<Describe>} The describe block path */ angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) { var path = []; var currentDefinition = spec.definition; while (currentDefinition && currentDefinition.name) { path.unshift(currentDefinition); currentDefinition = currentDefinition.parent; } return path; }; /** * Gets a spec by id. * * @param {string} The id of the spec to get the object for. * @return {Object} the Spec instance */ angular.scenario.ObjectModel.prototype.getSpec = function(id) { return this.specMap[id]; }; /** * A single it block. * * @param {string} id Id of the spec * @param {string} name Name of the spec * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec */ angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) { this.id = id; this.name = name; this.startTime = new Date().getTime(); this.steps = []; this.fullDefinitionName = (definitionNames || []).join(' '); }; /** * Adds a new step to the Spec. * * @param {string} step Name of the step (really name of the future) * @return {Object} the added step */ angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) { var step = new angular.scenario.ObjectModel.Step(name); this.steps.push(step); return step; }; /** * Gets the most recent step. * * @return {Object} the step */ angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() { return this.steps[this.steps.length-1]; }; /** * Set status of the Spec from given Step * * @param {angular.scenario.ObjectModel.Step} step */ angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) { if (!this.status || step.status == 'error') { this.status = step.status; this.error = step.error; this.line = step.line; } }; /** * A single step inside a Spec. * * @param {string} step Name of the step */ angular.scenario.ObjectModel.Step = function(name) { this.name = name; this.startTime = new Date().getTime(); }; /** * Helper method for setting all error status related properties * * @param {string} status * @param {string} error * @param {string} line */ angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) { this.status = status; this.error = error; this.line = line; }; /** * Runner for scenarios * * Has to be initialized before any test is loaded, * because it publishes the API into window (global space). */ angular.scenario.Runner = function($window) { this.listeners = []; this.$window = $window; this.rootDescribe = new angular.scenario.Describe(); this.currentDescribe = this.rootDescribe; this.api = { it: this.it, iit: this.iit, xit: angular.noop, describe: this.describe, ddescribe: this.ddescribe, xdescribe: angular.noop, beforeEach: this.beforeEach, afterEach: this.afterEach }; angular.forEach(this.api, angular.bind(this, function(fn, key) { this.$window[key] = angular.bind(this, fn); })); }; /** * Emits an event which notifies listeners and passes extra * arguments. * * @param {string} eventName Name of the event to fire. */ angular.scenario.Runner.prototype.emit = function(eventName) { var self = this; var args = Array.prototype.slice.call(arguments, 1); eventName = eventName.toLowerCase(); if (!this.listeners[eventName]) return; angular.forEach(this.listeners[eventName], function(listener) { listener.apply(self, args); }); }; /** * Adds a listener for an event. * * @param {string} eventName The name of the event to add a handler for * @param {string} listener The fn(...) that takes the extra arguments from emit() */ angular.scenario.Runner.prototype.on = function(eventName, listener) { eventName = eventName.toLowerCase(); this.listeners[eventName] = this.listeners[eventName] || []; this.listeners[eventName].push(listener); }; /** * Defines a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.describe = function(name, body) { var self = this; this.currentDescribe.describe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Same as describe, but makes ddescribe the only blocks to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.ddescribe = function(name, body) { var self = this; this.currentDescribe.ddescribe(name, function() { var parentDescribe = self.currentDescribe; self.currentDescribe = this; try { body.call(this); } finally { self.currentDescribe = parentDescribe; } }); }; /** * Defines a test in a describe block of a spec. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.it = function(name, body) { this.currentDescribe.it(name, body); }; /** * Same as it, but makes iit tests the only tests to run. * * @see Describe.js * * @param {string} name Name of the block * @param {function()} body Body of the block */ angular.scenario.Runner.prototype.iit = function(name, body) { this.currentDescribe.iit(name, body); }; /** * Defines a function to be called before each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.beforeEach = function(body) { this.currentDescribe.beforeEach(body); }; /** * Defines a function to be called after each it block in the describe * (and before all nested describes). * * @see Describe.js * * @param {function()} Callback to execute */ angular.scenario.Runner.prototype.afterEach = function(body) { this.currentDescribe.afterEach(body); }; /** * Creates a new spec runner. * * @private * @param {Object} scope parent scope */ angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) { var child = scope.$new(); var Cls = angular.scenario.SpecRunner; // Export all the methods to child scope manually as now we don't mess controllers with scopes // TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current for (var name in Cls.prototype) child[name] = angular.bind(child, Cls.prototype[name]); Cls.call(child); return child; }; /** * Runs all the loaded tests with the specified runner class on the * provided application. * * @param {angular.scenario.Application} application App to remote control. */ angular.scenario.Runner.prototype.run = function(application) { var self = this; var $root = angular.injector(['ng']).get('$rootScope'); angular.extend($root, this); angular.forEach(angular.scenario.Runner.prototype, function(fn, name) { $root[name] = angular.bind(self, fn); }); $root.application = application; $root.emit('RunnerBegin'); asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) { var dslCache = {}; var runner = self.createSpecRunner_($root); angular.forEach(angular.scenario.dsl, function(fn, key) { dslCache[key] = fn.call($root); }); angular.forEach(angular.scenario.dsl, function(fn, key) { self.$window[key] = function() { var line = callerFile(3); var scope = runner.$new(); // Make the dsl accessible on the current chain scope.dsl = {}; angular.forEach(dslCache, function(fn, key) { scope.dsl[key] = function() { return dslCache[key].apply(scope, arguments); }; }); // Make these methods work on the current chain scope.addFuture = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFuture.apply(scope, arguments); }; scope.addFutureAction = function() { Array.prototype.push.call(arguments, line); return angular.scenario.SpecRunner. prototype.addFutureAction.apply(scope, arguments); }; return scope.dsl[key].apply(scope, arguments); }; }); runner.run(spec, function() { runner.$destroy(); specDone.apply(this, arguments); }); }, function(error) { if (error) { self.emit('RunnerError', error); } self.emit('RunnerEnd'); }); }; /** * This class is the "this" of the it/beforeEach/afterEach method. * Responsibilities: * - "this" for it/beforeEach/afterEach * - keep state for single it/beforeEach/afterEach execution * - keep track of all of the futures to execute * - run single spec (execute each future) */ angular.scenario.SpecRunner = function() { this.futures = []; this.afterIndex = 0; }; /** * Executes a spec which is an it block with associated before/after functions * based on the describe nesting. * * @param {Object} spec A spec object * @param {function()} specDone function that is called when the spec finshes. Function(error, index) */ angular.scenario.SpecRunner.prototype.run = function(spec, specDone) { var self = this; this.spec = spec; this.emit('SpecBegin', spec); try { spec.before.call(this); spec.body.call(this); this.afterIndex = this.futures.length; spec.after.call(this); } catch (e) { this.emit('SpecError', spec, e); this.emit('SpecEnd', spec); specDone(); return; } var handleError = function(error, done) { if (self.error) { return done(); } self.error = true; done(null, self.afterIndex); }; asyncForEach( this.futures, function(future, futureDone) { self.step = future; self.emit('StepBegin', spec, future); try { future.execute(function(error) { if (error) { self.emit('StepFailure', spec, future, error); self.emit('StepEnd', spec, future); return handleError(error, futureDone); } self.emit('StepEnd', spec, future); self.$window.setTimeout(function() { futureDone(); }, 0); }); } catch (e) { self.emit('StepError', spec, future, e); self.emit('StepEnd', spec, future); handleError(e, futureDone); } }, function(e) { if (e) { self.emit('SpecError', spec, e); } self.emit('SpecEnd', spec); // Call done in a timeout so exceptions don't recursively // call this function self.$window.setTimeout(function() { specDone(); }, 0); } ); }; /** * Adds a new future action. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) { var future = new angular.scenario.Future(name, angular.bind(this, behavior), line); this.futures.push(future); return future; }; /** * Adds a new future action to be executed on the application window. * * Note: Do not pass line manually. It happens automatically. * * @param {string} name Name of the future * @param {function()} behavior Behavior of the future * @param {function()} line fn() that returns file/line number */ angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) { var self = this; var NG = /\[ng\\\:/; return this.addFuture(name, function(done) { this.application.executeAction(function($window, $document) { //TODO(esprehn): Refactor this so it doesn't need to be in here. $document.elements = function(selector) { var args = Array.prototype.slice.call(arguments, 1); selector = (self.selector || '') + ' ' + (selector || ''); selector = _jQuery.trim(selector) || '*'; angular.forEach(args, function(value, index) { selector = selector.replace('$' + (index + 1), value); }); var result = $document.find(selector); if (selector.match(NG)) { angular.forEach(['[ng-','[data-ng-','[x-ng-'], function(value, index){ result = result.add(selector.replace(NG, value), $document); }); } if (!result.length) { throw { type: 'selector', message: 'Selector ' + selector + ' did not match any elements.' }; } return result; }; try { behavior.call(self, $window, $document, done); } catch(e) { if (e.type && e.type === 'selector') { done(e.message); } else { throw e; } } }); }, line); }; /** * Shared DSL statements that are useful to all scenarios. */ /** * Usage: * pause() pauses until you call resume() in the console */ angular.scenario.dsl('pause', function() { return function() { return this.addFuture('pausing for you to resume', function(done) { this.emit('InteractivePause', this.spec, this.step); this.$window.resume = function() { done(); }; }); }; }); /** * Usage: * sleep(seconds) pauses the test for specified number of seconds */ angular.scenario.dsl('sleep', function() { return function(time) { return this.addFuture('sleep for ' + time + ' seconds', function(done) { this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000); }); }; }); /** * Usage: * browser().navigateTo(url) Loads the url into the frame * browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to * browser().reload() refresh the page (reload the same URL) * browser().window.href() window.location.href * browser().window.path() window.location.pathname * browser().window.search() window.location.search * browser().window.hash() window.location.hash without # prefix * browser().location().url() see ng.$location#url * browser().location().path() see ng.$location#path * browser().location().search() see ng.$location#search * browser().location().hash() see ng.$location#hash */ angular.scenario.dsl('browser', function() { var chain = {}; chain.navigateTo = function(url, delegate) { var application = this.application; return this.addFuture("browser navigate to '" + url + "'", function(done) { if (delegate) { url = delegate.call(this, url); } application.navigateTo(url, function() { done(null, url); }, done); }); }; chain.reload = function() { var application = this.application; return this.addFutureAction('browser reload', function($window, $document, done) { var href = $window.location.href; application.navigateTo(href, function() { done(null, href); }, done); }); }; chain.window = function() { var api = {}; api.href = function() { return this.addFutureAction('window.location.href', function($window, $document, done) { done(null, $window.location.href); }); }; api.path = function() { return this.addFutureAction('window.location.path', function($window, $document, done) { done(null, $window.location.pathname); }); }; api.search = function() { return this.addFutureAction('window.location.search', function($window, $document, done) { done(null, $window.location.search); }); }; api.hash = function() { return this.addFutureAction('window.location.hash', function($window, $document, done) { done(null, $window.location.hash.replace('#', '')); }); }; return api; }; chain.location = function() { var api = {}; api.url = function() { return this.addFutureAction('$location.url()', function($window, $document, done) { done(null, $document.injector().get('$location').url()); }); }; api.path = function() { return this.addFutureAction('$location.path()', function($window, $document, done) { done(null, $document.injector().get('$location').path()); }); }; api.search = function() { return this.addFutureAction('$location.search()', function($window, $document, done) { done(null, $document.injector().get('$location').search()); }); }; api.hash = function() { return this.addFutureAction('$location.hash()', function($window, $document, done) { done(null, $document.injector().get('$location').hash()); }); }; return api; }; return function() { return chain; }; }); /** * Usage: * expect(future).{matcher} where matcher is one of the matchers defined * with angular.scenario.matcher * * ex. expect(binding("name")).toEqual("Elliott") */ angular.scenario.dsl('expect', function() { var chain = angular.extend({}, angular.scenario.matcher); chain.not = function() { this.inverse = true; return chain; }; return function(future) { this.future = future; return chain; }; }); /** * Usage: * using(selector, label) scopes the next DSL element selection * * ex. * using('#foo', "'Foo' text field").input('bar') */ angular.scenario.dsl('using', function() { return function(selector, label) { this.selector = _jQuery.trim((this.selector||'') + ' ' + selector); if (angular.isString(label) && label.length) { this.label = label + ' ( ' + this.selector + ' )'; } else { this.label = this.selector; } return this.dsl; }; }); /** * Usage: * binding(name) returns the value of the first matching binding */ angular.scenario.dsl('binding', function() { return function(name) { return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) { var values = $document.elements().bindings($window.angular.element, name); if (!values.length) { return done("Binding selector '" + name + "' did not match."); } done(null, values[0]); }); }; }); /** * Usage: * input(name).enter(value) enters value in input with specified name * input(name).check() checks checkbox * input(name).select(value) selects the radio button with specified name/value * input(name).val() returns the value of the input. */ angular.scenario.dsl('input', function() { var chain = {}; var supportInputEvent = 'oninput' in document.createElement('div') && msie != 9; chain.enter = function(value, event) { return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); input.val(value); input.trigger(event || (supportInputEvent ? 'input' : 'change')); done(); }); }; chain.check = function() { return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox'); input.trigger('click'); done(); }); }; chain.select = function(value) { return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) { var input = $document. elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio'); input.trigger('click'); done(); }); }; chain.val = function() { return this.addFutureAction("return input val", function($window, $document, done) { var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input'); done(null,input.val()); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * repeater('#products table', 'Product List').count() number of rows * repeater('#products table', 'Product List').row(1) all bindings in row as an array * repeater('#products table', 'Product List').column('product.name') all values across all rows in an array */ angular.scenario.dsl('repeater', function() { var chain = {}; chain.count = function() { return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.column = function(binding) { return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) { done(null, $document.elements().bindings($window.angular.element, binding)); }); }; chain.row = function(index) { return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) { var matches = $document.elements().slice(index, index + 1); if (!matches.length) return done('row ' + index + ' out of bounds'); done(null, matches.bindings($window.angular.element)); }); }; return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Usage: * select(name).option('value') select one option * select(name).options('value1', 'value2', ...) select options from a multi select */ angular.scenario.dsl('select', function() { var chain = {}; chain.option = function(value) { return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) { var select = $document.elements('select[ng\\:model="$1"]', this.name); var option = select.find('option[value="' + value + '"]'); if (option.length) { select.val(value); } else { option = select.find('option:contains("' + value + '")'); if (option.length) { select.val(option.val()); } else { return done("option '" + value + "' not found"); } } select.trigger('change'); done(); }); }; chain.options = function() { var values = arguments; return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) { var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name); select.val(values); select.trigger('change'); done(); }); }; return function(name) { this.name = name; return chain; }; }); /** * Usage: * element(selector, label).count() get the number of elements that match selector * element(selector, label).click() clicks an element * element(selector, label).mouseover() mouseover an element * element(selector, label).mousedown() mousedown an element * element(selector, label).mouseup() mouseup an element * element(selector, label).query(fn) executes fn(selectedElements, done) * element(selector, label).{method}() gets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val) * element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr) * element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr) */ angular.scenario.dsl('element', function() { var KEY_VALUE_METHODS = ['attr', 'css', 'prop']; var VALUE_METHODS = [ 'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width', 'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset' ]; var chain = {}; chain.count = function() { return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) { try { done(null, $document.elements().length); } catch (e) { done(null, 0); } }); }; chain.click = function() { return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('click')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.dblclick = function() { return this.addFutureAction("element '" + this.label + "' dblclick", function($window, $document, done) { var elements = $document.elements(); var href = elements.attr('href'); var eventProcessDefault = elements.trigger('dblclick')[0]; if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) { this.application.navigateTo(href, function() { done(); }, done); } else { done(); } }); }; chain.mouseover = function() { return this.addFutureAction("element '" + this.label + "' mouseover", function($window, $document, done) { var elements = $document.elements(); elements.trigger('mouseover'); done(); }); }; chain.mousedown = function() { return this.addFutureAction("element '" + this.label + "' mousedown", function($window, $document, done) { var elements = $document.elements(); elements.trigger('mousedown'); done(); }); }; chain.mouseup = function() { return this.addFutureAction("element '" + this.label + "' mouseup", function($window, $document, done) { var elements = $document.elements(); elements.trigger('mouseup'); done(); }); }; chain.query = function(fn) { return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) { fn.call(this, $document.elements(), done); }); }; angular.forEach(KEY_VALUE_METHODS, function(methodName) { chain[methodName] = function(name, value) { var args = arguments, futureName = (args.length == 1) ? "element '" + this.label + "' get " + methodName + " '" + name + "'" : "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); angular.forEach(VALUE_METHODS, function(methodName) { chain[methodName] = function(value) { var args = arguments, futureName = (args.length == 0) ? "element '" + this.label + "' " + methodName : futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'"; return this.addFutureAction(futureName, function($window, $document, done) { var element = $document.elements(); done(null, element[methodName].apply(element, args)); }); }; }); return function(selector, label) { this.dsl.using(selector, label); return chain; }; }); /** * Matchers for implementing specs. Follows the Jasmine spec conventions. */ angular.scenario.matcher('toEqual', function(expected) { return angular.equals(this.actual, expected); }); angular.scenario.matcher('toBe', function(expected) { return this.actual === expected; }); angular.scenario.matcher('toBeDefined', function() { return angular.isDefined(this.actual); }); angular.scenario.matcher('toBeTruthy', function() { return this.actual; }); angular.scenario.matcher('toBeFalsy', function() { return !this.actual; }); angular.scenario.matcher('toMatch', function(expected) { return new RegExp(expected).test(this.actual); }); angular.scenario.matcher('toBeNull', function() { return this.actual === null; }); angular.scenario.matcher('toContain', function(expected) { return includes(this.actual, expected); }); angular.scenario.matcher('toBeLessThan', function(expected) { return this.actual < expected; }); angular.scenario.matcher('toBeGreaterThan', function(expected) { return this.actual > expected; }); /** * User Interface for the Scenario Runner. * * TODO(esprehn): This should be refactored now that ObjectModel exists * to use angular bindings for the UI. */ angular.scenario.output('html', function(context, runner, model) { var specUiMap = {}, lastStepUiMap = {}; context.append( '<div id="header">' + ' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' + ' <ul id="status-legend" class="status-display">' + ' <li class="status-error">0 Errors</li>' + ' <li class="status-failure">0 Failures</li>' + ' <li class="status-success">0 Passed</li>' + ' </ul>' + '</div>' + '<div id="specs">' + ' <div class="test-children"></div>' + '</div>' ); runner.on('InteractivePause', function(spec) { var ui = lastStepUiMap[spec.id]; ui.find('.test-title'). html('paused... <a href="javascript:resume()">resume</a> when ready.'); }); runner.on('SpecBegin', function(spec) { var ui = findContext(spec); ui.find('> .tests').append( '<li class="status-pending test-it"></li>' ); ui = ui.find('> .tests li:last'); ui.append( '<div class="test-info">' + ' <p class="test-title">' + ' <span class="timer-result"></span>' + ' <span class="test-name"></span>' + ' </p>' + '</div>' + '<div class="scrollpane">' + ' <ol class="test-actions"></ol>' + '</div>' ); ui.find('> .test-info .test-name').text(spec.name); ui.find('> .test-info').click(function() { var scrollpane = ui.find('> .scrollpane'); var actions = scrollpane.find('> .test-actions'); var name = context.find('> .test-info .test-name'); if (actions.find(':visible').length) { actions.hide(); name.removeClass('open').addClass('closed'); } else { actions.show(); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); name.removeClass('closed').addClass('open'); } }); specUiMap[spec.id] = ui; }); runner.on('SpecError', function(spec, error) { var ui = specUiMap[spec.id]; ui.append('<pre></pre>'); ui.find('> pre').text(formatException(error)); }); runner.on('SpecEnd', function(spec) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); ui.removeClass('status-pending'); ui.addClass('status-' + spec.status); ui.find("> .test-info .timer-result").text(spec.duration + "ms"); if (spec.status === 'success') { ui.find('> .test-info .test-name').addClass('closed'); ui.find('> .scrollpane .test-actions').hide(); } updateTotals(spec.status); }); runner.on('StepBegin', function(spec, step) { var ui = specUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>'); var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last'); stepUi.append( '<div class="timer-result"></div>' + '<div class="test-title"></div>' ); stepUi.find('> .test-title').text(step.name); var scrollpane = stepUi.parents('.scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); runner.on('StepFailure', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepError', function(spec, step, error) { var ui = lastStepUiMap[spec.id]; addError(ui, step.line, error); }); runner.on('StepEnd', function(spec, step) { var stepUi = lastStepUiMap[spec.id]; spec = model.getSpec(spec.id); step = spec.getLastStep(); stepUi.find('.timer-result').text(step.duration + 'ms'); stepUi.removeClass('status-pending'); stepUi.addClass('status-' + step.status); var scrollpane = specUiMap[spec.id].find('> .scrollpane'); scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight')); }); /** * Finds the context of a spec block defined by the passed definition. * * @param {Object} The definition created by the Describe object. */ function findContext(spec) { var currentContext = context.find('#specs'); angular.forEach(model.getDefinitionPath(spec), function(defn) { var id = 'describe-' + defn.id; if (!context.find('#' + id).length) { currentContext.find('> .test-children').append( '<div class="test-describe" id="' + id + '">' + ' <h2></h2>' + ' <div class="test-children"></div>' + ' <ul class="tests"></ul>' + '</div>' ); context.find('#' + id).find('> h2').text('describe: ' + defn.name); } currentContext = context.find('#' + id); }); return context.find('#describe-' + spec.definition.id); } /** * Updates the test counter for the status. * * @param {string} the status. */ function updateTotals(status) { var legend = context.find('#status-legend .status-' + status); var parts = legend.text().split(' '); var value = (parts[0] * 1) + 1; legend.text(value + ' ' + parts[1]); } /** * Add an error to a step. * * @param {Object} The JQuery wrapped context * @param {function()} fn() that should return the file/line number of the error * @param {Object} the error. */ function addError(context, line, error) { context.find('.test-title').append('<pre></pre>'); var message = _jQuery.trim(line() + '\n\n' + formatException(error)); context.find('.test-title pre:last').text(message); } }); /** * Generates JSON output into a context. */ angular.scenario.output('json', function(context, runner, model) { model.on('RunnerEnd', function() { context.text(angular.toJson(model.value)); }); }); /** * Generates XML output into a context. */ angular.scenario.output('xml', function(context, runner, model) { var $ = function(args) {return new context.init(args);}; model.on('RunnerEnd', function() { var scenario = $('<scenario></scenario>'); context.append(scenario); serializeXml(scenario, model.value); }); /** * Convert the tree into XML. * * @param {Object} context jQuery context to add the XML to. * @param {Object} tree node to serialize */ function serializeXml(context, tree) { angular.forEach(tree.children, function(child) { var describeContext = $('<describe></describe>'); describeContext.attr('id', child.id); describeContext.attr('name', child.name); context.append(describeContext); serializeXml(describeContext, child); }); var its = $('<its></its>'); context.append(its); angular.forEach(tree.specs, function(spec) { var it = $('<it></it>'); it.attr('id', spec.id); it.attr('name', spec.name); it.attr('duration', spec.duration); it.attr('status', spec.status); its.append(it); angular.forEach(spec.steps, function(step) { var stepContext = $('<step></step>'); stepContext.attr('name', step.name); stepContext.attr('duration', step.duration); stepContext.attr('status', step.status); it.append(stepContext); if (step.error) { var error = $('<error></error>'); stepContext.append(error); error.text(formatException(step.error)); } }); }); } }); /** * Creates a global value $result with the result of the runner. */ angular.scenario.output('object', function(context, runner, model) { runner.$window.$result = model.value; }); bindJQuery(); publishExternalAPI(angular); var $runner = new angular.scenario.Runner(window), scripts = document.getElementsByTagName('script'), script = scripts[scripts.length - 1], config = {}; angular.forEach(script.attributes, function(attr) { var match = attr.name.match(/ng[:\-](.*)/); if (match) { config[match[1]] = attr.value || true; } }); if (config.autotest) { JQLite(document).ready(function() { angular.scenario.setUpAndRun(config); }); } })(window, document); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>'); angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
src/containers/weather_list.js
peterussell/udemy-4-redux-wx
import React, { Component } from 'react'; import { connect } from 'react-redux'; import GoogleMap from '../components/google_map'; import Chart from '../components/chart'; class WeatherList extends Component { renderWeather(cityData) { const name = cityData.city.name; const temps = cityData.list.map(weather => weather.main.temp); const pressures = cityData.list.map(weather => weather.main.pressure); const humidities = cityData.list.map(weather => weather.main.humidity); // We can use ES6 to prevent duplicating the 'cityData.city.coord' like // below... // > const lon = cityData.city.coord.lon; // > const lat = cityData.city.coord.lat; // Instead we can use: const { lon, lat } = cityData.city.coord; return ( <tr key={name}> <td><GoogleMap lat={lat} lon={lon} /></td> <td><Chart data={temps} color="red" units="K" /></td> <td><Chart data={pressures} color="blue" units="hPa" /></td> <td><Chart data={humidities} color="green" units="%" /></td> </tr> ); } render() { return ( <table className="table table-hover"> <thead> <tr> <th>City</th> <th>Temperature (K)</th> <th>Pressure (hPa)</th> <th>Humidity (%)</th> </tr> </thead> <tbody> {this.props.weather.map(this.renderWeather)} </tbody> </table> ); } } // We can use some ES6 to quickly pull the weather property off state, // normally we would write: // > mapStateToProps(state) { return { weather: state.weather }; } // But with ES6 we can get the weather property on state directly by // using curly braces inside the argument list. This is the same as // writing: // > const weather = state.weather; // ... inside the function body. /* function mapStateToProps({ weather }}) { // weather is from state.weather; return { weather: weather }; } */ // Then recall, whenever we have a key and value with the same identifier, // then we can condense that down by using curly braces: // > { weather: weather } is the same as { weather } ... function mapStateToProps({ weather }) { return { weather }; } export default connect(mapStateToProps)(WeatherList);
src/BookList.react.js
DhammaLuke/citybook
import React, { Component } from 'react'; import Panel from 'react-bootstrap/lib/Panel'; import Col from 'react-bootstrap/lib/Col'; import Button from 'react-bootstrap/lib/Button'; import ListGroup from 'react-bootstrap/lib/ListGroup'; import ListGroupItem from 'react-bootstrap/lib/ListGroupItem'; import { Link } from 'react-router'; export default class BookList extends Component { constructor(){ super(); this.state = { books: [] } this.deleteStorage = this.deleteStorage.bind(this); } deleteStorage(){ localStorage.clear(); this.setState({ books: [] }) } componentWillMount(){ let books = []; for(var i=0, len=localStorage.length; i<len; i++) { let key = localStorage.key(i), value = localStorage[key]; books.push([key, value]); } this.setState({ books: books }) } render() { let bookList = this.state.books.map(function(result, i){ return ( <ListGroupItem key={i}><a href={'/#/books/' + result[1]}>{result[0]}</a></ListGroupItem> ) }) return ( <div> <h1 className="text-center">CityBook</h1> <Col lg={4} lgOffset={4}> <Panel header="My Contact Lists"> <ListGroup fill> {bookList} </ListGroup> </Panel> <Button bsStyle="danger" onClick={this.deleteStorage} block>Clear Contact Lists</Button> <br/> <Link to='/'> <Button bsStyle="primary" block>Make Another CityBook</Button> </Link> </Col> </div> ); } }
ajax/libs/rxjs/2.2.7/rx.lite.js
alexmojaki/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. (function (window, undefined) { var freeExports = typeof exports == 'object' && exports, freeModule = typeof module == 'object' && module && module.exports == freeExports && module, freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal) { window = freeGlobal; } /** * @name Rx * @type Object */ var Rx = { Internals: {} }; // Defaults function noop() { } function identity(x) { return x; } var defaultNow = Date.now; function defaultComparer(x, y) { return isEqual(x, y); } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.Internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { var result; // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && !(a && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior // http://es5.github.io/#x15.3.4.4 if (a == null || b == null) { return a === b; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `+0` vs. `-0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!suportNodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !supportsArgsClass && isArguments(a) ? Object : a.constructor, ctorB = !supportsArgsClass && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB )) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { length = a.length; size = b.length; // compare lengths to determine if a deep comparison is necessary result = size == a.length; // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } return result; } // deep compare each object for(var key in b) { if (hasOwnProperty.call(b, key)) { // count properties and deep compare each property value size++; return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], b[key], stackA, stackB)); } } if (result) { // ensure both objects have the same number of properties for (var key in a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.Internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.Internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.Internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.Internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. * @constructor */ var BooleanDisposable = Rx.BooleanDisposable = function () { this.isDisposed = false; this.current = null; }; // Set up aliases Rx.SingleAssignmentDisposable = Rx.SerialDisposable = BooleanDisposable; var booleanDisposablePrototype = BooleanDisposable.prototype; var SingleAssignmentDisposable = BooleanDisposable, SerialDisposable = BooleanDisposable; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /* @private */ booleanDisposablePrototype.disposable = function (value) { if (!value) { return this.getDisposable(); } else { this.setDisposable(value); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.Internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = window.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { window.clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = Scheduler.immediate = (function () { var queue; function Trampoline() { queue = new PriorityQueue(4); } Trampoline.prototype.dispose = function () { queue = null; }; Trampoline.prototype.run = function () { var item; while (queue.length > 0) { item = queue.dequeue(); if (!item.isCancelled()) { while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } }; function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { t = new Trampoline(); try { queue.enqueue(si); t.run(); } catch (e) { throw e; } finally { t.dispose(); } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var immediateScheduler = currentThreadScheduler; var SchedulePeriodicRecursive = Rx.Internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; (function () { function postMessageSupported () { // Ensure not in a worker if (!window.postMessage || window.importScripts) { return false; } var isAsync = false, oldHandler = window.onmessage; // Test for async window.onmessage = function () { isAsync = true; }; window.postMessage('','*'); window.onmessage = oldHandler; return isAsync; } // Check for setImmediate first for Node v0.11+ if (typeof window.setImmediate === 'function') { scheduleMethod = window.setImmediate; clearMethod = clearImmediate; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (window.addEventListener) { window.addEventListener('message', onGlobalPostMessage, false); } else { window.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; window.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!window.MessageChannel) { var channel = new window.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in window && 'onreadystatechange' in window.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = window.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; window.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return window.setTimeout(action, 0); }; clearMethod = window.clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = window.setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { window.clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * @constructor * @private */ var Enumerator = Rx.Internals.Enumerator = function (moveNext, getCurrent, dispose) { this.moveNext = moveNext; this.getCurrent = getCurrent; this.dispose = dispose; }; /** * @static * @memberOf Enumerator * @private */ var enumeratorCreate = Enumerator.create = function (moveNext, getCurrent, dispose) { var done = false; dispose || (dispose = noop); return new Enumerator(function () { if (done) { return false; } var result = moveNext(); if (!result) { done = true; dispose(); } return result; }, function () { return getCurrent(); }, function () { if (!done) { dispose(); done = true; } }); }; /** @private */ var Enumerable = Rx.Internals.Enumerable = (function () { /** * @constructor * @private */ function Enumerable(getEnumerator) { this.getEnumerator = getEnumerator; } /** * @private * @memberOf Enumerable# */ Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } else { e.dispose(); } } catch (exception) { ex = exception; e.dispose(); } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; e.dispose(); })); }); }; /** * @private * @memberOf Enumerable# */ Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e = sources.getEnumerator(), isDisposed = false, lastException; var subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, ex, hasNext; hasNext = false; if (!isDisposed) { try { hasNext = e.moveNext(); if (hasNext) { current = e.getCurrent(); } } catch (exception) { ex = exception; } } else { return; } if (ex) { observer.onError(ex); return; } if (!hasNext) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; return Enumerable; }()); /** * @static * @private * @memberOf Enumerable */ var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount === undefined) { repeatCount = -1; } return new Enumerable(function () { var current, left = repeatCount; return enumeratorCreate(function () { if (left === 0) { return false; } if (left > 0) { left--; } current = value; return true; }, function () { return current; }); }); }; /** * @static * @private * @memberOf Enumerable */ var enumerableFor = Enumerable.forEach = function (source, selector) { selector || (selector = identity); return new Enumerable(function () { var current, index = -1; return enumeratorCreate( function () { if (++index < source.length) { current = selector(source[index], index); return true; } return false; }, function () { return current; } ); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.Internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * * @constructor * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * * @memberOf AnonymousObserver * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * * @memberOf AnonymousObserver * @param {Any{ error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. * * @memberOf AnonymousObserver */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); }; return Observable; })(); /** @private */ var ScheduledObserver = Rx.Internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } /** @private */ ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; /** @private */ ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; /** @private */ ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; /** @private */ ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; /** @private */ ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable} other Observable sequence that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); var next = function (i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = slice.call(arguments); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; function selectMany(selector) { return this.select(selector).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x) { return selector(x).select(function (y) { return resultSelector(x, y); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = timeoutScheduler); return function () { var args = slice.call(arguments, 0), subject = new AsyncSubject(); scheduler.schedule(function () { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { subject.onError(err); return; } } else { if (results.length === 1) { results = results[0]; } } subject.onNext(results); subject.onCompleted(); } args.push(handler); func.apply(context, args); }); return subject.asObservable(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = timeoutScheduler); return function () { var args = slice.call(arguments, 0), subject = new AsyncSubject(); scheduler.schedule(function () { function handler(err) { if (err) { subject.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { subject.onError(e); return; } } else { if (results.length === 1) { results = results[0]; } } subject.onNext(results); subject.onCompleted(); } args.push(handler); func.apply(context, args); }); return subject.asObservable(); }; }; function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } else if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (el && el.length) { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el[i], eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} A Promises A+ implementation instance. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ Observable.fromPromise = function (promise) { var subject = new AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, function (reason) { subject.onError(reason); }); return subject.asObservable(); }; /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishLast(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** @private */ var ConnectableObservable = (function (_super) { inherits(ConnectableObservable, _super); /** * @constructor * @private */ function ConnectableObservable(source, subject) { var state = { subject: subject, source: source.asObservable(), hasSubscription: false, subscription: null }; this.connect = function () { if (!state.hasSubscription) { state.hasSubscription = true; state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { state.hasSubscription = false; })); } return state.subscription; }; function subscribe(observer) { return state.subject.subscribe(observer); } _super.call(this, subscribe); } /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.connect = function () { return this.connect(); }; /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.refCount = function () { var connectableSubscription = null, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect, subscription; count++; shouldConnect = count === 1; subscription = source.subscribe(observer); if (shouldConnect) { connectableSubscription = source.connect(); } return disposableCreate(function () { subscription.dispose(); count--; if (count === 0) { connectableSubscription.dispose(); } }); }); }; return ConnectableObservable; }(Observable)); function observableTimerTimeSpan(dueTime, scheduler) { var d = normalizeTime(dueTime); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(d, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { if (dueTime === period) { return new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }); } return observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { scheduler || (scheduler = timeoutScheduler); return observableTimerTimeSpanAndPeriod(period, period, scheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * var res = Rx.Observable.timer(5000); * var res = Rx.Observable.timer(5000, 1000); * var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; scheduler || (scheduler = timeoutScheduler); if (typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) { scheduler = periodOrScheduler; } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * var res = Rx.Observable.delay(5000); * var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.select(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { scheduler || (scheduler = timeoutScheduler); return this.select(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } if (atEnd) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { scheduler || (scheduler = timeoutScheduler); if (typeof intervalOrSampler === 'number') { return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); } return sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { var schedulerMethod, source = this; other || (other = observableThrow(new Error('Timeout'))); scheduler || (scheduler = timeoutScheduler); if (dueTime instanceof Date) { schedulerMethod = function (dt, action) { scheduler.scheduleWithAbsolute(dt, action); }; } else { schedulerMethod = function (dt, action) { scheduler.scheduleWithRelative(dt, action); }; } return new AnonymousObservable(function (observer) { var createTimer, id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); createTimer = function () { var myId = id; timer.setDisposable(schedulerMethod(dueTime, function () { switched = id === myId; var timerWins = switched; if (timerWins) { subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { var onNextWins = !switched; if (onNextWins) { id++; observer.onNext(x); createTimer(); } }, function (e) { var onErrorWins = !switched; if (onErrorWins) { id++; observer.onError(e); } }, function () { var onCompletedWins = !switched; if (onCompletedWins) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var t = scheduler.scheduleWithRelative(duration, function () { observer.onCompleted(); }); return new CompositeDisposable(t, source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithRelative(duration, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; var AnonymousObservable = Rx.Internals.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } _super.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception; var hv = this.hasValue; var v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.value = null, this.hasValue = false, this.observers = [], this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; var v = this.value; var hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); // Check for AMD if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { window.Rx = Rx; return define(function () { return Rx; }); } else if (freeExports) { if (typeof module == 'object' && module && module.exports == freeExports) { module.exports = Rx; } else { freeExports = Rx; } } else { window.Rx = Rx; } }(this));
example/src/views/buttons_home.js
fengshanjian/react-native-komect-uikit
import Expo from 'expo'; import React, { Component } from 'react'; import { View, ScrollView, StyleSheet, Platform } from 'react-native'; import { Text, Button, Icon, SocialIcon, Card } from 'react-native-elements'; import colors from 'HSColors'; import socialColors from 'HSSocialColors'; import fonts from 'HSFonts'; const log = () => { console.log('Attach a method here.'); }; class Buttons extends Component { render() { const { navigation } = this.props; return ( <ScrollView> <View style={styles.hero}> <Icon color="white" name="whatshot" size={62} type="material" /> <Text style={styles.heading}>Buttons & Icons</Text> </View> <Button buttonStyle={styles.button} backgroundColor={socialColors.facebook} icon={{ name: 'account', type: 'material-community' }} onPress={() => navigation.navigate('Button_Detail', { name: 'Jordan' })} title="Got to Buttons Detail View" /> <Button backgroundColor={socialColors.stumbleupon} onPress={() => log()} title="BUTTON" buttonStyle={styles.button} /> <Button buttonStyle={styles.button} iconRight backgroundColor={socialColors.quora} icon={{ name: 'invert-colors' }} onPress={() => log()} title="BUTTON WITH RIGHT ICON" /> <Button buttonStyle={styles.button} iconRight backgroundColor={socialColors.tumblr} icon={{ name: 'motorcycle' }} onPress={() => log()} title="BUTTON WITH RIGHT ICON" /> <Button buttonStyle={styles.button} raised backgroundColor={socialColors.foursquare} icon={{ name: 'card-travel' }} onPress={() => log()} title="BUTTON RAISED" /> <Button buttonStyle={styles.button} raised backgroundColor={socialColors.vimeo} icon={{ name: 'touch-app' }} onPress={() => log()} title="BUTTON RAISED" /> <Button buttonStyle={styles.button} raised backgroundColor={socialColors.twitter} icon={{ name: 'new-releases' }} onPress={() => log()} title="BUTTON RAISED" /> <Button buttonStyle={styles.button} raised backgroundColor={socialColors.linkedin} icon={{ name: 'business' }} onPress={() => log()} title="BUTTON RAISED" /> <Button buttonStyle={styles.button} raised backgroundColor={socialColors.pinterest} icon={{ name: 'send' }} onPress={() => log()} title="BUTTON RAISED" /> <Button buttonStyle={styles.button} raised onPress={() => log()} title="BUTTON RAISED" /> <Button large={true} buttonStyle={styles.button} onPress={() => log()} backgroundColor={socialColors.facebook} title="LARGE BUTTON" /> <Button large={true} buttonStyle={styles.button} backgroundColor={socialColors.stumbleupon} icon={{ name: 'cached' }} title="LARGE BUTTON WITH ICON" /> <Button large={true} buttonStyle={styles.button} backgroundColor={socialColors.quora} raised icon={{ name: 'album' }} title="LARGE RAISED WITH ICON" /> <Button large={true} buttonStyle={styles.button} raised iconRight backgroundColor={socialColors.tumblr} icon={{ name: 'accessibility' }} title="LARGE RAISED RIGHT ICON" /> <Button large={true} buttonStyle={styles.button} raised iconRight backgroundColor={socialColors.foursquare} icon={{ name: 'account-balance' }} title="LARGE RAISED RIGHT ICON" /> <Button large={true} buttonStyle={styles.button} raised backgroundColor={socialColors.vimeo} icon={{ name: 'change-history' }} title="LARGE RAISED WITH ICON" /> <Button large={true} buttonStyle={[{ marginBottom: 15, marginTop: 15 }]} icon={{ name: 'code' }} backgroundColor={socialColors.twitter} title="LARGE ANOTHER BUTTON" /> <Card title="ICONS" containerStyle={{ marginTop: 15 }}> <View style={[styles.socialRow, { marginVertical: 10 }]}> <Icon onPress={() => navigation.navigate('Icons_Detail')} type="font-awesome" color="#e14329" name="hashtag" /> <Icon onPress={() => console.log('hello')} type="font-awesome" color="#02b875" name="rocket" /> <Icon onPress={() => console.log('hello')} color="#000000" name="snapchat-ghost" type="font-awesome" /> <Icon color="#6441A5" name="btc" type="font-awesome" onPress={() => console.log('hello')} /> <Icon color="#f50" name="heartbeat" type="font-awesome" onPress={() => console.log('hello')} /> </View> <View style={[styles.socialRow, { marginVertical: 10 }]}> <Icon name="rowing" color="#673AB7" onPress={() => console.log('hello')} /> <Icon name="g-translate" color="#03A9F4" onPress={() => console.log('hello')} /> <Icon color="#009688" name="sc-telegram" type="evilicon" onPress={() => console.log('hello')} /> <Icon color="#8BC34A" name="social-apple" type="foundation" onPress={() => console.log('hello')} /> <Icon color="#FFC107" name="ios-american-football" type="ionicon" onPress={() => console.log('hello')} /> </View> <View style={styles.socialRow}> <Icon raised name="vpn-key" color="#E91E63" onPress={() => console.log('hello')} /> <Icon raised name="ring-volume" color="#3F51B5" onPress={() => console.log('hello')} /> <Icon raised color="#00BCD4" name="weekend" onPress={() => console.log('hello')} /> <Icon raised color="#CDDC39" name="bubble-chart" onPress={() => console.log('hello')} /> <Icon raised color="#FF5722" name="burst-mode" onPress={() => console.log('hello')} /> </View> <View style={styles.socialRow}> <Icon reverse raised name="account-balance" color="#673AB7" onPress={() => console.log('hello')} /> <Icon reverse raised name="android" color="#03A9F4" onPress={() => console.log('hello')} /> <Icon reverse raised color="#009688" name="code" onPress={() => console.log('hello')} /> <Icon reverse raised color="#8BC34A" name="card-travel" onPress={() => console.log('hello')} /> <Icon reverse raised color="#FF9800" name="extension" onPress={() => console.log('hello')} /> </View> <View style={styles.socialRow}> <Icon reverse name="group-work" color="#E91E63" onPress={() => console.log('hello')} /> <Icon reverse name="lightbulb-outline" color="#3F51B5" onPress={() => console.log('hello')} /> <Icon reverse color="#00BCD4" name="pets" onPress={() => console.log('hello')} /> <Icon reverse color="#CDDC39" name="polymer" onPress={() => console.log('hello')} /> <Icon reverse color="#FF5722" name="touch-app" onPress={() => console.log('hello')} /> </View> </Card> <Card title="SOCIAL ICONS" containerStyle={[ styles.socialRow, { marginTop: 15, marginBottom: 15 }, ]} > <View style={styles.socialRow}> <SocialIcon raised={false} type="gitlab" onPress={() => console.log('hi!')} /> <SocialIcon type="medium" onPress={() => console.log('hi2!')} /> <SocialIcon type="github-alt" onPress={() => console.log('hi3!')} /> <SocialIcon type="twitch" /> <SocialIcon type="soundcloud" /> </View> <View style={styles.socialRow}> <SocialIcon raised={false} type="facebook" onPress={() => console.log('hi!')} /> <SocialIcon type="twitter" onPress={() => console.log('hi2!')} /> <SocialIcon type="instagram" onPress={() => console.log('hi3!')} /> <SocialIcon raised={false} type="codepen" /> <SocialIcon raised={false} type="youtube" /> </View> </Card> <Card title="LIGHT SOCIAL ICONS" containerStyle={{ marginTop: 15, marginBottom: 15 }} > <View style={styles.socialRow}> <SocialIcon light raised={false} type="gitlab" onPress={() => console.log('hi!')} /> <SocialIcon light type="medium" onPress={() => console.log('hi2!')} /> <SocialIcon light type="github-alt" onPress={() => console.log('hi3!')} /> <SocialIcon light type="twitch" /> <SocialIcon light type="soundcloud" /> </View> </Card> <Card containerStyle={{ marginTop: 15, marginBottom: 15 }} title="SOCIAL BUTTONS" > <SocialIcon button type="medium" /> <SocialIcon button type="twitch" /> <SocialIcon title="Sign In With Facebook" button fontWeight="400" type="facebook" /> <SocialIcon title="Some Twitter Message" button type="twitter" /> <SocialIcon light button title="Some Instagram Message" type="instagram" /> </Card> </ScrollView> ); } } const styles = StyleSheet.create({ heading: { color: 'white', marginTop: 10, fontSize: 22, }, hero: { justifyContent: 'center', alignItems: 'center', padding: 40, backgroundColor: colors.primary2, }, titleContainer: {}, button: { marginTop: 15, }, title: { textAlign: 'center', color: colors.grey2, ...Platform.select({ ios: { fontFamily: fonts.ios.black, }, }), }, socialRow: { flexDirection: 'row', justifyContent: 'space-around', }, }); export default Buttons;
es/components/Form/TextField.js
welovekpop/uwave-web-welovekpop.club
import _jsx from "@babel/runtime/helpers/builtin/jsx"; import _extends from "@babel/runtime/helpers/builtin/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/builtin/objectWithoutProperties"; import _createClass from "@babel/runtime/helpers/builtin/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/builtin/assertThisInitialized"; import _inheritsLoose from "@babel/runtime/helpers/builtin/inheritsLoose"; import cx from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; var TextField = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(TextField, _React$Component); function TextField() { var _temp, _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return (_temp = _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this, _this.refInput = function (input) { _this.input = input; }, _temp) || _assertThisInitialized(_this); } var _proto = TextField.prototype; _proto.render = function render() { var _this$props = this.props, type = _this$props.type, icon = _this$props.icon, className = _this$props.className, props = _objectWithoutProperties(_this$props, ["type", "icon", "className"]); return _jsx("div", { className: cx('TextField', className) }, void 0, React.createElement("input", _extends({ ref: this.refInput, className: "TextField-input", type: type }, props)), _jsx("div", { className: "TextField-icon" }, void 0, icon)); }; _createClass(TextField, [{ key: "value", get: function get() { return this.input.value; } }]); return TextField; }(React.Component); TextField.defaultProps = { type: 'text' }; export { TextField as default }; TextField.propTypes = process.env.NODE_ENV !== "production" ? { className: PropTypes.string, type: PropTypes.string, icon: PropTypes.element } : {}; //# sourceMappingURL=TextField.js.map
Examples/UIExplorer/BorderExample.js
HSFGitHub/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * 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 NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var React = require('react-native'); var { StyleSheet, View } = React; var styles = StyleSheet.create({ box: { width: 100, height: 100, }, border1: { borderWidth: 10, borderColor: '#a52a2a', }, borderRadius: { borderWidth: 10, borderRadius: 10, borderColor: '#00ffff', }, border2: { borderWidth: 10, borderTopColor: 'red', borderRightColor: 'yellow', borderBottomColor: 'green', borderLeftColor: 'blue', }, border3: { borderColor: 'purple', borderTopWidth: 10, borderRightWidth: 20, borderBottomWidth: 30, borderLeftWidth: 40, }, border4: { borderTopWidth: 10, borderTopColor: 'red', borderRightWidth: 20, borderRightColor: 'yellow', borderBottomWidth: 30, borderBottomColor: 'green', borderLeftWidth: 40, borderLeftColor: 'blue', }, border5: { borderRadius: 50, borderTopWidth: 10, borderTopColor: 'red', borderRightWidth: 20, borderRightColor: 'yellow', borderBottomWidth: 30, borderBottomColor: 'green', borderLeftWidth: 40, borderLeftColor: 'blue', }, border6: { borderTopWidth: 10, borderTopColor: 'red', borderRightWidth: 20, borderRightColor: 'yellow', borderBottomWidth: 30, borderBottomColor: 'green', borderLeftWidth: 40, borderLeftColor: 'blue', borderTopLeftRadius: 100, }, border7: { borderWidth: 10, borderColor: 'rgba(255,0,0,0.5)', borderRadius: 30, overflow: 'hidden', }, border7_inner: { backgroundColor: 'blue', width: 100, height: 100 }, }); exports.title = 'Border'; exports.description = 'View borders'; exports.examples = [ { title: 'Equal-Width / Same-Color', description: 'borderWidth & borderColor', render() { return <View style={[styles.box, styles.border1]} />; } }, { title: 'Equal-Width / Same-Color', description: 'borderWidth & borderColor & borderRadius', render() { return <View style={[styles.box, styles.borderRadius]} />; } }, { title: 'Equal-Width Borders', description: 'borderWidth & border*Color', render() { return <View style={[styles.box, styles.border2]} />; } }, { title: 'Same-Color Borders', description: 'border*Width & borderColor', render() { return <View style={[styles.box, styles.border3]} />; } }, { title: 'Custom Borders', description: 'border*Width & border*Color', render() { return <View style={[styles.box, styles.border4]} />; } }, { title: 'Custom Borders', description: 'border*Width & border*Color', platform: 'ios', render() { return <View style={[styles.box, styles.border5]} />; } }, { title: 'Custom Borders', description: 'border*Width & border*Color', platform: 'ios', render() { return <View style={[styles.box, styles.border6]} />; } }, { title: 'Custom Borders', description: 'borderRadius & clipping', platform: 'ios', render() { return ( <View style={[styles.box, styles.border7]}> <View style={styles.border7_inner} /> </View> ); } }, ];
frontend/modules/list/components/AddItem.js
RyanNoelk/OpenEats
"use strict"; import React from 'react' import PropTypes from 'prop-types' import { injectIntl, defineMessages } from 'react-intl' import { ENTER_KEY } from '../constants/ListStatus' class AddItem extends React.Component { constructor(props) { super(props); this.state = { title: '', }; } handleChange = (event) => { this.setState({title: event.target.value}); }; handleKeyDown = (event) => { if (event.keyCode !== ENTER_KEY) { return; } event.preventDefault(); let val = this.state.title.trim(); if (val) { this.props.addItem(val); this.setState({title: ''}); } }; render() { const {formatMessage} = this.props.intl; const messages = defineMessages({ item: { id: 'list.new-input-placeholder', description: 'Placeholder for inputting new items', defaultMessage: 'What do you need to buy?', }, }); return ( <input className="new-item" placeholder={formatMessage(messages.item)} value={this.state.title} onKeyDown={this.handleKeyDown} onChange={this.handleChange} autoFocus={true} /> ) } } AddItem.propTypes = { addItem: PropTypes.func.isRequired, intl: PropTypes.object.isRequired }; export default injectIntl(AddItem)
modules/TransitionHook.js
omerts/react-router
import React from 'react'; import warning from 'warning'; var { object } = React.PropTypes; var TransitionHook = { contextTypes: { router: object.isRequired }, componentDidMount() { warning( typeof this.routerWillLeave === 'function', 'Components that mixin TransitionHook should have a routerWillLeave method, check %s', this.constructor.displayName || this.constructor.name ); if (this.routerWillLeave) this.context.router.addTransitionHook(this.routerWillLeave); }, componentWillUnmount() { if (this.routerWillLeave) this.context.router.removeTransitionHook(this.routerWillLeave); } }; export default TransitionHook;
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/Spinner.js
GoogleCloudPlatform/prometheus-engine
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { mapToCssModules, tagPropType } from './utils'; const propTypes = { tag: tagPropType, type: PropTypes.string, size: PropTypes.string, color: PropTypes.string, className: PropTypes.string, cssModule: PropTypes.object, children: PropTypes.string }; const defaultProps = { tag: 'div', type: 'border', children: 'Loading...' }; const Spinner = props => { const { className, cssModule, type, size, color, children, tag: Tag, ...attributes } = props; const classes = mapToCssModules( classNames( className, size ? `spinner-${type}-${size}` : false, `spinner-${type}`, color ? `text-${color}` : false ), cssModule ); return ( <Tag role="status" {...attributes} className={classes}> {children && <span className={mapToCssModules('sr-only', cssModule)}> {children} </span> } </Tag> ); }; Spinner.propTypes = propTypes; Spinner.defaultProps = defaultProps; export default Spinner;
admin/client/App/screens/Home/components/Section.js
pr1ntr/keystone
import React from 'react'; import getRelatedIconClass from '../utils/getRelatedIconClass'; class Section extends React.Component { render () { const iconClass = this.props.icon || getRelatedIconClass(this.props.id); return ( <div className="dashboard-group" data-section-label={this.props.label}> <div className="dashboard-group__heading"> <span className={`dashboard-group__heading-icon ${iconClass}`} /> {this.props.label} </div> {this.props.children} </div> ); } } Section.propTypes = { children: React.PropTypes.element.isRequired, icon: React.PropTypes.string, id: React.PropTypes.string, label: React.PropTypes.string.isRequired, }; export default Section;
HomeRange/app/pages/mine/vipcenter.js
Onlyjson/yanShu_Project
/** * @author: zhangyh-k@glondon.com * @description: * @Date: 2017/10/9 下午3:40 */ import React, { Component } from 'react'; import request from '../../utils/Request' import config from '../../utils/Config' import {Toast} from 'antd-mobile' import { AppRegistry, StyleSheet, AsyncStorage, Text, View, // ImageBackground, Image, Dimensions, PixelRatio, StatusBar, TouchableOpacity } from 'react-native'; let dim = Dimensions.get('window'); export default class Mine extends Component { // 获取 async get(key) { return AsyncStorage.getItem(key).then((value) => { const jsonValue = JSON.parse(value); this.setState({ userInfo:jsonValue }) return jsonValue; }); } //初始化赋值 constructor(props){ super(props); this.state={ level:"", money:"", } } static navigationOptions=({navigation})=>({ headerTintColor: "#333", headerBackTitle:null, headerStyle:{ backgroundColor:'#fff' }, headerTitle:'会员中心', headerTitleStyle:{ fontSize:18, color:'#333' }, }); //初始化赋值 componentDidMount(){ this.get('userInfo').then(()=>this.fetchcard()); } render() { let stuas = this.state.level; return ( <View style={{width:dim.width,height:dim.height,backgroundColor:'#fff'}}> <StatusBar barStyle={"dark-content"}/> <Vip navigation={this.props.navigation} tittle={this.tittleInfo(stuas)} load={this.Imgload(stuas)} ls={stuas}></Vip> <View style={[styles.center,{marginTop:49,opacity:this.kaitong(stuas)}]}> <View style={[{width:220,height:16,marginTop:25},styles.row]}> <View style={{width:100,alignSelf:'flex-end'}}> <Text style={{textAlign:'right',color:'#999',fontSize:16}}> 昵称: </Text> </View> <View style={{flex:1}}> <Text style={{color:'#333',fontSize:16}}> 逆风如解意 </Text> </View> </View> <View style={[{width:220,height:16,marginTop:25},styles.row]}> <View style={{width:100,alignSelf:'flex-end'}}> <Text style={{textAlign:'right',color:'#999',fontSize:16}}> 电话: </Text> </View> <View style={{flex:1}}> <Text style={{color:'#333',fontSize:16}}> 15690283832 </Text> </View> </View> <View style={[{width:220,height:16,marginTop:25},styles.row]}> <View style={{width:100,alignSelf:'flex-end'}}> <Text style={{textAlign:'right',color:'#999',fontSize:16}}> 会员卡号: </Text> </View> <View style={{flex:1}}> <Text style={{color:'#333',fontSize:16}}> 164994132 </Text> </View> </View> <View style={[{width:220,height:16,marginTop:25},styles.row]}> <View style={{width:100,alignSelf:'flex-end'}}> <Text style={{textAlign:'right',color:'#999',fontSize:16}}> 会员等级: </Text> </View> <View style={{flex:1}}> <Text style={{color:'#333',fontSize:16}}> 金卡 </Text> </View> </View> <View style={[{width:220,height:16,marginTop:25},styles.row]}> <View style={{width:100,alignSelf:'flex-end'}}> <Text style={{textAlign:'right',color:'#999',fontSize:16}}> 会员有效期: </Text> </View> <View style={{flex:1}}> <Text style={{color:'#333',fontSize:16}}> 2018年9月5日 </Text> <View style={{opacity:this.signByovervip(stuas)}}> <Text style={{color:'#ff3434',fontSize:12}}> (即将到期,请续费) </Text> </View> </View> </View> </View> </View> ); } signByovervip(obj){ if(obj==0){ return 1; }else { return 0; } } tittleInfo(obj){ if(obj==1){ return "金卡"; }if(obj==0){ return "暂无会员卡"; } else { return "即将到期"; } } Imgload(obj){ if(obj==1||obj==0){ return require("../../image/huiyuanzhongxin/bg.png"); }else { return require("../../image/huiyuanzhongxin/maturity_bg.png"); } } kaitong(obj){ if(obj!=0){ return 1 }else { return 0 } } fetchcard(){ let body = { userid: this.state.userInfo.id }; let url = config.api.base + config.api.mycard; request.post(url, body).then( (data) => { if (data.code =='1') { this.setState({ vipdata: data.data, level:data.data.viplevel }); //TODO } else { //TODO } } ).catch((err) => { alert(err); }).done(); } } function Vip(props) { let text =""; if(props.ls==0){ text="立即开通" }else{ text="立即续费" } let secondDisplay=""; if(props.ls==0){ secondDisplay=0; } else { secondDisplay=1; } let des=""; if(props.ls==2){ des="VIP"; } else { des="V"; } let firLevel=""; if(props.ls==0){ firLevel=""; }else { firLevel="1"; } let button1=""; if(props.ls==1){ button1=0; }else { button1=1; } return( <View> <StatusBar barStyle="dark-content"/> <View style={{width:dim.width,height:177,backgroundColor:'#fff'}}> <Image source={props.load} style={[{width:dim.width,height:177},styles.center]}> <Image style={{width:dim.width,height:4}} source={require("../../image/huiyuanzhongxin/line.png")}> </Image> <Image source={require("../../image/huiyuanzhongxin/ring.png")} style={[styles.center,{width:77,height:77,position:'absolute'}]}> <Text style={{backgroundColor:'rgba(0,0,0,0)',color:'#fff',fontSize:24}}> {des}<Text style={{fontSize:16}}>{firLevel}</Text> </Text> </Image> <Image source={require("../../image/huiyuanzhongxin/Small_circle.png")} style={[styles.center,{opacity:secondDisplay,width:42,height:42,position:'absolute',right:40}]}> <Text style={{backgroundColor:'rgba(0,0,0,0)',color:'#fff',fontSize:20}}> V<Text style={{fontSize:12}}>2</Text> </Text> </Image> </Image> <View style={[{backgroundColor:'rgba(0,0,0,0)',position:'absolute',top:125,left:dim.width/2,width:100,marginLeft:-50},styles.center]}> <Text style={{color:'#fff',fontSize:18}}>{props.tittle}</Text> </View> </View> <TouchableOpacity onPress={()=>props.navigation.navigate("FufeiVip",{})} style={[styles.center,{opacity:button1,backgroundColor:'#fff',width:193,height:50,borderRadius:40,overflow:'hidden',borderWidth:1,position:'absolute',top:152,left:dim.width/2,marginLeft:-96.5}]}> <Text style={{color:"#333",fontSize:18}}> {text} </Text> </TouchableOpacity> </View> ) } const styles = StyleSheet.create({ row:{ flexDirection:'row' }, borderTop:{ borderTopWidth:1,borderTopColor:"#f1f1f1" }, borderBottom:{ borderBottomWidth:1,borderBottomColor:"#f1f1f1" }, center:{ justifyContent: 'center', alignItems: 'center', }, container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
src/parser/warrior/arms/modules/features/Checklist/Module.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import BaseChecklist from 'parser/shared/modules/features/Checklist/Module'; import CastEfficiency from 'parser/shared/modules/CastEfficiency'; import Combatants from 'parser/shared/modules/Combatants'; import PreparationRuleAnalyzer from 'parser/shared/modules/features/Checklist/PreparationRuleAnalyzer'; import AlwaysBeCasting from '../AlwaysBeCasting'; import DeepWoundsUptime from '../../core/Dots/DeepWoundsUptime'; import RendUptime from '../../core/Dots/RendUptime'; import MortalStrike from '../../core/Execute/MortalStrike'; import SweepingStrikes from '../../core/SweepingStrikes'; import Component from './Component'; class Checklist extends BaseChecklist { static dependencies = { combatants: Combatants, castEfficiency: CastEfficiency, alwaysBeCasting: AlwaysBeCasting, preparationRuleAnalyzer: PreparationRuleAnalyzer, deepWoundsUptime: DeepWoundsUptime, rendUptime: RendUptime, mortalStrike: MortalStrike, sweepingStrikes: SweepingStrikes, }; render() { return ( <Component combatant={this.combatants.selected} castEfficiency={this.castEfficiency} thresholds={{ ...this.preparationRuleAnalyzer.thresholds, deepWounds: this.deepWoundsUptime.suggestionThresholds, rend: this.rendUptime.suggestionThresholds, downtimeSuggestionThresholds: this.alwaysBeCasting.downtimeSuggestionThresholds, goodMortalStrike: this.mortalStrike.goodMortalStrikeThresholds, badMortalStrike: this.mortalStrike.badMortalStrikeThresholds, badSweepingStrikes: this.sweepingStrikes.suggestionThresholds, }} /> ); } } export default Checklist;
ajax/libs/jquery/1.4.4/jquery.min.js
philipwalton/cdnjs
/*! * jQuery JavaScript Library v1.4.4 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Nov 11 19:04:53 2010 -0500 */ (function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h= h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"|| h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La, "`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this, e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a, "margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+ a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/, C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j, s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this, j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length}, toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j=== -1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false; if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--; if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload", b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&& !F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&& l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z], z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j, s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v= s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)|| [];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u, false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"), k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false, scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent= false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom= 1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display= "none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h= c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando); else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this, a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e= c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this, a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan", colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType=== 1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "), l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this, "__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one"; if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r= a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true}, attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&& b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0}; c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem, arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid= d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+ c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b= w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType=== 8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k=== "click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+ d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.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[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!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:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this, Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp= c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U}; var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!== "form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V, xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired= B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type=== "file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]=== 0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d, a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d= 1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d=== "object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}}); c.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){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}}); (function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i, [y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3]; break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr, q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h= l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*")); return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!== B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=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|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()=== i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m= i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g, "")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n, m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled=== true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"=== g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]- 0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n=== "first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()=== i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]]; if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m, g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1; for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"), i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g); n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&& function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F|| p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g= t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition? function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML; c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})}, not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h= h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context): c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a, 2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a, b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&& e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={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,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(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,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null; else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d= c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a, b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")): this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append", prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument|| b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length- 1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script")))); d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i, jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true, zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b), h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b); if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f= d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left; e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b=== "object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&& !this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})}, getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html", script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data|| !T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache= false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset; A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type", b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&& c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d|| c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]= encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess", [b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"), e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}}); if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show", 3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay", d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b, d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)=== "inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L|| 1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b, d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a* Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.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=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)} var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true; this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide|| this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a= c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(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;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a=== b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&& h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle; for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+= parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px", height:"1px",visibility:"hidden"});b.innerHTML="<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>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells= f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a, "marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a, e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&& c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase(); c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+ b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
ajax/libs/clappr/0.0.6/clappr.js
qrohlf/cdnjs
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // 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. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && 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); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],2:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],3:[function(require,module,exports){ (function (process,global){ (function(global) { 'use strict'; if (global.$traceurRuntime) { return; } var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $Object.defineProperties; var $defineProperty = $Object.defineProperty; var $freeze = $Object.freeze; var $getOwnPropertyDescriptor = $Object.getOwnPropertyDescriptor; var $getOwnPropertyNames = $Object.getOwnPropertyNames; var $keys = $Object.keys; var $hasOwnProperty = $Object.prototype.hasOwnProperty; var $toString = $Object.prototype.toString; var $preventExtensions = Object.preventExtensions; var $seal = Object.seal; var $isExtensible = Object.isExtensible; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var types = { void: function voidType() {}, any: function any() {}, string: function string() {}, number: function number() {}, boolean: function boolean() {} }; var method = nonEnum; var counter = 0; function newUniqueString() { return '__$' + Math.floor(Math.random() * 1e9) + '$' + ++counter + '$__'; } var symbolInternalProperty = newUniqueString(); var symbolDescriptionProperty = newUniqueString(); var symbolDataProperty = newUniqueString(); var symbolValues = $create(null); var privateNames = $create(null); function createPrivateName() { var s = newUniqueString(); privateNames[s] = true; return s; } function isSymbol(symbol) { return typeof symbol === 'object' && symbol instanceof SymbolValue; } function typeOf(v) { if (isSymbol(v)) return 'symbol'; return typeof v; } function Symbol(description) { var value = new SymbolValue(description); if (!(this instanceof Symbol)) return value; throw new TypeError('Symbol cannot be new\'ed'); } $defineProperty(Symbol.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(Symbol.prototype, 'toString', method(function() { var symbolValue = this[symbolDataProperty]; if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); var desc = symbolValue[symbolDescriptionProperty]; if (desc === undefined) desc = ''; return 'Symbol(' + desc + ')'; })); $defineProperty(Symbol.prototype, 'valueOf', method(function() { var symbolValue = this[symbolDataProperty]; if (!symbolValue) throw TypeError('Conversion from symbol to string'); if (!getOption('symbols')) return symbolValue[symbolInternalProperty]; return symbolValue; })); function SymbolValue(description) { var key = newUniqueString(); $defineProperty(this, symbolDataProperty, {value: this}); $defineProperty(this, symbolInternalProperty, {value: key}); $defineProperty(this, symbolDescriptionProperty, {value: description}); freeze(this); symbolValues[key] = this; } $defineProperty(SymbolValue.prototype, 'constructor', nonEnum(Symbol)); $defineProperty(SymbolValue.prototype, 'toString', { value: Symbol.prototype.toString, enumerable: false }); $defineProperty(SymbolValue.prototype, 'valueOf', { value: Symbol.prototype.valueOf, enumerable: false }); var hashProperty = createPrivateName(); var hashPropertyDescriptor = {value: undefined}; var hashObjectProperties = { hash: {value: undefined}, self: {value: undefined} }; var hashCounter = 0; function getOwnHashObject(object) { var hashObject = object[hashProperty]; if (hashObject && hashObject.self === object) return hashObject; if ($isExtensible(object)) { hashObjectProperties.hash.value = hashCounter++; hashObjectProperties.self.value = object; hashPropertyDescriptor.value = $create(null, hashObjectProperties); $defineProperty(object, hashProperty, hashPropertyDescriptor); return hashPropertyDescriptor.value; } return undefined; } function freeze(object) { getOwnHashObject(object); return $freeze.apply(this, arguments); } function preventExtensions(object) { getOwnHashObject(object); return $preventExtensions.apply(this, arguments); } function seal(object) { getOwnHashObject(object); return $seal.apply(this, arguments); } Symbol.iterator = Symbol(); freeze(SymbolValue.prototype); function toProperty(name) { if (isSymbol(name)) return name[symbolInternalProperty]; return name; } function getOwnPropertyNames(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; if (!symbolValues[name] && !privateNames[name]) rv.push(name); } return rv; } function getOwnPropertyDescriptor(object, name) { return $getOwnPropertyDescriptor(object, toProperty(name)); } function getOwnPropertySymbols(object) { var rv = []; var names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var symbol = symbolValues[names[i]]; if (symbol) rv.push(symbol); } return rv; } function hasOwnProperty(name) { return $hasOwnProperty.call(this, toProperty(name)); } function getOption(name) { return global.traceur && global.traceur.options[name]; } function setProperty(object, name, value) { var sym, desc; if (isSymbol(name)) { sym = name; name = name[symbolInternalProperty]; } object[name] = value; if (sym && (desc = $getOwnPropertyDescriptor(object, name))) $defineProperty(object, name, {enumerable: false}); return value; } function defineProperty(object, name, descriptor) { if (isSymbol(name)) { if (descriptor.enumerable) { descriptor = $create(descriptor, {enumerable: {value: false}}); } name = name[symbolInternalProperty]; } $defineProperty(object, name, descriptor); return object; } function polyfillObject(Object) { $defineProperty(Object, 'defineProperty', {value: defineProperty}); $defineProperty(Object, 'getOwnPropertyNames', {value: getOwnPropertyNames}); $defineProperty(Object, 'getOwnPropertyDescriptor', {value: getOwnPropertyDescriptor}); $defineProperty(Object.prototype, 'hasOwnProperty', {value: hasOwnProperty}); $defineProperty(Object, 'freeze', {value: freeze}); $defineProperty(Object, 'preventExtensions', {value: preventExtensions}); $defineProperty(Object, 'seal', {value: seal}); Object.getOwnPropertySymbols = getOwnPropertySymbols; } function exportStar(object) { for (var i = 1; i < arguments.length; i++) { var names = $getOwnPropertyNames(arguments[i]); for (var j = 0; j < names.length; j++) { var name = names[j]; if (privateNames[name]) continue; (function(mod, name) { $defineProperty(object, name, { get: function() { return mod[name]; }, enumerable: true }); })(arguments[i], names[j]); } } return object; } function isObject(x) { return x != null && (typeof x === 'object' || typeof x === 'function'); } function toObject(x) { if (x == null) throw $TypeError(); return $Object(x); } function assertObject(x) { if (!isObject(x)) throw $TypeError(x + ' is not an Object'); return x; } function setupGlobals(global) { global.Symbol = Symbol; polyfillObject(global.Object); } setupGlobals(global); global.$traceurRuntime = { assertObject: assertObject, createPrivateName: createPrivateName, exportStar: exportStar, getOwnHashObject: getOwnHashObject, privateNames: privateNames, setProperty: setProperty, setupGlobals: setupGlobals, toObject: toObject, toProperty: toProperty, type: types, typeof: typeOf, defineProperties: $defineProperties, defineProperty: $defineProperty, getOwnPropertyDescriptor: $getOwnPropertyDescriptor, getOwnPropertyNames: $getOwnPropertyNames, keys: $keys }; })(typeof global !== 'undefined' ? global : this); (function() { 'use strict'; var toObject = $traceurRuntime.toObject; function spread() { var rv = [], k = 0; for (var i = 0; i < arguments.length; i++) { var valueToSpread = toObject(arguments[i]); for (var j = 0; j < valueToSpread.length; j++) { rv[k++] = valueToSpread[j]; } } return rv; } $traceurRuntime.spread = spread; })(); (function() { 'use strict'; var $Object = Object; var $TypeError = TypeError; var $create = $Object.create; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $getOwnPropertyDescriptor = $traceurRuntime.getOwnPropertyDescriptor; var $getOwnPropertyNames = $traceurRuntime.getOwnPropertyNames; var $getPrototypeOf = Object.getPrototypeOf; function superDescriptor(homeObject, name) { var proto = $getPrototypeOf(homeObject); do { var result = $getOwnPropertyDescriptor(proto, name); if (result) return result; proto = $getPrototypeOf(proto); } while (proto); return undefined; } function superCall(self, homeObject, name, args) { return superGet(self, homeObject, name).apply(self, args); } function superGet(self, homeObject, name) { var descriptor = superDescriptor(homeObject, name); if (descriptor) { if (!descriptor.get) return descriptor.value; return descriptor.get.call(self); } return undefined; } function superSet(self, homeObject, name, value) { var descriptor = superDescriptor(homeObject, name); if (descriptor && descriptor.set) { descriptor.set.call(self, value); return value; } throw $TypeError("super has no setter '" + name + "'."); } function getDescriptors(object) { var descriptors = {}, name, names = $getOwnPropertyNames(object); for (var i = 0; i < names.length; i++) { var name = names[i]; descriptors[name] = $getOwnPropertyDescriptor(object, name); } return descriptors; } function createClass(ctor, object, staticObject, superClass) { $defineProperty(object, 'constructor', { value: ctor, configurable: true, enumerable: false, writable: true }); if (arguments.length > 3) { if (typeof superClass === 'function') ctor.__proto__ = superClass; ctor.prototype = $create(getProtoParent(superClass), getDescriptors(object)); } else { ctor.prototype = object; } $defineProperty(ctor, 'prototype', { configurable: false, writable: false }); return $defineProperties(ctor, getDescriptors(staticObject)); } function getProtoParent(superClass) { if (typeof superClass === 'function') { var prototype = superClass.prototype; if ($Object(prototype) === prototype || prototype === null) return superClass.prototype; } if (superClass === null) return null; throw new $TypeError(); } function defaultSuperCall(self, homeObject, args) { if ($getPrototypeOf(homeObject) !== null) superCall(self, homeObject, 'constructor', args); } $traceurRuntime.createClass = createClass; $traceurRuntime.defaultSuperCall = defaultSuperCall; $traceurRuntime.superCall = superCall; $traceurRuntime.superGet = superGet; $traceurRuntime.superSet = superSet; })(); (function() { 'use strict'; var createPrivateName = $traceurRuntime.createPrivateName; var $defineProperties = $traceurRuntime.defineProperties; var $defineProperty = $traceurRuntime.defineProperty; var $create = Object.create; var $TypeError = TypeError; function nonEnum(value) { return { configurable: true, enumerable: false, value: value, writable: true }; } var ST_NEWBORN = 0; var ST_EXECUTING = 1; var ST_SUSPENDED = 2; var ST_CLOSED = 3; var END_STATE = -2; var RETHROW_STATE = -3; function getInternalError(state) { return new Error('Traceur compiler bug: invalid state in state machine: ' + state); } function GeneratorContext() { this.state = 0; this.GState = ST_NEWBORN; this.storedException = undefined; this.finallyFallThrough = undefined; this.sent_ = undefined; this.returnValue = undefined; this.tryStack_ = []; } GeneratorContext.prototype = { pushTry: function(catchState, finallyState) { if (finallyState !== null) { var finallyFallThrough = null; for (var i = this.tryStack_.length - 1; i >= 0; i--) { if (this.tryStack_[i].catch !== undefined) { finallyFallThrough = this.tryStack_[i].catch; break; } } if (finallyFallThrough === null) finallyFallThrough = RETHROW_STATE; this.tryStack_.push({ finally: finallyState, finallyFallThrough: finallyFallThrough }); } if (catchState !== null) { this.tryStack_.push({catch: catchState}); } }, popTry: function() { this.tryStack_.pop(); }, get sent() { this.maybeThrow(); return this.sent_; }, set sent(v) { this.sent_ = v; }, get sentIgnoreThrow() { return this.sent_; }, maybeThrow: function() { if (this.action === 'throw') { this.action = 'next'; throw this.sent_; } }, end: function() { switch (this.state) { case END_STATE: return this; case RETHROW_STATE: throw this.storedException; default: throw getInternalError(this.state); } }, handleException: function(ex) { this.GState = ST_CLOSED; this.state = END_STATE; throw ex; } }; function nextOrThrow(ctx, moveNext, action, x) { switch (ctx.GState) { case ST_EXECUTING: throw new Error(("\"" + action + "\" on executing generator")); case ST_CLOSED: if (action == 'next') { return { value: undefined, done: true }; } throw new Error(("\"" + action + "\" on closed generator")); case ST_NEWBORN: if (action === 'throw') { ctx.GState = ST_CLOSED; throw x; } if (x !== undefined) throw $TypeError('Sent value to newborn generator'); case ST_SUSPENDED: ctx.GState = ST_EXECUTING; ctx.action = action; ctx.sent = x; var value = moveNext(ctx); var done = value === ctx; if (done) value = ctx.returnValue; ctx.GState = done ? ST_CLOSED : ST_SUSPENDED; return { value: value, done: done }; } } var ctxName = createPrivateName(); var moveNextName = createPrivateName(); function GeneratorFunction() {} function GeneratorFunctionPrototype() {} GeneratorFunction.prototype = GeneratorFunctionPrototype; $defineProperty(GeneratorFunctionPrototype, 'constructor', nonEnum(GeneratorFunction)); GeneratorFunctionPrototype.prototype = { constructor: GeneratorFunctionPrototype, next: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'next', v); }, throw: function(v) { return nextOrThrow(this[ctxName], this[moveNextName], 'throw', v); } }; $defineProperties(GeneratorFunctionPrototype.prototype, { constructor: {enumerable: false}, next: {enumerable: false}, throw: {enumerable: false} }); Object.defineProperty(GeneratorFunctionPrototype.prototype, Symbol.iterator, nonEnum(function() { return this; })); function createGeneratorInstance(innerFunction, functionObject, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new GeneratorContext(); var object = $create(functionObject.prototype); object[ctxName] = ctx; object[moveNextName] = moveNext; return object; } function initGeneratorFunction(functionObject) { functionObject.prototype = $create(GeneratorFunctionPrototype.prototype); functionObject.__proto__ = GeneratorFunctionPrototype; return functionObject; } function AsyncFunctionContext() { GeneratorContext.call(this); this.err = undefined; var ctx = this; ctx.result = new Promise(function(resolve, reject) { ctx.resolve = resolve; ctx.reject = reject; }); } AsyncFunctionContext.prototype = $create(GeneratorContext.prototype); AsyncFunctionContext.prototype.end = function() { switch (this.state) { case END_STATE: this.resolve(this.returnValue); break; case RETHROW_STATE: this.reject(this.storedException); break; default: this.reject(getInternalError(this.state)); } }; AsyncFunctionContext.prototype.handleException = function() { this.state = RETHROW_STATE; }; function asyncWrap(innerFunction, self) { var moveNext = getMoveNext(innerFunction, self); var ctx = new AsyncFunctionContext(); ctx.createCallback = function(newState) { return function(value) { ctx.state = newState; ctx.value = value; moveNext(ctx); }; }; ctx.errback = function(err) { handleCatch(ctx, err); moveNext(ctx); }; moveNext(ctx); return ctx.result; } function getMoveNext(innerFunction, self) { return function(ctx) { while (true) { try { return innerFunction.call(self, ctx); } catch (ex) { handleCatch(ctx, ex); } } }; } function handleCatch(ctx, ex) { ctx.storedException = ex; var last = ctx.tryStack_[ctx.tryStack_.length - 1]; if (!last) { ctx.handleException(ex); return; } ctx.state = last.catch !== undefined ? last.catch : last.finally; if (last.finallyFallThrough !== undefined) ctx.finallyFallThrough = last.finallyFallThrough; } $traceurRuntime.asyncWrap = asyncWrap; $traceurRuntime.initGeneratorFunction = initGeneratorFunction; $traceurRuntime.createGeneratorInstance = createGeneratorInstance; })(); (function() { function buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = []; if (opt_scheme) { out.push(opt_scheme, ':'); } if (opt_domain) { out.push('//'); if (opt_userInfo) { out.push(opt_userInfo, '@'); } out.push(opt_domain); if (opt_port) { out.push(':', opt_port); } } if (opt_path) { out.push(opt_path); } if (opt_queryData) { out.push('?', opt_queryData); } if (opt_fragment) { out.push('#', opt_fragment); } return out.join(''); } ; var splitRe = new RegExp('^' + '(?:' + '([^:/?#.]+)' + ':)?' + '(?://' + '(?:([^/?#]*)@)?' + '([\\w\\d\\-\\u0100-\\uffff.%]*)' + '(?::([0-9]+))?' + ')?' + '([^?#]+)?' + '(?:\\?([^#]*))?' + '(?:#(.*))?' + '$'); var ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; function split(uri) { return (uri.match(splitRe)); } function removeDotSegments(path) { if (path === '/') return '/'; var leadingSlash = path[0] === '/' ? '/' : ''; var trailingSlash = path.slice(-1) === '/' ? '/' : ''; var segments = path.split('/'); var out = []; var up = 0; for (var pos = 0; pos < segments.length; pos++) { var segment = segments[pos]; switch (segment) { case '': case '.': break; case '..': if (out.length) out.pop(); else up++; break; default: out.push(segment); } } if (!leadingSlash) { while (up-- > 0) { out.unshift('..'); } if (out.length === 0) out.push('.'); } return leadingSlash + out.join('/') + trailingSlash; } function joinAndCanonicalizePath(parts) { var path = parts[ComponentIndex.PATH] || ''; path = removeDotSegments(path); parts[ComponentIndex.PATH] = path; return buildFromEncodedParts(parts[ComponentIndex.SCHEME], parts[ComponentIndex.USER_INFO], parts[ComponentIndex.DOMAIN], parts[ComponentIndex.PORT], parts[ComponentIndex.PATH], parts[ComponentIndex.QUERY_DATA], parts[ComponentIndex.FRAGMENT]); } function canonicalizeUrl(url) { var parts = split(url); return joinAndCanonicalizePath(parts); } function resolveUrl(base, url) { var parts = split(url); var baseParts = split(base); if (parts[ComponentIndex.SCHEME]) { return joinAndCanonicalizePath(parts); } else { parts[ComponentIndex.SCHEME] = baseParts[ComponentIndex.SCHEME]; } for (var i = ComponentIndex.SCHEME; i <= ComponentIndex.PORT; i++) { if (!parts[i]) { parts[i] = baseParts[i]; } } if (parts[ComponentIndex.PATH][0] == '/') { return joinAndCanonicalizePath(parts); } var path = baseParts[ComponentIndex.PATH]; var index = path.lastIndexOf('/'); path = path.slice(0, index + 1) + parts[ComponentIndex.PATH]; parts[ComponentIndex.PATH] = path; return joinAndCanonicalizePath(parts); } function isAbsolute(name) { if (!name) return false; if (name[0] === '/') return true; var parts = split(name); if (parts[ComponentIndex.SCHEME]) return true; return false; } $traceurRuntime.canonicalizeUrl = canonicalizeUrl; $traceurRuntime.isAbsolute = isAbsolute; $traceurRuntime.removeDotSegments = removeDotSegments; $traceurRuntime.resolveUrl = resolveUrl; })(); (function(global) { 'use strict'; var $__2 = $traceurRuntime.assertObject($traceurRuntime), canonicalizeUrl = $__2.canonicalizeUrl, resolveUrl = $__2.resolveUrl, isAbsolute = $__2.isAbsolute; var moduleInstantiators = Object.create(null); var baseURL; if (global.location && global.location.href) baseURL = resolveUrl(global.location.href, './'); else baseURL = ''; var UncoatedModuleEntry = function UncoatedModuleEntry(url, uncoatedModule) { this.url = url; this.value_ = uncoatedModule; }; ($traceurRuntime.createClass)(UncoatedModuleEntry, {}, {}); var UncoatedModuleInstantiator = function UncoatedModuleInstantiator(url, func) { $traceurRuntime.superCall(this, $UncoatedModuleInstantiator.prototype, "constructor", [url, null]); this.func = func; }; var $UncoatedModuleInstantiator = UncoatedModuleInstantiator; ($traceurRuntime.createClass)(UncoatedModuleInstantiator, {getUncoatedModule: function() { if (this.value_) return this.value_; return this.value_ = this.func.call(global); }}, {}, UncoatedModuleEntry); function getUncoatedModuleInstantiator(name) { if (!name) return; var url = ModuleStore.normalize(name); return moduleInstantiators[url]; } ; var moduleInstances = Object.create(null); var liveModuleSentinel = {}; function Module(uncoatedModule) { var isLive = arguments[1]; var coatedModule = Object.create(null); Object.getOwnPropertyNames(uncoatedModule).forEach((function(name) { var getter, value; if (isLive === liveModuleSentinel) { var descr = Object.getOwnPropertyDescriptor(uncoatedModule, name); if (descr.get) getter = descr.get; } if (!getter) { value = uncoatedModule[name]; getter = function() { return value; }; } Object.defineProperty(coatedModule, name, { get: getter, enumerable: true }); })); Object.preventExtensions(coatedModule); return coatedModule; } var ModuleStore = { normalize: function(name, refererName, refererAddress) { if (typeof name !== "string") throw new TypeError("module name must be a string, not " + typeof name); if (isAbsolute(name)) return canonicalizeUrl(name); if (/[^\.]\/\.\.\//.test(name)) { throw new Error('module name embeds /../: ' + name); } if (name[0] === '.' && refererName) return resolveUrl(refererName, name); return canonicalizeUrl(name); }, get: function(normalizedName) { var m = getUncoatedModuleInstantiator(normalizedName); if (!m) return undefined; var moduleInstance = moduleInstances[m.url]; if (moduleInstance) return moduleInstance; moduleInstance = Module(m.getUncoatedModule(), liveModuleSentinel); return moduleInstances[m.url] = moduleInstance; }, set: function(normalizedName, module) { normalizedName = String(normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, (function() { return module; })); moduleInstances[normalizedName] = module; }, get baseURL() { return baseURL; }, set baseURL(v) { baseURL = String(v); }, registerModule: function(name, func) { var normalizedName = ModuleStore.normalize(name); if (moduleInstantiators[normalizedName]) throw new Error('duplicate module named ' + normalizedName); moduleInstantiators[normalizedName] = new UncoatedModuleInstantiator(normalizedName, func); }, bundleStore: Object.create(null), register: function(name, deps, func) { if (!deps || !deps.length && !func.length) { this.registerModule(name, func); } else { this.bundleStore[name] = { deps: deps, execute: function() { var $__0 = arguments; var depMap = {}; deps.forEach((function(dep, index) { return depMap[dep] = $__0[index]; })); var registryEntry = func.call(this, depMap); registryEntry.execute.call(this); return registryEntry.exports; } }; } }, getAnonymousModule: function(func) { return new Module(func.call(global), liveModuleSentinel); }, getForTesting: function(name) { var $__0 = this; if (!this.testingPrefix_) { Object.keys(moduleInstances).some((function(key) { var m = /(traceur@[^\/]*\/)/.exec(key); if (m) { $__0.testingPrefix_ = m[1]; return true; } })); } return this.get(this.testingPrefix_ + name); } }; ModuleStore.set('@traceur/src/runtime/ModuleStore', new Module({ModuleStore: ModuleStore})); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); }; $traceurRuntime.ModuleStore = ModuleStore; global.System = { register: ModuleStore.register.bind(ModuleStore), get: ModuleStore.get, set: ModuleStore.set, normalize: ModuleStore.normalize }; $traceurRuntime.getModuleImpl = function(name) { var instantiator = getUncoatedModuleInstantiator(name); return instantiator && instantiator.getUncoatedModule(); }; })(typeof global !== 'undefined' ? global : this); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/utils", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/utils"; var toObject = $traceurRuntime.toObject; function toUint32(x) { return x | 0; } function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function isCallable(x) { return typeof x === 'function'; } function toInteger(x) { x = +x; if (isNaN(x)) return 0; if (!isFinite(x) || x === 0) return x; return x > 0 ? Math.floor(x) : Math.ceil(x); } var MAX_SAFE_LENGTH = Math.pow(2, 53) - 1; function toLength(x) { var len = toInteger(x); return len < 0 ? 0 : Math.min(len, MAX_SAFE_LENGTH); } return { get toObject() { return toObject; }, get toUint32() { return toUint32; }, get isObject() { return isObject; }, get isCallable() { return isCallable; }, get toInteger() { return toInteger; }, get toLength() { return toLength; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Array", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Array"; var $__3 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__3.toInteger, toLength = $__3.toLength, toObject = $__3.toObject, isCallable = $__3.isCallable; function fill(value) { var start = arguments[1] !== (void 0) ? arguments[1] : 0; var end = arguments[2]; var object = toObject(this); var len = toLength(object.length); var fillStart = toInteger(start); var fillEnd = end !== undefined ? toInteger(end) : len; fillStart = fillStart < 0 ? Math.max(len + fillStart, 0) : Math.min(fillStart, len); fillEnd = fillEnd < 0 ? Math.max(len + fillEnd, 0) : Math.min(fillEnd, len); while (fillStart < fillEnd) { object[fillStart] = value; fillStart++; } return object; } function find(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg); } function findIndex(predicate) { var thisArg = arguments[1]; return findHelper(this, predicate, thisArg, true); } function findHelper(self, predicate) { var thisArg = arguments[2]; var returnIndex = arguments[3] !== (void 0) ? arguments[3] : false; var object = toObject(self); var len = toLength(object.length); if (!isCallable(predicate)) { throw TypeError(); } for (var i = 0; i < len; i++) { if (i in object) { var value = object[i]; if (predicate.call(thisArg, value, i, object)) { return returnIndex ? i : value; } } } return returnIndex ? -1 : undefined; } return { get fill() { return fill; }, get find() { return find; }, get findIndex() { return findIndex; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator", [], function() { "use strict"; var $__5; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator"; var $__6 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toObject = $__6.toObject, toUint32 = $__6.toUint32; var ARRAY_ITERATOR_KIND_KEYS = 1; var ARRAY_ITERATOR_KIND_VALUES = 2; var ARRAY_ITERATOR_KIND_ENTRIES = 3; var ArrayIterator = function ArrayIterator() {}; ($traceurRuntime.createClass)(ArrayIterator, ($__5 = {}, Object.defineProperty($__5, "next", { value: function() { var iterator = toObject(this); var array = iterator.iteratorObject_; if (!array) { throw new TypeError('Object is not an ArrayIterator'); } var index = iterator.arrayIteratorNextIndex_; var itemKind = iterator.arrayIterationKind_; var length = toUint32(array.length); if (index >= length) { iterator.arrayIteratorNextIndex_ = Infinity; return createIteratorResultObject(undefined, true); } iterator.arrayIteratorNextIndex_ = index + 1; if (itemKind == ARRAY_ITERATOR_KIND_VALUES) return createIteratorResultObject(array[index], false); if (itemKind == ARRAY_ITERATOR_KIND_ENTRIES) return createIteratorResultObject([index, array[index]], false); return createIteratorResultObject(index, false); }, configurable: true, enumerable: true, writable: true }), Object.defineProperty($__5, Symbol.iterator, { value: function() { return this; }, configurable: true, enumerable: true, writable: true }), $__5), {}); function createArrayIterator(array, kind) { var object = toObject(array); var iterator = new ArrayIterator; iterator.iteratorObject_ = object; iterator.arrayIteratorNextIndex_ = 0; iterator.arrayIterationKind_ = kind; return iterator; } function createIteratorResultObject(value, done) { return { value: value, done: done }; } function entries() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_ENTRIES); } function keys() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_KEYS); } function values() { return createArrayIterator(this, ARRAY_ITERATOR_KIND_VALUES); } return { get entries() { return entries; }, get keys() { return keys; }, get values() { return values; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Map", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Map"; var isObject = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")).isObject; var getOwnHashObject = $traceurRuntime.getOwnHashObject; var $hasOwnProperty = Object.prototype.hasOwnProperty; var deletedSentinel = {}; function lookupIndex(map, key) { if (isObject(key)) { var hashObject = getOwnHashObject(key); return hashObject && map.objectIndex_[hashObject.hash]; } if (typeof key === 'string') return map.stringIndex_[key]; return map.primitiveIndex_[key]; } function initMap(map) { map.entries_ = []; map.objectIndex_ = Object.create(null); map.stringIndex_ = Object.create(null); map.primitiveIndex_ = Object.create(null); map.deletedCount_ = 0; } var Map = function Map() { var iterable = arguments[0]; if (!isObject(this)) throw new TypeError("Constructor Map requires 'new'"); if ($hasOwnProperty.call(this, 'entries_')) { throw new TypeError("Map can not be reentrantly initialised"); } initMap(this); if (iterable !== null && iterable !== undefined) { var iter = iterable[Symbol.iterator]; if (iter !== undefined) { for (var $__8 = iterable[Symbol.iterator](), $__9; !($__9 = $__8.next()).done; ) { var $__10 = $traceurRuntime.assertObject($__9.value), key = $__10[0], value = $__10[1]; { this.set(key, value); } } } } }; ($traceurRuntime.createClass)(Map, { get size() { return this.entries_.length / 2 - this.deletedCount_; }, get: function(key) { var index = lookupIndex(this, key); if (index !== undefined) return this.entries_[index + 1]; }, set: function(key, value) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index = lookupIndex(this, key); if (index !== undefined) { this.entries_[index + 1] = value; } else { index = this.entries_.length; this.entries_[index] = key; this.entries_[index + 1] = value; if (objectMode) { var hashObject = getOwnHashObject(key); var hash = hashObject.hash; this.objectIndex_[hash] = index; } else if (stringMode) { this.stringIndex_[key] = index; } else { this.primitiveIndex_[key] = index; } } return this; }, has: function(key) { return lookupIndex(this, key) !== undefined; }, delete: function(key) { var objectMode = isObject(key); var stringMode = typeof key === 'string'; var index; var hash; if (objectMode) { var hashObject = getOwnHashObject(key); if (hashObject) { index = this.objectIndex_[hash = hashObject.hash]; delete this.objectIndex_[hash]; } } else if (stringMode) { index = this.stringIndex_[key]; delete this.stringIndex_[key]; } else { index = this.primitiveIndex_[key]; delete this.primitiveIndex_[key]; } if (index !== undefined) { this.entries_[index] = deletedSentinel; this.entries_[index + 1] = undefined; this.deletedCount_++; } }, clear: function() { initMap(this); }, forEach: function(callbackFn) { var thisArg = arguments[1]; for (var i = 0, len = this.entries_.length; i < len; i += 2) { var key = this.entries_[i]; var value = this.entries_[i + 1]; if (key === deletedSentinel) continue; callbackFn.call(thisArg, value, key, this); } } }, {}); return {get Map() { return Map; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Object", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Object"; var $__11 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/utils")), toInteger = $__11.toInteger, toLength = $__11.toLength, toObject = $__11.toObject, isCallable = $__11.isCallable; var $__11 = $traceurRuntime.assertObject($traceurRuntime), defineProperty = $__11.defineProperty, getOwnPropertyDescriptor = $__11.getOwnPropertyDescriptor, getOwnPropertyNames = $__11.getOwnPropertyNames, keys = $__11.keys, privateNames = $__11.privateNames; function is(left, right) { if (left === right) return left !== 0 || 1 / left === 1 / right; return left !== left && right !== right; } function assign(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; var props = keys(source); var p, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; target[name] = source[name]; } } return target; } function mixin(target, source) { var props = getOwnPropertyNames(source); var p, descriptor, length = props.length; for (p = 0; p < length; p++) { var name = props[p]; if (privateNames[name]) continue; descriptor = getOwnPropertyDescriptor(source, props[p]); defineProperty(target, props[p], descriptor); } return target; } return { get is() { return is; }, get assign() { return assign; }, get mixin() { return mixin; } }; }); System.register("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap"; var $__default = function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { scheduleFlush(); } }; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; function useNextTick() { return function() { process.nextTick(flush); }; } function useMutationObserver() { var iterations = 0; var observer = new BrowserMutationObserver(flush); var node = document.createTextNode(''); observer.observe(node, {characterData: true}); return function() { node.data = (iterations = ++iterations % 2); }; } function useSetTimeout() { return function() { setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } return {get default() { return $__default; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/Promise", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/Promise"; var async = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/node_modules/rsvp/lib/rsvp/asap")).default; var promiseRaw = {}; function isPromise(x) { return x && typeof x === 'object' && x.status_ !== undefined; } function idResolveHandler(x) { return x; } function idRejectHandler(x) { throw x; } function chain(promise) { var onResolve = arguments[1] !== (void 0) ? arguments[1] : idResolveHandler; var onReject = arguments[2] !== (void 0) ? arguments[2] : idRejectHandler; var deferred = getDeferred(promise.constructor); switch (promise.status_) { case undefined: throw TypeError; case 0: promise.onResolve_.push(onResolve, deferred); promise.onReject_.push(onReject, deferred); break; case +1: promiseEnqueue(promise.value_, [onResolve, deferred]); break; case -1: promiseEnqueue(promise.value_, [onReject, deferred]); break; } return deferred.promise; } function getDeferred(C) { if (this === $Promise) { var promise = promiseInit(new $Promise(promiseRaw)); return { promise: promise, resolve: (function(x) { promiseResolve(promise, x); }), reject: (function(r) { promiseReject(promise, r); }) }; } else { var result = {}; result.promise = new C((function(resolve, reject) { result.resolve = resolve; result.reject = reject; })); return result; } } function promiseSet(promise, status, value, onResolve, onReject) { promise.status_ = status; promise.value_ = value; promise.onResolve_ = onResolve; promise.onReject_ = onReject; return promise; } function promiseInit(promise) { return promiseSet(promise, 0, undefined, [], []); } var Promise = function Promise(resolver) { if (resolver === promiseRaw) return; if (typeof resolver !== 'function') throw new TypeError; var promise = promiseInit(this); try { resolver((function(x) { promiseResolve(promise, x); }), (function(r) { promiseReject(promise, r); })); } catch (e) { promiseReject(promise, e); } }; ($traceurRuntime.createClass)(Promise, { catch: function(onReject) { return this.then(undefined, onReject); }, then: function(onResolve, onReject) { if (typeof onResolve !== 'function') onResolve = idResolveHandler; if (typeof onReject !== 'function') onReject = idRejectHandler; var that = this; var constructor = this.constructor; return chain(this, function(x) { x = promiseCoerce(constructor, x); return x === that ? onReject(new TypeError) : isPromise(x) ? x.then(onResolve, onReject) : onResolve(x); }, onReject); } }, { resolve: function(x) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), +1, x); } else { return new this(function(resolve, reject) { resolve(x); }); } }, reject: function(r) { if (this === $Promise) { return promiseSet(new $Promise(promiseRaw), -1, r); } else { return new this((function(resolve, reject) { reject(r); })); } }, cast: function(x) { if (x instanceof this) return x; if (isPromise(x)) { var result = getDeferred(this); chain(x, result.resolve, result.reject); return result.promise; } return this.resolve(x); }, all: function(values) { var deferred = getDeferred(this); var resolutions = []; try { var count = values.length; if (count === 0) { deferred.resolve(resolutions); } else { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then(function(i, x) { resolutions[i] = x; if (--count === 0) deferred.resolve(resolutions); }.bind(undefined, i), (function(r) { deferred.reject(r); })); } } } catch (e) { deferred.reject(e); } return deferred.promise; }, race: function(values) { var deferred = getDeferred(this); try { for (var i = 0; i < values.length; i++) { this.resolve(values[i]).then((function(x) { deferred.resolve(x); }), (function(r) { deferred.reject(r); })); } } catch (e) { deferred.reject(e); } return deferred.promise; } }); var $Promise = Promise; var $PromiseReject = $Promise.reject; function promiseResolve(promise, x) { promiseDone(promise, +1, x, promise.onResolve_); } function promiseReject(promise, r) { promiseDone(promise, -1, r, promise.onReject_); } function promiseDone(promise, status, value, reactions) { if (promise.status_ !== 0) return; promiseEnqueue(value, reactions); promiseSet(promise, status, value); } function promiseEnqueue(value, tasks) { async((function() { for (var i = 0; i < tasks.length; i += 2) { promiseHandle(value, tasks[i], tasks[i + 1]); } })); } function promiseHandle(value, handler, deferred) { try { var result = handler(value); if (result === deferred.promise) throw new TypeError; else if (isPromise(result)) chain(result, deferred.resolve, deferred.reject); else deferred.resolve(result); } catch (e) { try { deferred.reject(e); } catch (e) {} } } var thenableSymbol = '@@thenable'; function isObject(x) { return x && (typeof x === 'object' || typeof x === 'function'); } function promiseCoerce(constructor, x) { if (!isPromise(x) && isObject(x)) { var then; try { then = x.then; } catch (r) { var promise = $PromiseReject.call(constructor, r); x[thenableSymbol] = promise; return promise; } if (typeof then === 'function') { var p = x[thenableSymbol]; if (p) { return p; } else { var deferred = getDeferred(constructor); x[thenableSymbol] = deferred.promise; try { then.call(x, deferred.resolve, deferred.reject); } catch (r) { deferred.reject(r); } return deferred.promise; } } } return x; } return {get Promise() { return Promise; }}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/String", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/String"; var $toString = Object.prototype.toString; var $indexOf = String.prototype.indexOf; var $lastIndexOf = String.prototype.lastIndexOf; function startsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) == start; } function endsWith(search) { var string = String(this); if (this == null || $toString.call(search) == '[object RegExp]') { throw TypeError(); } var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var pos = stringLength; if (arguments.length > 1) { var position = arguments[1]; if (position !== undefined) { pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } } } var end = Math.min(Math.max(pos, 0), stringLength); var start = end - searchLength; if (start < 0) { return false; } return $lastIndexOf.call(string, searchString, start) == start; } function contains(search) { if (this == null) { throw TypeError(); } var string = String(this); var stringLength = string.length; var searchString = String(search); var searchLength = searchString.length; var position = arguments.length > 1 ? arguments[1] : undefined; var pos = position ? Number(position) : 0; if (isNaN(pos)) { pos = 0; } var start = Math.min(Math.max(pos, 0), stringLength); return $indexOf.call(string, searchString, pos) != -1; } function repeat(count) { if (this == null) { throw TypeError(); } var string = String(this); var n = count ? Number(count) : 0; if (isNaN(n)) { n = 0; } if (n < 0 || n == Infinity) { throw RangeError(); } if (n == 0) { return ''; } var result = ''; while (n--) { result += string; } return result; } function codePointAt(position) { if (this == null) { throw TypeError(); } var string = String(this); var size = string.length; var index = position ? Number(position) : 0; if (isNaN(index)) { index = 0; } if (index < 0 || index >= size) { return undefined; } var first = string.charCodeAt(index); var second; if (first >= 0xD800 && first <= 0xDBFF && size > index + 1) { second = string.charCodeAt(index + 1); if (second >= 0xDC00 && second <= 0xDFFF) { return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; } } return first; } function raw(callsite) { var raw = callsite.raw; var len = raw.length >>> 0; if (len === 0) return ''; var s = ''; var i = 0; while (true) { s += raw[i]; if (i + 1 === len) return s; s += arguments[++i]; } } function fromCodePoint() { var codeUnits = []; var floor = Math.floor; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } while (++index < length) { var codePoint = Number(arguments[index]); if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || floor(codePoint) != codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } } return String.fromCharCode.apply(null, codeUnits); } return { get startsWith() { return startsWith; }, get endsWith() { return endsWith; }, get contains() { return contains; }, get repeat() { return repeat; }, get codePointAt() { return codePointAt; }, get raw() { return raw; }, get fromCodePoint() { return fromCodePoint; } }; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfills/polyfills"; var Map = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Map")).Map; var Promise = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Promise")).Promise; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/String")), codePointAt = $__14.codePointAt, contains = $__14.contains, endsWith = $__14.endsWith, fromCodePoint = $__14.fromCodePoint, repeat = $__14.repeat, raw = $__14.raw, startsWith = $__14.startsWith; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Array")), fill = $__14.fill, find = $__14.find, findIndex = $__14.findIndex; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/ArrayIterator")), entries = $__14.entries, keys = $__14.keys, values = $__14.values; var $__14 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/Object")), assign = $__14.assign, is = $__14.is, mixin = $__14.mixin; function maybeDefineMethod(object, name, value) { if (!(name in object)) { Object.defineProperty(object, name, { value: value, configurable: true, enumerable: false, writable: true }); } } function maybeAddFunctions(object, functions) { for (var i = 0; i < functions.length; i += 2) { var name = functions[i]; var value = functions[i + 1]; maybeDefineMethod(object, name, value); } } function polyfillPromise(global) { if (!global.Promise) global.Promise = Promise; } function polyfillCollections(global) { if (!global.Map) global.Map = Map; } function polyfillString(String) { maybeAddFunctions(String.prototype, ['codePointAt', codePointAt, 'contains', contains, 'endsWith', endsWith, 'startsWith', startsWith, 'repeat', repeat]); maybeAddFunctions(String, ['fromCodePoint', fromCodePoint, 'raw', raw]); } function polyfillArray(Array, Symbol) { maybeAddFunctions(Array.prototype, ['entries', entries, 'keys', keys, 'values', values, 'fill', fill, 'find', find, 'findIndex', findIndex]); if (Symbol && Symbol.iterator) { Object.defineProperty(Array.prototype, Symbol.iterator, { value: values, configurable: true, enumerable: false, writable: true }); } } function polyfillObject(Object) { maybeAddFunctions(Object, ['assign', assign, 'is', is, 'mixin', mixin]); } function polyfill(global) { polyfillPromise(global); polyfillCollections(global); polyfillString(global.String); polyfillArray(global.Array, global.Symbol); polyfillObject(global.Object); } polyfill(this); var setupGlobals = $traceurRuntime.setupGlobals; $traceurRuntime.setupGlobals = function(global) { setupGlobals(global); polyfill(global); }; return {}; }); System.register("traceur-runtime@0.0.42/src/runtime/polyfill-import", [], function() { "use strict"; var __moduleName = "traceur-runtime@0.0.42/src/runtime/polyfill-import"; var $__16 = $traceurRuntime.assertObject(System.get("traceur-runtime@0.0.42/src/runtime/polyfills/polyfills")); return {}; }); System.get("traceur-runtime@0.0.42/src/runtime/polyfill-import" + ''); }).call(this,require("FWaASH"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"FWaASH":2}],4:[function(require,module,exports){ /*! * jQuery JavaScript Library v2.1.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-05-01T17:11Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // 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+ // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.1", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/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(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return 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 just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // 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 ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( 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] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; 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; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // 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 ( i === length ) { 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({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // 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, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android < 4.0, iOS < 6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // 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; }, // Support: Android<4.1 trim: 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 { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // 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 new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return 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 = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( 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; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // 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 ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v1.10.19 * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-04-18 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, 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; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // 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#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // 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 + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + 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" ), "bool": new RegExp( "^(?:" + booleans + ")$", "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" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint 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; } }; } 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 (jQuery #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 || !rbuggyQSA.test( selector )) ) { nid = old = 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 ) && testContext( 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 ); } /** * 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 keys = []; function cache( 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); } return cache; } /** * 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 { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~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 * @param {String} type */ 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 * @param {String} type */ 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 * @param {Function} fn */ 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]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== strundefined && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ 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 hasCompare, doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // 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 ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", function() { setDocument(); }, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", function() { setDocument(); }); } } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { 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 { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; 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; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( 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 msallowclip=''><option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowclip^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // 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 ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + 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 = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || 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 = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( 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 ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 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 doc; }; 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']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !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 ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; 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 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * 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 while ( (node = elem[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 (jQuery #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, attrHandle: {}, 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[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[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // 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( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : 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( typeof elem.className === "string" && 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 negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { 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; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // 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; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // 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 ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( 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 oldCache, outerCache, newCache = [ 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 ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { 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 multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } 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( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).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 ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (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; } } // 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, match /* 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 ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and 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" && support.getById && 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; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } 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 ) && testContext( 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 if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); 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; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ 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 : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // 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". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // 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 = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ 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 // Intentionally let the error be thrown if parseHTML is not present 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 ) { // 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 typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // 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 indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && 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 elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // 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( 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 // 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; }, // 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 = []; firingLength = 0; 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 ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; 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 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[ tuple[ 0 ] + "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 = 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 ? 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(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // 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; } // 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.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } 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 ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = 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 < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // 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 = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { 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 data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( 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 data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", 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 ); }); }, 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 = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( 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 ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // #11217 - WebKit loses check when the name is after the checked attribute // Support: Windows Web Apps (WWA) // `name` and `type` need .setAttribute for WWA input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE9-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * 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 handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( 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 !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // 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 if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } 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; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( 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; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = 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 ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; 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 = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === 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( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( 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; elem[ type ](); 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, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( 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 i, matches, sel, handleObj, 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 process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( 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; }, // 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // 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 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, 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: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { 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 = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; 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.defaultPrevented === undefined && // Support: Android < 4.0 src.returnValue === false ? 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 && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, 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; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } 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" ) { // ( 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 ); }); }, 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 ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !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 ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws 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 || fragment.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; } // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; 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( fragment.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 ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { 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 ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function 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'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (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 !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.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; }; var // 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]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, 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[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 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.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 && ( 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"; } 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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( 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.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; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": 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": "cssFloat" }, // 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 null and NaN values aren't set. See: #7116 if ( value == null || value !== 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 specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !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 ) { style[ name ] = value; } } 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 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, 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; } }); 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 rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? 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.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, 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" ] ); } } ); // 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; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, 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 ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); 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; } } } }; // Support: IE9 // 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.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 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 ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // 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; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // 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 IE9-10 do 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 display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // 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; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } 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; } } } 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; } } jQuery.map( props, createTween, animation ); 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 ); } 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 ); } } }); 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.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, or finishing resolves immediately if ( empty || data_priv.get( 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 = data_priv.get( 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 = data_priv.get( 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.stop ) { hooks.stop.call( this, true ); } // 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; }); } }); 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 ); }; }); // 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.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; 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 ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; 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 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.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 ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // 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; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, 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 === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, 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( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !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; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, 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 ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; 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( 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 + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( 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 + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } 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 ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( 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 ? "" : data_priv.get( 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; } }); var rreturn = /\r/g; jQuery.fn.extend({ 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; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).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 ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, 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 ]; // IE6-9 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 ( 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 optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion 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.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, 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 ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* 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( 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 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 ); } return target; } /* Handles responses to an ajax request: * - 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; // 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 * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else 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.unshift( tmp[ 1 ] ); } 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 }; } } } } } } return { state: "success", data: response }; } 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", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": 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 transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // 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 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 (prefilters might expect it) // 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( 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 += ( 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_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + 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; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // 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 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.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; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); 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 }); }; }); // 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._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; 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 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.firstElementChild ) { elem = elem.firstElementChild; } 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(); } }); 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.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; 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 ); } } // 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, "+" ); }; 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 || !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(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // 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 crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // 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, 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 += ( 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"; } }); // 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 jQuery.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 && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); 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; }; jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // 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({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 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 !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its 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 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 || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // 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 jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, 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; } } ); }); // 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 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 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 ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via 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. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); },{}],5:[function(require,module,exports){ (function (global){ //! moment.js //! version : 2.8.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = '2.8.1', // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for locale config files locales = {}, // extra moment internal properties (plugins register props here) momentProperties = [], // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 parseTokenOrdinal = /\d{1,2}/, //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.localeData().monthsShort(this, format); }, MMMM : function (format) { return this.localeData().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.localeData().weekdaysMin(this, format); }, ddd : function (format) { return this.localeData().weekdaysShort(this, format); }, dddd : function (format) { return this.localeData().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.localeData().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.localeData().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, deprecations = {}, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error('Implement me'); } } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function printMsg(msg) { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn("Deprecation warning: " + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { printMsg(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } function deprecateSimple(name, msg) { if (!deprecations[name]) { printMsg(msg); deprecations[name] = true; } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Locale() { } // Moment prototype object function Moment(config, skipOverflow) { if (skipOverflow !== false) { checkOverflow(config); } copyConfig(this, config); this._d = new Date(+config._d); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = moment.localeData(); this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty('toString')) { a.toString = b.toString; } if (b.hasOwnProperty('valueOf')) { a.valueOf = b.valueOf; } return a; } function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = makeAs(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period)."); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = moment.duration(val, period); addOrSubtractDurationFromMoment(this, dur, direction); return this; }; } function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment._locale[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment._locale, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; if (!locales[name] && hasModule) { try { oldLocale = moment.locale(); require('./locale/' + name); // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales moment.locale(oldLocale); } catch (e) { } } return locales[name]; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Locale ************************************/ extend(Locale.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), months : function (m) { return this._months[m.month()]; }, _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace('%d', number); }, _ordinal : '%d', preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return config._locale._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return parseTokenOrdinal; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); return a; } } function timezoneMinutesFromString(string) { string = string || ''; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = config._locale.monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt(input, 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = config._locale.isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be "T" or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += 'Z'; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function makeDateFromInput(config) { var input = config._i, matched; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if ((matched = aspNetJsonRegex.exec(input)) !== null) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromConfig(config); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(posNegDuration, withoutSuffix, locale) { var duration = moment.duration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), years = round(duration.as('y')), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days < relativeTimeThresholds.d && ['dd', days] || months === 1 && ['M'] || months < relativeTimeThresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = +posNegDuration > 0; args[4] = locale; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; config._locale = config._locale || moment.localeData(config._l); if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (moment.isMoment(input)) { return new Moment(input, true); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, locale, strict) { var c; if (typeof(locale) === "boolean") { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = locale; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i); } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, locale, strict) { var c; if (typeof(locale) === "boolean") { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, diffRes; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(moment(duration.from), moment(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (moment.isDuration(input) && input.hasOwnProperty('_locale')) { ret._locale = input._locale; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function (threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } if (limit === undefined) { return relativeTimeThresholds[threshold]; } relativeTimeThresholds[threshold] = limit; return true; }; moment.lang = deprecate( "moment.lang is deprecated. Use moment.locale instead.", function (key, value) { return moment.locale(key, value); } ); // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. moment.locale = function (key, values) { var data; if (key) { if (typeof(values) !== "undefined") { data = moment.defineLocale(key, values); } else { data = moment.localeData(key); } if (data) { moment.duration._locale = moment._locale = data; } } return moment._locale._abbr; }; moment.defineLocale = function (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale moment.locale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } }; moment.langData = deprecate( "moment.langData is deprecated. Use moment.localeData instead.", function (key) { return moment.localeData(key); } ); // returns locale data moment.localeData = function (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return moment._locale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && obj.hasOwnProperty('_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().locale('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function (keepLocalTime) { return this.zone(0, keepLocalTime); }, local : function (keepLocalTime) { if (this._isUTC) { this.zone(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.add(this._d.getTimezoneOffset(), 'm'); } } return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.localeData().postformat(output); }, add : createAdder(1, 'add'), subtract : createAdder(-1, 'subtract'), diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } }, month : makeAccessor('Month', true), startOf : function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = units || 'ms'; return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); }, min: deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = this._d.getTimezoneOffset(); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.subtract(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? 'UTC' : ''; }, zoneName : function () { return this._isUTC ? 'Coordinated Universal Time' : ''; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); }, week : function (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); }, weekday : function (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. locale : function (key) { if (key === undefined) { return this._locale._abbr; } else { this._locale = moment.localeData(key); return this; } }, lang : deprecate( "moment().lang() is deprecated. Use moment().localeData() instead.", function (key) { if (key === undefined) { return this.localeData(); } else { this._locale = moment.localeData(key); return this; } } ), localeData : function () { return this._locale; } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absRound(years / 4) - // absRound(years / 100) + absRound(years / 400); return years * 146097 / 400; } extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); // Accurately convert days to years, assume start from year 0. years = absRound(daysToYears(days)); days -= absRound(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absRound(days / 30); days %= 30; // 12 months -> 1 year years += absRound(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; }, abs : function () { this._milliseconds = Math.abs(this._milliseconds); this._days = Math.abs(this._days); this._months = Math.abs(this._months); this._data.milliseconds = Math.abs(this._data.milliseconds); this._data.seconds = Math.abs(this._data.seconds); this._data.minutes = Math.abs(this._data.minutes); this._data.hours = Math.abs(this._data.hours); this._data.months = Math.abs(this._data.months); this._data.years = Math.abs(this._data.years); return this; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var output = relativeTime(this, !withSuffix, this.localeData()); if (withSuffix) { output = this.localeData().pastFuture(+this, output); } return this.localeData().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { var days, months; units = normalizeUnits(units); days = this._days + this._milliseconds / 864e5; if (units === 'month' || units === 'year') { months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { days += yearsToDays(this._months / 12); switch (units) { case 'week': return days / 7; case 'day': return days; case 'hour': return days * 24; case 'minute': return days * 24 * 60; case 'second': return days * 24 * 60 * 60; case 'millisecond': return days * 24 * 60 * 60 * 1000; default: throw new Error('Unknown unit ' + units); } } }, lang : moment.fn.lang, locale : moment.fn.locale, toIsoString : deprecate( "toIsoString() is deprecated. Please use toISOString() instead " + "(notice the capitals)", function () { return this.toISOString(); } ), toISOString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); }, localeData : function () { return this._locale; } }); function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationGetter(i.toLowerCase()); } } moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; moment.duration.fn.asSeconds = function () { return this.as('s'); }; moment.duration.fn.asMinutes = function () { return this.as('m'); }; moment.duration.fn.asHours = function () { return this.as('h'); }; moment.duration.fn.asDays = function () { return this.as('d'); }; moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; moment.duration.fn.asMonths = function () { return this.as('M'); }; moment.duration.fn.asYears = function () { return this.as('y'); }; /************************************ Default Locale ************************************/ // Set default locale, other locale will inherit from English. moment.locale('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LOCALES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( 'Accessing Moment through the global scope is ' + 'deprecated, and will be removed in an upcoming ' + 'release.', moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (typeof define === 'function' && define.amd) { define('moment', function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }); makeGlobal(true); } else { makeGlobal(); } }).call(this); }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],6:[function(require,module,exports){ // Underscore.js 1.6.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Establish the object that gets returned to break out of a loop iteration. var breaker = {}; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeForEach = ArrayProto.forEach, nativeMap = ArrayProto.map, nativeReduce = ArrayProto.reduce, nativeReduceRight = ArrayProto.reduceRight, nativeFilter = ArrayProto.filter, nativeEvery = ArrayProto.every, nativeSome = ArrayProto.some, nativeIndexOf = ArrayProto.indexOf, nativeLastIndexOf = ArrayProto.lastIndexOf, nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object via a string identifier, // for Closure Compiler "advanced" mode. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.6.0'; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles objects with the built-in `forEach`, arrays, and raw objects. // Delegates to **ECMAScript 5**'s native `forEach` if available. var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return obj; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, length = obj.length; i < length; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) return; } } else { var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; } } return obj; }; // Return the results of applying the iterator to each element. // Delegates to **ECMAScript 5**'s native `map` if available. _.map = _.collect = function(obj, iterator, context) { var results = []; if (obj == null) return results; if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); each(obj, function(value, index, list) { results.push(iterator.call(context, value, index, list)); }); return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduce && obj.reduce === nativeReduce) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); } each(obj, function(value, index, list) { if (!initial) { memo = value; initial = true; } else { memo = iterator.call(context, memo, value, index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // The right-associative version of reduce, also known as `foldr`. // Delegates to **ECMAScript 5**'s native `reduceRight` if available. _.reduceRight = _.foldr = function(obj, iterator, memo, context) { var initial = arguments.length > 2; if (obj == null) obj = []; if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { if (context) iterator = _.bind(iterator, context); return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); } var length = obj.length; if (length !== +length) { var keys = _.keys(obj); length = keys.length; } each(obj, function(value, index, list) { index = keys ? keys[--length] : --length; if (!initial) { memo = obj[index]; initial = true; } else { memo = iterator.call(context, memo, obj[index], index, list); } }); if (!initial) throw new TypeError(reduceError); return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; any(obj, function(value, index, list) { if (predicate.call(context, value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Delegates to **ECMAScript 5**'s native `filter` if available. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context); each(obj, function(value, index, list) { if (predicate.call(context, value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, function(value, index, list) { return !predicate.call(context, value, index, list); }, context); }; // Determine whether all of the elements match a truth test. // Delegates to **ECMAScript 5**'s native `every` if available. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate || (predicate = _.identity); var result = true; if (obj == null) return result; if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context); each(obj, function(value, index, list) { if (!(result = result && predicate.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if at least one element in the object matches a truth test. // Delegates to **ECMAScript 5**'s native `some` if available. // Aliased as `any`. var any = _.some = _.any = function(obj, predicate, context) { predicate || (predicate = _.identity); var result = false; if (obj == null) return result; if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context); each(obj, function(value, index, list) { if (result || (result = predicate.call(context, value, index, list))) return breaker; }); return !!result; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; return any(obj, function(value) { return value === target; }); }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element or (element-based computation). // Can't optimize arrays of integers longer than 65,535 elements. // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) _.max = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.max.apply(Math, obj); } var result = -Infinity, lastComputed = -Infinity; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; if (computed > lastComputed) { result = value; lastComputed = computed; } }); return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iterator, context) { if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { return Math.min.apply(Math, obj); } var result = Infinity, lastComputed = Infinity; each(obj, function(value, index, list) { var computed = iterator ? iterator.call(context, value, index, list) : value; if (computed < lastComputed) { result = value; lastComputed = computed; } }); return result; }; // Shuffle an array, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { var rand; var index = 0; var shuffled = []; each(obj, function(value) { rand = _.random(index++); shuffled[index - 1] = shuffled[rand]; shuffled[rand] = value; }); return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // An internal function to generate lookup iterators. var lookupIterator = function(value) { if (value == null) return _.identity; if (_.isFunction(value)) return value; return _.property(value); }; // Sort the object's values by a criterion produced by an iterator. _.sortBy = function(obj, iterator, context) { iterator = lookupIterator(iterator); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iterator.call(context, value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iterator, context) { var result = {}; iterator = lookupIterator(iterator); each(obj, function(value, index) { var key = iterator.call(context, value, index, obj); behavior(result, key, value); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, key, value) { _.has(result, key) ? result[key].push(value) : result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, key, value) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, key) { _.has(result, key) ? result[key]++ : result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iterator, context) { iterator = lookupIterator(iterator); var value = iterator.call(context, obj); var low = 0, high = array.length; while (low < high) { var mid = (low + high) >>> 1; iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if ((n == null) || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, (n == null) || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } each(input, function(value) { if (_.isArray(value) || _.isArguments(value)) { shallow ? push.apply(output, value) : flatten(value, shallow, output); } else { output.push(value); } }); return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Split an array into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(array, predicate) { var pass = [], fail = []; each(array, function(elem) { (predicate(elem) ? pass : fail).push(elem); }); return [pass, fail]; }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iterator, context) { if (_.isFunction(isSorted)) { context = iterator; iterator = isSorted; isSorted = false; } var initial = iterator ? _.map(array, iterator, context) : array; var results = []; var seen = []; each(initial, function(value, index) { if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { seen.push(value); results.push(array[index]); } }); return results; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(_.flatten(arguments, true)); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { return _.contains(other, item); }); }); }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { var length = _.max(_.pluck(arguments, 'length').concat(0)); var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, '' + i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), // we need this function. Return the position of the first occurrence of an // item in an array, or -1 if the item is not included in the array. // Delegates to **ECMAScript 5**'s native `indexOf` if available. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); for (; i < length; i++) if (array[i] === item) return i; return -1; }; // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var hasIndex = from != null; if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); } var i = (hasIndex ? from : array.length); while (i--) if (array[i] === item) return i; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = arguments[2] || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var idx = 0; var range = new Array(length); while(idx < length) { range[idx++] = start; start += step; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError; args = slice.call(arguments, 2); return bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); ctor.prototype = func.prototype; var self = new ctor; ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) return result; return self; }; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var funcs = slice.call(arguments, 1); if (funcs.length === 0) throw new Error('bindAll must be passed function names'); each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memo = {}; hasher || (hasher = _.identity); return function() { var key = hasher.apply(this, arguments); return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); }; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; options || (options = {}); var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) { timeout = setTimeout(later, wait); } if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = function(func) { var ran = false, memo; return function() { if (ran) return memo; ran = true; memo = func.apply(this, arguments); func = null; return memo; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var funcs = arguments; return function() { var args = arguments; for (var i = funcs.length - 1; i >= 0; i--) { args = [funcs[i].apply(this, args)]; } return args[0]; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = new Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = new Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { obj[prop] = source[prop]; } } }); return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); each(keys, function(key) { if (key in obj) copy[key] = obj[key]; }); return copy; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj) { var copy = {}; var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); for (var key in obj) { if (!_.contains(keys, key)) copy[key] = obj[key]; } return copy; }; // Fill in a given object with default properties. _.defaults = function(obj) { each(slice.call(arguments, 1), function(source) { if (source) { for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } }); return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a == 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className != toString.call(b)) return false; switch (className) { // Strings, numbers, dates, and booleans are compared by value. case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return a == String(b); case '[object Number]': // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for // other numeric values. return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a == +b; // RegExps are compared by their source patterns and flags. case '[object RegExp]': return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] == a) return bStack[length] == b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor)) && ('constructor' in a && 'constructor' in b)) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size = 0, result = true; // Recursively compare objects and arrays. if (className == '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size == b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. for (var key in a) { if (_.has(a, key)) { // Count the expected number of properties. size++; // Deep compare each member. if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } // Ensure that both objects contain the same number of properties. if (result) { for (key in b) { if (_.has(b, key) && !(size--)) break; } result = !size; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { return obj === Object(obj); }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) == '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return !!(obj && _.has(obj, 'callee')); }; } // Optimize `isFunction` if appropriate. if (typeof (/./) !== 'function') { _.isFunction = function(obj) { return typeof obj === 'function'; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj != +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iterators. _.identity = function(value) { return value; }; _.constant = function(value) { return function () { return value; }; }; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { return function(obj) { if (obj === attrs) return true; //avoid comparing an object to itself. for (var key in attrs) { if (attrs[key] !== obj[key]) return false; } return true; } }; // Run a function **n** times. _.times = function(n, iterator, context) { var accum = Array(Math.max(0, n)); for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var entityMap = { escape: { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;' } }; entityMap.unescape = _.invert(entityMap.escape); // Regexes containing the keys and values listed immediately above. var entityRegexes = { escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') }; // Functions for escaping and unescaping strings to/from HTML interpolation. _.each(['escape', 'unescape'], function(method) { _[method] = function(string) { if (string == null) return ''; return ('' + string).replace(entityRegexes[method], function(match) { return entityMap[method][match]; }); }; }); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? value.call(object) : value; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. _.template = function(text, data, settings) { var render; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = new RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset) .replace(escaper, function(match) { return '\\' + escapes[match]; }); if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } index = offset + match.length; return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n"; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } if (data) return render(data, _); var template = function(data) { return render.call(this, data, _); }; // Provide the compiled function source as a convenience for precompilation. template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; return template; }; // Add a "chain" function, which will delegate to the wrapper. _.chain = function(obj) { return _(obj).chain(); }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); _.extend(_.prototype, { // Start chaining a wrapped Underscore object. chain: function() { this._chain = true; return this; }, // Extracts the result from a wrapped and chained object. value: function() { return this._wrapped; } }); // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }).call(this); },{}],7:[function(require,module,exports){ var EventEmitter = require('events').EventEmitter var inherits = require('inherits') var shimvis = true var change = null var hidden = null module.exports = Visibility if (typeof document.hidden !== 'undefined') { hidden = 'hidden' change = 'visibilitychange' } else if (typeof document.mozHidden !== 'undefined') { hidden = 'mozHidden' change = 'mozvisibilitychange' } else if (typeof document.webkitHidden !== 'undefined') { hidden = 'webkitHidden' change = 'webkitvisibilitychange' } else if (typeof document.webkitHidden !== 'undefined') { hidden = 'webkitHidden' change = 'webkitvisibilitychange' } inherits(Visibility, EventEmitter) function Visibility() { if (!(this instanceof Visibility)) return new Visibility var self = this EventEmitter.call(this) this.supported = !!hidden if (this.supported) { document.addEventListener(change, function() { var visible = !document[hidden] self.emit('change', visible) self.emit(visible ? 'show' : 'hide') }, false) } else { document.addEventListener('focusout', function() { self.emit('change', false) self.emit('hide') shimvis = false }, false) document.addEventListener('focusin', function() { self.emit('change', true) self.emit('show') shimvis = true }, false) } window.addEventListener('unload', function() { self.emit('exit') }, false) } Visibility.prototype.hidden = function() { return this.supported ? !!document[hidden] : !shimvis } Visibility.prototype.visible = function() { return this.supported ? !document[hidden] : shimvis } },{"events":1,"inherits":8}],8:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],"base_object":[function(require,module,exports){ module.exports=require('2HNVgz'); },{}],"2HNVgz":[function(require,module,exports){ "use strict"; var _ = require('underscore'); var extend = require('./utils').extend; var Events = require('./events'); var pluginOptions = ['container']; var BaseObject = function BaseObject(options) { this.uniqueId = _.uniqueId('o'); options || (options = {}); _.extend(this, _.pick(options, pluginOptions)); if (this.initialize) { this.initialize.apply(this, arguments); } }; ($traceurRuntime.createClass)(BaseObject, {}, {}, Events); BaseObject.extend = extend; module.exports = BaseObject; },{"./events":11,"./utils":20,"underscore":6}],11:[function(require,module,exports){ (function (global){ "use strict"; var _ = require('underscore'); var Log = require('../plugins/log'); var slice = Array.prototype.slice; var Events = function Events() {}; ($traceurRuntime.createClass)(Events, { on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback, context: context, ctx: context || this }); return this; }, once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; events = this._events[name]; if (events) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, trigger: function(name) { var klass = arguments[arguments.length - 1]; if (global.DEBUG) { if (Log.BLACKLIST.indexOf(name) < 0) Log.info(klass, 'event ' + name + ' triggered'); } if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }, {}); var eventSplitter = /\s+/; var eventsApi = function(obj, action, name, rest) { if (!name) return true; if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = { listenTo: 'on', listenToOnce: 'once' }; _.each(listenMethods, function(implementation, method) { Events.prototype[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); module.exports = Events; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../plugins/log":45,"underscore":6}],12:[function(require,module,exports){ "use strict"; var _ = require('underscore'); module.exports = { 'media_control': _.template('<div class="media-control-layer" data-controls> <% var renderBar = function(name) { %> <div class="bar-container" data-<%= name %>> <div class="bar-background" data-<%= name %>> <div class="bar-fill-1" data-<%= name %>></div> <div class="bar-fill-2" data-<%= name %>></div> </div> <div class="bar-scrubber" data-<%= name %>> <div class="bar-scrubber-icon" data-<%= name %>></div> </div> </div> <% }; %> <% var renderDrawer = function(name, renderContent) { %> <div class="drawer-container" data-<%= name %>> <div class="drawer-icon-container" data-<%= name %>> <div class="drawer-icon media-control-icon" data-<%= name %>></div> <span class="drawer-text" data-<%= name %>></span> </div> <% renderContent(name); %> </div> <% }; %> <% var renderIndicator = function(name) { %> <div class="media-control-indicator" data-<%= name %>></div> <% }; %> <% var renderButton = function(name) { %> <button class="media-control-button media-control-icon" data-<%= name %>></button> <% }; %> <% var render = function(settings) { _.each(settings, function(setting) { if(setting === "seekbar") { renderBar(setting); } else if (setting === "volume") { renderDrawer(setting, renderBar); } else if (setting === "duration" || setting === "position") { renderIndicator(setting); } else { renderButton(setting); } }); }; %> <% if (settings.left && settings.left.length) { %> <div class="media-control-left-panel" data-media-control> <% render(settings.left); %> </div> <% } %> <% if (settings.right && settings.right.length) { %> <div class="media-control-right-panel" data-media-control> <% render(settings.right); %> </div> <% } %> <% if (settings.default && settings.default.length) { %> <div class="media-control-center-panel" data-media-control> <% render(settings.default); %> </div> <% } %></div>'), 'flash_vod': _.template(' <param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" disabled="disabled" tabindex="-1" enablecontextmenu="false" allowScriptAccess="always" quality="autohight" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="gpu" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'), 'hls': _.template(' <param name="movie" value="<%= swfPath %>?inline=1"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> <param name=FlashVars value="playbackId=<%= playbackId %>" /> <embed type="application/x-shockwave-flash" tabindex="1" enablecontextmenu="false" allowScriptAccess="always" quality="autohigh" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="transparent" swliveconnect="true" type="application/x-shockwave-flash" allowfullscreen="false" bgcolor="#000000" FlashVars="playbackId=<%= playbackId %>" src="<%= swfPath %>"> </embed>'), 'poster': _.template('<img class="poster-background" data-poster src="" /><div class="play-wrapper" data-poster> <span class="poster-icon play" data-poster /></div>'), 'spinner_loading': _.template('<div data-spinner-container class="spin-container1"> <div data-circle1></div> <div data-circle2></div> <div data-circle3></div> <div data-circle4></div></div><div data-spinner-container class="spin-container2"> <div data-circle1></div> <div data-circle2></div> <div data-circle3></div> <div data-circle4></div></div><div data-spinner-container class="spin-container3"> <div data-circle1></div> <div data-circle2></div> <div data-circle3></div> <div data-circle4></div></div>'), 'spinner_three_bounce': _.template('<div data-bounce1></div><div data-bounce2></div><div data-bounce3></div>'), 'watermark': _.template('<div data-watermark data-watermark-<%=position %>><img src="<%= imageUrl %>"></div>'), CSS: { 'container': '[data-container]{position:absolute;background-color:#000;height:100%;width:100%}', 'core': '[data-player] *{-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;margin:0;padding:0;border:0;font-style:normal;font-weight:400;text-align:center;font-size:100%;color:#000;font-family:"lucida grande",tahoma,verdana,arial,sans-serif;text-shadow:0 0 0;box-sizing:border-box}[data-player] * a,[data-player] * abbr,[data-player] * acronym,[data-player] * address,[data-player] * applet,[data-player] * article,[data-player] * aside,[data-player] * audio,[data-player] * b,[data-player] * big,[data-player] * blockquote,[data-player] * canvas,[data-player] * caption,[data-player] * center,[data-player] * cite,[data-player] * code,[data-player] * dd,[data-player] * del,[data-player] * details,[data-player] * dfn,[data-player] * div,[data-player] * dl,[data-player] * dt,[data-player] * em,[data-player] * embed,[data-player] * fieldset,[data-player] * figcaption,[data-player] * figure,[data-player] * footer,[data-player] * form,[data-player] * h1,[data-player] * h2,[data-player] * h3,[data-player] * h4,[data-player] * h5,[data-player] * h6,[data-player] * header,[data-player] * hgroup,[data-player] * i,[data-player] * iframe,[data-player] * img,[data-player] * ins,[data-player] * kbd,[data-player] * label,[data-player] * legend,[data-player] * li,[data-player] * mark,[data-player] * menu,[data-player] * nav,[data-player] * object,[data-player] * ol,[data-player] * output,[data-player] * p,[data-player] * pre,[data-player] * q,[data-player] * ruby,[data-player] * s,[data-player] * samp,[data-player] * section,[data-player] * small,[data-player] * span,[data-player] * strike,[data-player] * strong,[data-player] * sub,[data-player] * summary,[data-player] * sup,[data-player] * table,[data-player] * tbody,[data-player] * td,[data-player] * tfoot,[data-player] * th,[data-player] * thead,[data-player] * time,[data-player] * tr,[data-player] * tt,[data-player] * u,[data-player] * ul,[data-player] * var,[data-player] * video{margin:0;padding:0;border:0;font:inherit;font-size:100%;vertical-align:baseline}[data-player] * table{border-collapse:collapse;border-spacing:0}[data-player] * caption,[data-player] * td,[data-player] * th{text-align:left;font-weight:400;vertical-align:middle}[data-player] * blockquote,[data-player] * q{quotes:none}[data-player] * blockquote:after,[data-player] * blockquote:before,[data-player] * q:after,[data-player] * q:before{content:"";content:none}[data-player] * a img{border:none}[data-player]{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);transform:translate3d(0,0,0);position:relative;margin:0;height:594px;width:1055px;text-align:center;overflow:hidden}[data-player].fullscreen{width:100%;height:100%}[data-player].nocursor{cursor:none}', 'media_control': '@font-face{font-family:Player;src:url(assets/Player-Regular.eot);src:url(assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(assets/Player-Regular.ttf) format("truetype"),url(assets/Player-Regular.svg#player) format("svg")}.media-control[data-media-control]{position:absolute;background-color:rgba(2,2,2,.5);border-radius:0;bottom:0;left:0;right:0;margin-left:auto;margin-right:auto;max-width:100%;min-width:60%;height:40px;z-index:9999;-webkit-transition:all .4s ease-out;-moz-transition:all .4s ease-out;-ms-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.media-control[data-media-control] .media-control-icon{font-family:Player;font-weight:400;font-style:normal;font-size:26px;line-height:32px;letter-spacing:0;speak:none;color:#fff;vertical-align:middle;text-align:left;padding:0 6px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.media-control[data-media-control].media-control-hide{bottom:-40px}.media-control[data-media-control].media-control-hide .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls]{position:relative;top:10%;height:80%;vertical-align:middle}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-left-panel[data-media-control]{position:absolute;top:0;left:5px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-center-panel[data-media-control]{height:100%;text-align:center;line-height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-right-panel[data-media-control]{position:absolute;top:0;right:5px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button{background-color:transparent;border:0;margin:0 8px;cursor:pointer;display:inline-block}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button:focus{outline:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-play]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-pause]:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-stop]:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]{float:right;background-color:transparent;border:0;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-fullscreen]:before{content:"\\e006"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]{cursor:default;float:right;background-color:transparent;border:0;width:32px;height:100%;opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator]:before{content:"\\e007"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-hd-indicator].enabled{opacity:1}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].playing:before{content:"\\e002"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playpause].paused:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]{float:left;width:32px;height:100%}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop]:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].playing:before{content:"\\e003"}.media-control[data-media-control] .media-control-layer[data-controls] button.media-control-button[data-playstop].stopped:before{content:"\\e001"}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration],.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-position]{display:inline-block;font-size:13px;color:#fff;cursor:default;line-height:32px;position:relative}.media-control[data-media-control] .media-control-layer[data-controls] .media-control-indicator[data-duration]:before{content:"/";margin-right:3px}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar]{position:absolute;top:-20px;left:0;display:inline-block;vertical-align:middle;width:100%;height:32px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar]{width:100%;height:8px;position:relative;top:12px;background-color:#6f6f6f;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-1[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#bebebe;-webkit-transition:all .1s ease-out;-moz-transition:all .1s ease-out;-ms-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-background[data-seekbar] .bar-fill-2[data-seekbar]{position:absolute;top:0;left:0;width:0;height:100%;background-color:#fff;-webkit-transition:all .1s ease-out;-moz-transition:all .1s ease-out;-ms-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar]{position:absolute;top:6px;left:0;width:20px;height:20px;opacity:1;-webkit-transition:all .1s ease-out;-moz-transition:all .1s ease-out;-ms-transition:all .1s ease-out;-o-transition:all .1s ease-out;transition:all .1s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .bar-container[data-seekbar] .bar-scrubber[data-seekbar] .bar-scrubber-icon[data-seekbar]{position:absolute;left:3px;top:3px;width:14px;height:14px;border-radius:6px;border:1px solid #6f6f6f;background-color:#fff}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume]{float:right;display:inline-block;width:32px;height:32px;cursor:pointer}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume]{position:absolute;bottom:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]{background-color:transparent;border:0;width:32px;height:32px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume]:before{content:"\\e004"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .drawer-icon-container[data-volume] .drawer-icon[data-volume].muted:before{content:"\\e005"}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume]{width:32px;height:88px;position:absolute;bottom:40px;background:rgba(2,2,2,.5);border-radius:4px;-webkit-transition:all .2s ease-out;-moz-transition:all .2s ease-out;-ms-transition:all .2s ease-out;-o-transition:all .2s ease-out;transition:all .2s ease-out}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume].volume-bar-hide{opacity:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume]{margin-left:12px;background:#6f6f6f;border-radius:4px;width:8px;height:72px;position:relative;top:8px;overflow:hidden}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-background[data-volume] .bar-fill-1[data-volume]{position:absolute;bottom:0;background:#fff;width:100%;height:0}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume]{position:absolute;bottom:40%;left:6px;width:20px;height:20px}.media-control[data-media-control] .media-control-layer[data-controls] .drawer-container[data-volume] .bar-container[data-volume] .bar-scrubber[data-volume] .bar-scrubber-icon[data-volume]{position:absolute;left:4px;top:4px;width:12px;height:12px;border-radius:6px;border:1px solid #6f6f6f;background-color:#fff}', 'flash_vod': '[data-flash-vod]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'hls': '[data-hls]{position:absolute;height:100%;width:100%;background-color:#000;display:block;pointer-events:none}', 'html5_video': '[data-html5-video]{position:absolute;height:100%;width:100%;display:block}', 'pip': '.pip-loading[data-pip]{left:25px;top:15px;position:relative;float:left;z-index:3001;color:#fff}.pip-transition[data-pip]{-webkit-transition:all .4s ease-out;-moz-transition:all .4s ease-out;-ms-transition:all .4s ease-out;-o-transition:all .4s ease-out;transition:all .4s ease-out}.master-container[data-pip]{cursor:default;width:100%;height:100%;font-size:100%;position:absolute;bottom:0;right:0;border:none}.pip-container[data-pip]{cursor:pointer;width:24%;height:24%;font-size:24%;z-index:2000;position:absolute;right:23px;bottom:23px;border-width:2px;border-radius:3px;border-style:solid;border-color:rgba(255,255,255,.25);background-clip:padding-box;-webkit-background-clip:padding-box}.pip-container[data-pip].over-media-control{bottom:63px}', 'poster': '@font-face{font-family:Player;src:url(assets/Player-Regular.eot);src:url(assets/Player-Regular.eot?#iefix) format("embedded-opentype"),url(assets/Player-Regular.ttf) format("truetype"),url(assets/Player-Regular.svg#player) format("svg")}.player-poster[data-poster]{cursor:pointer;position:absolute;height:100%;width:100%;z-index:998;top:0}.player-poster[data-poster] .poster-background[data-poster]{width:100%;height:100%}.player-poster[data-poster] .play-wrapper[data-poster]{position:absolute;overflow:hidden;width:100%;height:20%;line-height:100%;font-size:20%;top:50%;margin-top:-5%;text-align:center}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]{font-family:Player;font-weight:400;font-style:normal;line-height:1;letter-spacing:0;speak:none;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;color:#fff;opacity:.75}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster].play[data-poster]:before{content:"\\e001"}.player-poster[data-poster] .play-wrapper[data-poster] .poster-icon[data-poster]:hover{opacity:1}', 'spinner_loading': 'div[data-spinner]{width:50px;height:50px;position:relative;margin-left:auto;margin-right:auto;right:0;left:0;z-index:999;top:45%}.spin-container1>div,.spin-container2>div,.spin-container3>div{width:13px;height:13px;background-color:#fff;border-radius:100%;position:absolute;-webkit-animation:bouncedelay 1.2s infinite ease-in-out;animation:bouncedelay 1.2s infinite ease-in-out;-webkit-animation-fill-mode:both;animation-fill-mode:both}[data-spinner] [data-spinner-container]{position:absolute;width:100%;height:100%}.spin-container2{-webkit-transform:rotateZ(45deg);transform:rotateZ(45deg)}.spin-container3{-webkit-transform:rotateZ(90deg);transform:rotateZ(90deg)}[data-circle1]{top:0;left:0}[data-circle2]{top:0;right:0}[data-circle3]{right:0;bottom:0}[data-circle4]{left:0;bottom:0}.spin-container2 [data-circle1]{-webkit-animation-delay:-1.1s;animation-delay:-1.1s}.spin-container3 [data-circle1]{-webkit-animation-delay:-1s;animation-delay:-1s}.spin-container1 [data-circle2]{-webkit-animation-delay:-.9s;animation-delay:-.9s}.spin-container2 [data-circle2]{-webkit-animation-delay:-.8s;animation-delay:-.8s}.spin-container3 [data-circle2]{-webkit-animation-delay:-.7s;animation-delay:-.7s}.spin-container1 [data-circle3]{-webkit-animation-delay:-.6s;animation-delay:-.6s}.spin-container2 [data-circle3]{-webkit-animation-delay:-.5s;animation-delay:-.5s}.spin-container3 [data-circle3]{-webkit-animation-delay:-.4s;animation-delay:-.4s}.spin-container1 [data-circle4]{-webkit-animation-delay:-.3s;animation-delay:-.3s}.spin-container2 [data-circle4]{-webkit-animation-delay:-.2s;animation-delay:-.2s}.spin-container3 [data-circle4]{-webkit-animation-delay:-.1s;animation-delay:-.1s}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0)}40%{-webkit-transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{transform:scale(0);-webkit-transform:scale(0)}40%{transform:scale(1);-webkit-transform:scale(1)}}', 'spinner_three_bounce': '.spinner-three-bounce[data-spinner]{position:absolute;margin:0 auto;width:70px;text-align:center;z-index:10;top:47%;left:0;right:0}.spinner-three-bounce[data-spinner]>div{width:18px;height:18px;background-color:#FFF;border-radius:100%;display:inline-block;-webkit-animation:bouncedelay 1.4s infinite ease-in-out;-moz-animation:bouncedelay 1.4s infinite ease-in-out;-o-animation:bouncedelay 1.4s infinite ease-in-out;animation:bouncedelay 1.4s infinite ease-in-out;-webkit-animation-fill-mode:both;-moz-animation-fill-mode:both;-o-animation-fill-mode:both;animation-fill-mode:both}.spinner-three-bounce[data-spinner] [data-bounce1]{-webkit-animation-delay:-.32s;animation-delay:-.32s}.spinner-three-bounce[data-spinner] [data-bounce2]{-webkit-animation-delay:-.16s;animation-delay:-.16s}@-webkit-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}@-moz-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}@-ms-keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}@keyframes bouncedelay{0%,100%,80%{-webkit-transform:scale(0);-moz-transform:scale(0);transform:scale(0)}40%{-webkit-transform:scale(1);-moz-transform:scale(1);transform:scale(1)}}', 'watermark': '[data-watermark]{position:absolute;margin:100px auto 0;width:70px;text-align:center;z-index:10}[data-watermark-bottom-left]{bottom:10px;left:10px}[data-watermark-bottom-right]{bottom:10px;right:42px}[data-watermark-top-left]{top:-95px;left:10px}[data-watermark-top-right]{top:-95px;right:37px}' } }; },{"underscore":6}],13:[function(require,module,exports){ "use strict"; var PluginMixin = require('./plugin_mixin'); var BaseObject = require('./base_object'); var Plugin = BaseObject.extend(PluginMixin).extend({}); module.exports = Plugin; },{"./base_object":"2HNVgz","./plugin_mixin":14}],14:[function(require,module,exports){ "use strict"; var PluginMixin = { initialize: function() { this.bindEvents(); }, enable: function() { this.bindEvents(); }, disable: function() { this.stopListening(); } }; module.exports = PluginMixin; },{}],15:[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var JST = require('./jst'); var Styler = {getStyleFor: function(name, options) { options = options || {}; return $('<style></style>').html(_.template(JST.CSS[name])(options)); }}; module.exports = Styler; },{"./jst":12,"jquery":4,"underscore":6}],"ui_object":[function(require,module,exports){ module.exports=require('8lqCAT'); },{}],"8lqCAT":[function(require,module,exports){ "use strict"; var $ = require('jquery'); var _ = require('underscore'); var extend = require('./utils').extend; var BaseObject = require('./base_object'); var delegateEventSplitter = /^(\S+)\s*(.*)$/; var viewOptions = ['container', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; var UIObject = function UIObject(options) { this.cid = _.uniqueId('c'); this._ensureElement(); $traceurRuntime.superCall(this, $UIObject.prototype, "constructor", [options]); this.delegateEvents(); }; var $UIObject = UIObject; ($traceurRuntime.createClass)(UIObject, { get tagName() { return 'div'; }, $: function(selector) { return this.$el.find(selector); }, initialize: function() {}, render: function() { return this; }, remove: function() { this.$el.remove(); this.stopListening(); return this; }, setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof $ ? element : $(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = $('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }, {}, BaseObject); UIObject.extend = extend; module.exports = UIObject; },{"./base_object":"2HNVgz","./utils":20,"jquery":4,"underscore":6}],"Z7u8cr":[function(require,module,exports){ "use strict"; var PluginMixin = require('./plugin_mixin'); var UIObject = require('./ui_object'); var extend = require('./utils').extend; var _ = require('underscore'); var UIPlugin = function UIPlugin() { $traceurRuntime.defaultSuperCall(this, $UIPlugin.prototype, arguments); }; var $UIPlugin = UIPlugin; ($traceurRuntime.createClass)(UIPlugin, { get type() { return 'ui'; }, enable: function() { $UIPlugin.super('enable').call(this); this.$el.show(); }, disable: function() { $UIPlugin.super('disable').call(this); this.$el.hide(); }, bindEvents: function() {} }, {}, UIObject); _.extend(UIPlugin.prototype, PluginMixin); UIPlugin.extend = extend; module.exports = UIPlugin; },{"./plugin_mixin":14,"./ui_object":"8lqCAT","./utils":20,"underscore":6}],"ui_plugin":[function(require,module,exports){ module.exports=require('Z7u8cr'); },{}],20:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var Moment = require('moment'); var extend = function(protoProps, staticProps) { var parent = this; var child; if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function() { return parent.apply(this, arguments); }; } _.extend(child, parent, staticProps); var Surrogate = function() { this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate(); if (protoProps) _.extend(child.prototype, protoProps); child.__super__ = parent.prototype; child.super = function(name) { return parent.prototype[name]; }; child.prototype.getClass = function() { return child; }; return child; }; var zeroPad = function(number, size) { return (new Array(size + 1 - number.toString().length)).join('0') + number; }; var formatTime = function(time, showMillis) { var duration = Moment.duration(time * 1000); var str = zeroPad(duration.seconds(), 2); if (duration.hours()) { str = zeroPad(duration.minutes(), 2) + ':' + str; str = duration.hours() + ':' + str; } else { str = duration.minutes() + ':' + str; } if (showMillis) str += '.' + duration.milliseconds(); return str; }; var Fullscreen = { isFullscreen: function() { return document.webkitIsFullScreen || document.mozFullScreen; }, requestFullscreen: function(el) { if (el.requestFullscreen) { el.requestFullscreen(); } else if (el.webkitRequestFullscreen) { el.webkitRequestFullscreen(); } else if (el.mozRequestFullScreen) { el.mozRequestFullScreen(); } else if (el.msRequestFullscreen) { el.msRequestFullscreen(); } }, cancelFullscreen: function() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } } }; module.exports = { extend: extend, zeroPad: zeroPad, formatTime: formatTime, Fullscreen: Fullscreen }; },{"moment":5,"underscore":6}],"browser":[function(require,module,exports){ module.exports=require('195Wj5'); },{}],"195Wj5":[function(require,module,exports){ "use strict"; var Browser = function Browser() {}; ($traceurRuntime.createClass)(Browser, {}, {}); Browser.isSafari = (!!navigator.userAgent.match(/safari/i) && navigator.userAgent.indexOf('Chrome') === -1); Browser.isChrome = !!(navigator.userAgent.match(/chrome/i)); Browser.isFirefox = !!(navigator.userAgent.match(/firefox/i)); Browser.isLegacyIE = !!(window.ActiveXObject); module.exports = Browser; },{}],23:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var _ = require('underscore'); var Container = function Container() { $traceurRuntime.defaultSuperCall(this, $Container.prototype, arguments); }; var $Container = Container; ($traceurRuntime.createClass)(Container, { get name() { return 'Container'; }, get attributes() { return {'data-container': ''}; }, get events() { return {'click': 'clicked'}; }, initialize: function(options) { this.playback = options.playback; this.settings = this.playback.settings; this.listenTo(this.playback, 'playback:progress', this.progress); this.listenTo(this.playback, 'playback:timeupdate', this.timeUpdated); this.listenTo(this.playback, 'playback:ready', this.ready); this.listenTo(this.playback, 'playback:buffering', this.buffering); this.listenTo(this.playback, 'playback:bufferfull', this.bufferfull); this.listenTo(this.playback, 'playback:settingsupdate', this.settingsUpdate); this.listenTo(this.playback, 'playback:loadedmetadata', this.loadedMetadata); this.listenTo(this.playback, 'playback:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.playback, 'playback:mediacontrol:disable', this.disableMediaControl); this.listenTo(this.playback, 'playback:mediacontrol:enable', this.enableMediaControl); this.listenTo(this.playback, 'playback:ended', this.ended); this.listenTo(this.playback, 'playback:play', this.playing); this.isReady = false; this.mediaControlDisabled = false; this.plugins = [this.playback]; }, with: function(klass) { _.extend(this, klass); return this; }, statsAdd: function(metric) { this.trigger('container:stats:add', metric); }, statsReport: function(metrics) { this.trigger('container:stats:report', metrics); }, destroy: function() { this.trigger('container:destroyed', this, this.name); this.playback.destroy(); this.$el.remove(); }, setStyle: function(style) { this.$el.css(style); }, animate: function(style, duration) { return this.$el.animate(style, duration).promise(); }, ready: function() { this.isReady = true; this.trigger('container:ready', this.name); }, isPlaying: function() { return this.playback.isPlaying(); }, error: function(errorObj) { this.trigger('container:error', errorObj, this.name); }, loadedMetadata: function(duration) { this.trigger('container:loadedmetadata', duration); }, timeUpdated: function(position, duration) { this.trigger('container:timeupdate', position, duration, this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger('container:progress', startPosition, endPosition, duration, this.name); }, playing: function() { this.trigger('container:play', this.name); }, play: function() { this.playback.play(); }, stop: function() { this.trigger('container:stop', this.name); this.playback.stop(); }, pause: function() { this.trigger('container:pause', this.name); this.playback.pause(); }, ended: function() { this.trigger('container:ended', this, this.name); }, clicked: function() { this.trigger('container:click', this, this.name); }, setCurrentTime: function(time) { this.trigger('container:seek', time, this.name); this.playback.seek(time); }, setVolume: function(value) { this.trigger('container:volume', value, this.name); this.playback.volume(value); }, requestFullscreen: function() { this.trigger('container:fullscreen', this.name); }, buffering: function() { this.trigger('container:state:buffering', this.name); }, bufferfull: function() { this.trigger('container:state:bufferfull', this.name); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find(function(plugin) { return plugin.name === name; }); }, settingsUpdate: function() { this.settings = this.playback.settings; this.trigger('container:settingsupdate'); }, highDefinitionUpdate: function() { this.trigger('container:highdefinitionupdate'); }, isHighDefinitionInUse: function() { return this.playback.isHighDefinition(); }, disableMediaControl: function() { this.mediaControlDisabled = true; this.trigger('container:mediacontrol:disable'); }, enableMediaControl: function() { this.mediaControlDisabled = false; this.trigger('container:mediacontrol:enable'); }, render: function() { var style = Styler.getStyleFor('container'); this.$el.append(style); this.$el.append(this.playback.render().el); return this; } }, {}, UIObject); ; module.exports = Container; },{"../../base/styler":15,"../../base/ui_object":"8lqCAT","underscore":6}],24:[function(require,module,exports){ "use strict"; module.exports = require('./container'); },{"./container":23}],25:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Container = require('../container'); var $ = require('jquery'); var ContainerFactory = function ContainerFactory() { $traceurRuntime.defaultSuperCall(this, $ContainerFactory.prototype, arguments); }; var $ContainerFactory = ContainerFactory; ($traceurRuntime.createClass)(ContainerFactory, { initialize: function(params, loader) { this.params = params; this.loader = loader; }, createContainers: function() { return $.Deferred(function(promise) { promise.resolve(_.map(this.params.sources, function(source) { return this.createContainer(source); }, this)); }.bind(this)); }, findPlaybackPlugin: function(source) { return _.find(this.loader.playbackPlugins, (function(p) { return p.canPlay("" + source); }), this); }, createContainer: function(source) { var playbackPlugin = this.findPlaybackPlugin(source); var params = _.extend({}, this.params, { src: source, autoPlay: !!this.params.autoPlay }); var playback = new playbackPlugin(params); var container = new Container({playback: playback}); var defer = $.Deferred(); defer.promise(container); this.addContainerPlugins(container, source); this.listenToOnce(container, 'container:ready', (function() { return defer.resolve(container); })); return container; }, addContainerPlugins: function(container, source) { _.each(this.loader.containerPlugins, function(plugin) { var params = _.extend(this.params, { container: container, src: source }); container.addPlugin(new plugin(params)); }, this); } }, {}, BaseObject); ; module.exports = ContainerFactory; },{"../../base/base_object":"2HNVgz","../container":24,"jquery":4,"underscore":6}],26:[function(require,module,exports){ "use strict"; module.exports = require('./container_factory'); },{"./container_factory":25}],27:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var UIObject = require('../../base/ui_object'); var ContainerFactory = require('../container_factory'); var Fullscreen = require('../../base/utils').Fullscreen; var Loader = require('../loader'); var Styler = require('../../base/styler'); var MediaControl = require('../media_control'); var Core = function Core() { $traceurRuntime.defaultSuperCall(this, $Core.prototype, arguments); }; var $Core = Core; ($traceurRuntime.createClass)(Core, { get events() { return { 'webkitfullscreenchange': 'exit', 'mousemove': 'showMediaControl', 'mouseleave': 'hideMediaControl' }; }, get attributes() { return {'data-player': ''}; }, initialize: function(params) { var $__0 = this; this.defer = $.Deferred(); this.defer.promise(this); this.plugins = []; this.containers = []; this.params = params; this.params.displayType || (this.params.displayType = 'pip'); this.parentElement = params.parentElement; this.loader = new Loader(params); this.containerFactory = new ContainerFactory(params, this.loader); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })).then((function(containers) { return $__0.resolveOnContainersReady(containers); })); this.updateSize(); document.addEventListener('mozfullscreenchange', (function() { return $__0.exit(); })); $(window).resize((function() { return $__0.updateSize(); })); }, updateSize: function() { if (Fullscreen.isFullscreen()) { this.$el.addClass('fullscreen'); this.$el.removeAttr('style'); } else { var width = 0; var height = 0; if (this.params.stretchWidth && this.params.stretchHeight && this.params.stretchWidth <= window.innerWidth && this.params.stretchHeight <= (window.innerHeight * 0.73)) { width = this.params.stretchWidth; height = this.params.stretchHeight; } else { width = this.params.width || width; height = this.params.height || height; } if (width > 0) { this.$el.css({width: width}); } if (height > 0) { this.$el.css({height: height}); } this.$el.removeClass('fullscreen'); } }, resolveOnContainersReady: function(containers) { var $__0 = this; $.when.apply($, containers).done((function() { return $__0.defer.resolve($__0); })); }, addPlugin: function(plugin) { this.plugins.push(plugin); }, hasPlugin: function(name) { return !!this.getPlugin(name); }, getPlugin: function(name) { return _(this.plugins).find((function(plugin) { return plugin.name === name; })); }, load: function(sources) { var $__0 = this; sources = _.isString(sources) ? [sources] : sources; _(this.containers).each((function(container) { return container.destroy(); })); this.containerFactory.params = _(this.params).extend({sources: sources}); this.containerFactory.createContainers().then((function(containers) { return $__0.setupContainers(containers); })); }, destroy: function() { _(this.containers).each((function(container) { return container.destroy(); })); this.$el.remove(); }, exit: function() { this.updateSize(); this.mediaControl.show(); }, setMediaControlContainer: function(container) { this.mediaControl.setContainer(container); this.mediaControl.render(); }, disableMediaControl: function() { this.mediaControl.disable(); this.$el.removeClass('nocursor'); }, enableMediaControl: function() { this.mediaControl.enable(); }, removeContainer: function(container) { console.log('container being removed'); this.stopListening(container); this.containers = _.without(this.containers, container); }, appendContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.el.appendChild(container.render().el); this.containers.push(container); }, prependContainer: function(container) { this.listenTo(container, 'container:destroyed', this.removeContainer); this.$el.append(container.render().el); this.containers.unshift(container); }, setupContainers: function(containers) { _.map(containers, this.appendContainer, this); this.setupMediaControl(this.getCurrentContainer()); this.render(); this.$el.appendTo(this.parentElement); return containers; }, createContainer: function(source) { var container = this.containerFactory.createContainer(source); this.appendContainer(container); return container; }, setupMediaControl: function(container) { var params = _.extend({container: container}, this.params); if (this.mediaControl) { this.mediaControl.setContainer(container); } else { this.mediaControl = new MediaControl(_.extend({container: container}, this.params)); this.listenTo(this.mediaControl, 'mediacontrol:fullscreen', this.toggleFullscreen); this.listenTo(this.mediaControl, 'mediacontrol:show', this.onMediaControlShow.bind(this, true)); this.listenTo(this.mediaControl, 'mediacontrol:hide', this.onMediaControlShow.bind(this, false)); } }, getCurrentContainer: function() { return this.containers[0]; }, toggleFullscreen: function() { if (!Fullscreen.isFullscreen()) { Fullscreen.requestFullscreen(this.el); this.$el.addClass('fullscreen'); } else { Fullscreen.cancelFullscreen(); this.$el.removeClass('fullscreen nocursor'); } this.mediaControl.show(); }, showMediaControl: function(event) { this.mediaControl.show(event); }, hideMediaControl: function(event) { this.mediaControl.hide(event); }, onMediaControlShow: function(showing) { if (showing) this.$el.removeClass('nocursor'); else if (Fullscreen.isFullscreen()) this.$el.addClass('nocursor'); }, render: function() { var $__0 = this; var style = Styler.getStyleFor('core'); this.$el.append(style); this.$el.append(this.mediaControl.render().el); this.$el.ready((function() { $__0.params.width = $__0.params.width || $__0.$el.width(); $__0.params.height = $__0.params.height || $__0.$el.height(); $__0.updateSize(); })); return this; } }, {}, UIObject); module.exports = Core; },{"../../base/styler":15,"../../base/ui_object":"8lqCAT","../../base/utils":20,"../container_factory":26,"../loader":31,"../media_control":33,"jquery":4,"underscore":6}],28:[function(require,module,exports){ "use strict"; module.exports = require('./core'); },{"./core":27}],29:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var BaseObject = require('../../base/base_object'); var Core = require('../core'); var CoreFactory = BaseObject.extend({ initialize: function(player, loader) { this.player = player; this.params = player.params; this.loader = loader; }, create: function() { this.core = new Core(this.params); this.core.then(this.addCorePlugins.bind(this)); return this.core; }, addCorePlugins: function() { _.each(this.loader.globalPlugins, function(Plugin) { var plugin = new Plugin(this.core); this.core.addPlugin(plugin); this.setupExternalInterface(plugin); }, this); return this.core; }, setupExternalInterface: function(plugin) { _.each(plugin.getExternalInterface(), function(value, key) { this.player[key] = value.bind(plugin); }, this); } }); module.exports = CoreFactory; },{"../../base/base_object":"2HNVgz","../core":28,"underscore":6}],30:[function(require,module,exports){ "use strict"; module.exports = require('./core_factory'); },{"./core_factory":29}],31:[function(require,module,exports){ "use strict"; module.exports = require('./loader'); },{"./loader":32}],32:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var _ = require('underscore'); var HTML5VideoPlaybackPlugin = require('../../playbacks/html5_video'); var FlashVideoPlaybackPlugin = require('../../playbacks/flash_vod'); var HTML5AudioPlaybackPlugin = require('../../playbacks/html5_audio'); var HLSVideoPlaybackPlugin = require('../../playbacks/hls'); var SpinnerThreeBouncePlugin = require('../../plugins/spinner_three_bounce'); var StatsPlugin = require('../../plugins/stats'); var WaterMarkPlugin = require('../../plugins/watermark'); var PosterPlugin = require('../../plugins/poster'); var Sequence = require('../../plugins/sequence'); var Loader = BaseObject.extend({ displayPlugins: {'sequence': Sequence}, initialize: function(params) { this.params = params; this.playbackPlugins = [FlashVideoPlaybackPlugin, HTML5VideoPlaybackPlugin, HTML5AudioPlaybackPlugin, HLSVideoPlaybackPlugin]; this.containerPlugins = [SpinnerThreeBouncePlugin, WaterMarkPlugin, PosterPlugin, StatsPlugin]; this.globalPlugins = [this.displayPlugins[this.params.displayType]]; this.addExternalPlugins(params.plugins || []); }, addExternalPlugins: function(plugins) { if (plugins.playback) { this.playbackPlugins = plugins.playback.concat(this.playbackPlugins); } if (plugins.container) { this.containerPlugins = plugins.container.concat(this.containerPlugins); } if (plugins.core) { this.globalPlugins = plugins.core.concat(this.globalPlugins); } }, getPlugin: function(name) { return _.find(_.union(this.containerPlugins, this.playbackPlugins, this.globalPlugins), function(plugin) { return plugin.prototype.name === name; }); } }); module.exports = Loader; },{"../../base/base_object":"2HNVgz","../../playbacks/flash_vod":38,"../../playbacks/hls":40,"../../playbacks/html5_audio":42,"../../playbacks/html5_video":44,"../../plugins/poster":47,"../../plugins/sequence":49,"../../plugins/spinner_three_bounce":52,"../../plugins/stats":54,"../../plugins/watermark":56,"underscore":6}],33:[function(require,module,exports){ "use strict"; module.exports = require('./media_control'); },{"./media_control":34}],34:[function(require,module,exports){ "use strict"; var _ = require('underscore'); var $ = require('jquery'); var JST = require('../../base/jst'); var Styler = require('../../base/styler'); var UIObject = require('../../base/ui_object'); var Utils = require('../../base/utils'); var MediaControl = function MediaControl() { $traceurRuntime.defaultSuperCall(this, $MediaControl.prototype, arguments); }; var $MediaControl = MediaControl; ($traceurRuntime.createClass)(MediaControl, { get name() { return 'MediaControl'; }, get attributes() { return { class: 'media-control', 'data-media-control': '' }; }, get events() { return { 'click [data-play]': 'play', 'click [data-pause]': 'pause', 'click [data-playpause]': 'togglePlayPause', 'click [data-stop]': 'stop', 'click [data-playstop]': 'togglePlayStop', 'click [data-fullscreen]': 'toggleFullscreen', 'click [data-seekbar]': 'seek', 'click .bar-background[data-volume]': 'volume', 'click .drawer-icon[data-volume]': 'toggleMute', 'mouseover .drawer-container[data-volume]': 'showVolumeBar', 'mouseleave .drawer-container[data-volume]': 'hideVolumeBar', 'mousedown .bar-scrubber[data-seekbar]': 'startSeekDrag', 'mousedown .bar-scrubber[data-volume]': 'startVolumeDrag', 'mouseenter .media-control-layer[data-controls]': 'setKeepVisible', 'mouseleave .media-control-layer[data-controls]': 'resetKeepVisible' }; }, get template() { return JST.media_control; }, initialize: function(params) { var $__0 = this; this.params = params; this.container = params.container; this.keepVisible = false; this.addEventListeners(); this.defaultSettings = { left: ['play', 'stop', 'pause'], right: ['volume'], default: ['position', 'seekbar', 'duration'] }; this.disabled = false; if (this.container.mediaControlDisabled || this.params.chromeless) this.disable(); this.currentVolume = 100; $(document).bind('mouseup', (function(event) { return $__0.stopDrag(event); })); $(document).bind('mousemove', (function(event) { return $__0.updateDrag(event); })); }, addEventListeners: function() { this.listenTo(this.container, 'container:play', this.changeTogglePlay); this.listenTo(this.container, 'container:playing', this.changeTogglePlay); this.listenTo(this.container, 'container:timeupdate', this.updateSeekBar); this.listenTo(this.container, 'container:progress', this.updateProgressBar); this.listenTo(this.container, 'container:settingsupdate', this.settingsUpdate); this.listenTo(this.container, 'container:highdefinitionupdate', this.highDefinitionUpdate); this.listenTo(this.container, 'container:mediacontrol:disable', this.disable); this.listenTo(this.container, 'container:mediacontrol:enable', this.enable); this.listenTo(this.container, 'container:ended', this.ended); }, disable: function() { this.disabled = true; this.hide(); this.$el.hide(); }, enable: function() { if (this.params.chromeless) return; this.disabled = false; this.show(); }, play: function() { this.container.play(); }, pause: function() { this.container.pause(); }, stop: function() { this.container.stop(); }, changeTogglePlay: function() { if (this.container.isPlaying()) { this.$playPauseToggle.removeClass('paused').addClass('playing'); this.$playStopToggle.removeClass('stopped').addClass('playing'); } else { this.$playPauseToggle.removeClass('playing').addClass('paused'); this.$playStopToggle.removeClass('playing').addClass('stopped'); } }, onKeyDown: function(event) { if (event.keyCode === 32) this.togglePlayPause(); }, togglePlayPause: function() { if (this.container.isPlaying()) { this.container.pause(); } else { this.container.play(); } this.changeTogglePlay(); }, togglePlayStop: function() { if (this.container.isPlaying()) { this.container.stop(); } else { this.container.play(); } this.changeTogglePlay(); }, startSeekDrag: function(event) { this.draggingSeekBar = true; if (event) { event.preventDefault(); } }, startVolumeDrag: function(event) { this.draggingVolumeBar = true; if (event) { event.preventDefault(); } }, stopDrag: function(event) { if (this.draggingSeekBar) { this.seek(event); } this.draggingSeekBar = false; this.draggingVolumeBar = false; }, updateDrag: function(event) { if (event) { event.preventDefault(); } if (this.draggingSeekBar) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.setSeekPercentage(pos); } else if (this.draggingVolumeBar) { this.volume(event); } }, volume: function(event) { var offsetY = event.pageY - this.$volumeBarContainer.offset().top; this.currentVolume = (1 - (offsetY / this.$volumeBarContainer.height())) * 100; this.currentVolume = Math.min(100, Math.max(this.currentVolume, 0)); this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); }, toggleMute: function() { if (!!this.mute) { this.container.setVolume(this.currentVolume); this.setVolumeLevel(this.currentVolume); this.mute = false; } else { this.container.setVolume(0); this.setVolumeLevel(0); this.mute = true; } }, toggleFullscreen: function() { this.trigger('mediacontrol:fullscreen', this.name); }, setContainer: function(container) { this.stopListening(this.container); this.container = container; this.changeTogglePlay(); this.addEventListeners(); this.settingsUpdate(); this.container.setVolume(this.currentVolume); if (this.container.mediaControlDisabled) this.disable(); }, showVolumeBar: function() { if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.$volumeBarContainer.show(); this.$volumeBarContainer.removeClass('volume-bar-hide'); }, hideVolumeBar: function() { var $__0 = this; if (!this.$volumeBarContainer) return; if (this.hideVolumeId) { clearTimeout(this.hideVolumeId); } this.hideVolumeId = setTimeout((function() { $__0.$volumeBarContainer.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', (function() { $__0.$volumeBarContainer.off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend'); $__0.$volumeBarContainer.hide(); })); $__0.$volumeBarContainer.addClass('volume-bar-hide'); }), 750); }, ended: function() { this.changeTogglePlay(); }, updateProgressBar: function(startPosition, endPosition, duration) { var loadedStart = startPosition / duration * 100; var loadedEnd = endPosition / duration * 100; this.$seekBarLoaded.css({ left: loadedStart + '%', width: (loadedEnd - loadedStart) + '%' }); }, updateSeekBar: function(position, duration) { if (this.draggingSeekBar) return; var seekbarValue = (100 / duration) * position; this.setSeekPercentage(seekbarValue); this.$('[data-position]').html(Utils.formatTime(position)); this.$('[data-duration]').html(Utils.formatTime(duration)); }, seek: function(event) { var offsetX = event.pageX - this.$seekBarContainer.offset().left; var pos = offsetX / this.$seekBarContainer.width() * 100; pos = Math.min(100, Math.max(pos, 0)); this.container.setCurrentTime(pos); }, setKeepVisible: function() { this.keepVisible = true; }, resetKeepVisible: function() { this.keepVisible = false; }, show: function(event) { var $__0 = this; if (this.disabled) return; var timeout = 2000; if (!event || (event.clientX !== this.lastMouseX && event.clientY !== this.lastMouseY) || navigator.userAgent.match(/firefox/i)) { if (this.hideId) { clearTimeout(this.hideId); } this.$el.show(); this.trigger('mediacontrol:show', this.name); this.$el.removeClass('media-control-hide'); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (event) { this.lastMouseX = event.clientX; this.lastMouseY = event.clientY; } } }, hide: function() { var $__0 = this; var timeout = 2000; if (this.hideId) { clearTimeout(this.hideId); } if (this.keepVisible || this.draggingVolumeBar || this.draggingSeekBar) { this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); } else { if (this.$volumeBarContainer) { this.$volumeBarContainer.hide(); } this.trigger('mediacontrol:hide', this.name); this.$el.addClass('media-control-hide'); } }, settingsUpdate: function() { this.render(); }, highDefinitionUpdate: function() { var $element = this.$el.find('button[data-hd]'); $element.removeClass('enabled'); if (this.container.isHighDefinitionInUse()) { $element.addClass('enabled'); } }, createCachedElements: function() { this.$playPauseToggle = this.$el.find('button.media-control-button[data-playpause]'); this.$playStopToggle = this.$el.find('button.media-control-button[data-playstop]'); this.$seekBarContainer = this.$el.find('.bar-container[data-seekbar]'); this.$seekBarLoaded = this.$el.find('.bar-fill-1[data-seekbar]'); this.$seekBarPosition = this.$el.find('.bar-fill-2[data-seekbar]'); this.$seekBarScrubber = this.$el.find('.bar-scrubber[data-seekbar]'); this.$volumeBarContainer = this.$el.find('.bar-container[data-volume]'); this.$volumeBarBackground = this.$el.find('.bar-background[data-volume]'); this.$volumeBarFill = this.$el.find('.bar-fill-1[data-volume]'); this.$volumeBarScrubber = this.$el.find('.bar-scrubber[data-volume]'); this.$volumeIcon = this.$el.find('.drawer-icon[data-volume]'); }, setVolumeLevel: function(value) { var containerHeight = this.$volumeBarContainer.height(); var barHeight = this.$volumeBarBackground.height(); var offset = (containerHeight - barHeight) / 2.0; var pos = barHeight * value / 100.0 - this.$volumeBarScrubber.height() / 2.0 + offset; this.$volumeBarFill.css({height: value + '%'}); this.$volumeBarScrubber.css({bottom: pos}); if (value > 0) { this.$volumeIcon.removeClass('muted'); } else { this.$volumeIcon.addClass('muted'); } }, setSeekPercentage: function(value) { var pos = this.$seekBarContainer.width() * value / 100.0 - this.$seekBarScrubber.width() / 2.0; this.$seekBarPosition.css({width: value + '%'}); this.$seekBarScrubber.css({left: pos}); }, bindKeyEvents: function() { var $__0 = this; if (this.keydownHandlerFn) { $(document).unbind('keydown', this.keydownHandlerFn); } else { this.keydownHandlerFn = (function(event) { return $__0.onKeyDown(event); }); } if (this.$playPauseToggle.length > 0) { $(document).bind('keydown', this.keydownHandlerFn); } }, render: function() { var $__0 = this; var timeout = 1000; var style = Styler.getStyleFor('media_control'); var settings = _.isEmpty(this.container.settings) ? this.defaultSettings : this.container.settings; this.$el.html(this.template({settings: settings})); this.$el.append(style); this.createCachedElements(); this.$playPauseToggle.addClass('paused'); this.$playStopToggle.addClass('stopped'); this.currentVolume = this.currentVolume || 100; this.$volumeBarContainer.hide(); if (this.params.autoPlay) { this.togglePlayPause(); this.togglePlayStop(); } this.changeTogglePlay(); this.hideId = setTimeout((function() { return $__0.hide(); }), timeout); if (this.disabled) this.hide(); this.$el.ready((function() { $__0.setVolumeLevel($__0.currentVolume); $__0.setSeekPercentage(0); $__0.bindKeyEvents(); })); return this; } }, {}, UIObject); module.exports = MediaControl; },{"../../base/jst":12,"../../base/styler":15,"../../base/ui_object":"8lqCAT","../../base/utils":20,"jquery":4,"underscore":6}],35:[function(require,module,exports){ "use strict"; var Events = require('../base/events'); var events = new Events(); var Mediator = function Mediator() {}; ($traceurRuntime.createClass)(Mediator, {}, {}); Mediator.on = function(name, callback, context) { events.on(name, callback, context); return; }; Mediator.once = function(name, callback, context) { events.once(name, callback, context); return; }; Mediator.off = function(name, callback, context) { events.off(name, callback, context); return; }; Mediator.trigger = function(name, opts) { events.trigger(name, opts); return; }; Mediator.stopListening = function(obj, name, callback) { events.stopListening(obj, name, callback); return; }; module.exports = Mediator; },{"../base/events":11}],36:[function(require,module,exports){ (function (global){ "use strict"; var BaseObject = require('./base/base_object'); var CoreFactory = require('./components/core_factory'); var Loader = require('./components/loader'); var Mediator = require('./components/mediator'); var Player = function Player() { $traceurRuntime.defaultSuperCall(this, $Player.prototype, arguments); }; var $Player = Player; ($traceurRuntime.createClass)(Player, { initialize: function(params) { window.p = this; params.displayType || (params.displayType = 'pip'); this.params = params; this.loader = new Loader(this.params); this.coreFactory = new CoreFactory(this, this.loader); }, attachTo: function(element) { this.params.parentElement = element; this.core = this.coreFactory.create(); }, load: function(sources) { this.core.load(sources); }, destroy: function() { this.core.destroy(); } }, {}, BaseObject); global.DEBUG = false; window.WP3 = { Player: Player, Mediator: Mediator }; module.exports = window.WP3; }).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./base/base_object":"2HNVgz","./components/core_factory":30,"./components/loader":31,"./components/mediator":35}],37:[function(require,module,exports){ "use strict"; var UIObject = require('../../base/ui_object'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var Mediator = require('../../components/mediator'); var _ = require('underscore'); var $ = require('jquery'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-flash-vod=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="gpu"> <param name="tabindex" value="1"> </object>'; var FlashVOD = function FlashVOD() { $traceurRuntime.defaultSuperCall(this, $FlashVOD.prototype, arguments); }; var $FlashVOD = FlashVOD; ($traceurRuntime.createClass)(FlashVOD, { get name() { return 'flash_vod'; }, get tagName() { return 'object'; }, get template() { return JST.flash_vod; }, initialize: function(options) { $traceurRuntime.superCall(this, $FlashVOD.prototype, "initialize", [options]); this.src = options.src; this.swfPath = options.swfPath || "assets/Player.swf"; this.autoPlay = options.autoPlay; this.settings = { left: ["playpause", "position", "duration"], default: ["seekbar"], right: ["fullscreen", "volume"] }; this.isReady = false; this.addListeners(); }, safe: function(fn) { if (this.el.getState && this.el.getDuration && this.el.getPosition && this.el.getBytesLoaded && this.el.getBytesTotal) { return fn.apply(this); } }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.isReady = true; this.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.autoPlay && this.play(); $('<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" />').insertAfter(this.$el); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-flash-vod', ''); this.setElement($el[0]); }, getPlaybackType: function() { return "vod"; }, updateTime: function() { var $__0 = this; this.safe((function() { $__0.trigger('playback:timeupdate', $__0.el.getPosition(), $__0.el.getDuration(), $__0.name); })); }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':progress', (function() { return $__0.progress(); })); Mediator.on(this.uniqueId + ':timeupdate', (function() { return $__0.updateTime(); })); Mediator.on(this.uniqueId + ':statechanged', (function() { return $__0.checkState(); })); Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); }, stopListening: function() { $traceurRuntime.superCall(this, $FlashVOD.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':progress'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':statechanged'); }, checkState: function() { var $__0 = this; this.safe((function() { if ($__0.currentState !== "PLAYING_BUFFERING" && $__0.el.getState() === "PLAYING_BUFFERING") { $__0.trigger('playback:buffering', $__0.name); $__0.currentState = "PLAYING_BUFFERING"; } else if ($__0.currentState === "PLAYING_BUFFERING" && $__0.el.getState() === "PLAYING") { $__0.trigger('playback:bufferfull', $__0.name); $__0.currentState = "PLAYING"; } else if ($__0.el.getState() === "IDLE") { $__0.currentState = "IDLE"; } else if ($__0.el.getState() === "ENDED") { $__0.trigger('playback:ended', $__0.name); $__0.trigger('playback:timeupdate', 0, $__0.el.getDuration(), $__0.name); $__0.currentState = "ENDED"; } })); }, progress: function() { var $__0 = this; this.safe((function() { if ($__0.currentState !== "IDLE" && $__0.currentState !== "ENDED") { $__0.trigger('playback:progress', 0, $__0.el.getBytesLoaded(), $__0.el.getBytesTotal(), $__0.name); } })); }, firstPlay: function() { var $__0 = this; this.safe((function() { $__0.currentState = "PLAYING"; $__0.el.playerPlay($__0.src); })); }, play: function() { var $__0 = this; this.safe((function() { if ($__0.el.getState() === 'PAUSED') { $__0.currentState = "PLAYING"; $__0.el.playerResume(); } else if ($__0.el.getState() !== 'PLAYING') { $__0.firstPlay(); } $__0.trigger('playback:play', $__0.name); })); }, volume: function(value) { var $__0 = this; this.safe((function() { $__0.el.playerVolume(value); })); }, pause: function() { var $__0 = this; this.safe((function() { $__0.currentState = "PAUSED"; $__0.el.playerPause(); })); }, stop: function() { var $__0 = this; this.safe((function() { $__0.el.playerStop(); $__0.trigger('playback:timeupdate', 0, $__0.name); })); }, isPlaying: function() { return !!(this.isReady && this.currentState == "PLAYING"); }, getDuration: function() { var $__0 = this; return this.safe((function() { return $__0.el.getDuration(); })); }, seek: function(time) { var $__0 = this; this.safe((function() { var seekTo = $__0.el.getDuration() * (time / 100); $__0.el.playerSeek(seekTo); $__0.trigger('playback:timeupdate', seekTo, $__0.el.getDuration(), $__0.name); if ($__0.currentState == "PAUSED") { $__0.pause(); } })); }, destroy: function() { clearInterval(this.bootstrapId); this.stopListening(); this.$el.remove(); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath }))); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); if (navigator.userAgent.match(/firefox/i)) { this.setupFirefox(); } else if (window.ActiveXObject) { this.setupIE(); } this.$el.append(style); return this; } }, {}, UIObject); FlashVOD.canPlay = function(resource) { if (navigator.userAgent.match(/firefox/i) || window.ActiveXObject) { return _.isString(resource) && !!resource.match(/(.*).(mp4|mov|f4v|3gpp|3gp)/); } else { return _.isString(resource) && !!resource.match(/(.*).(mov|f4v|3gpp|3gp)/); } }; module.exports = FlashVOD; },{"../../base/jst":12,"../../base/styler":15,"../../base/ui_object":"8lqCAT","../../components/mediator":35,"jquery":4,"underscore":6}],38:[function(require,module,exports){ "use strict"; module.exports = require('./flash_vod'); },{"./flash_vod":37}],39:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var _ = require("underscore"); var Mediator = require('../../components/mediator'); var Visibility = require('visibility'); var Browser = require('../../components/browser'); var objectIE = '<object type="application/x-shockwave-flash" id="<%= cid %>" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" data-hls=""><param name="movie" value="<%= swfPath %>"> <param name="quality" value="autohigh"> <param name="swliveconnect" value="true"> <param name="allowScriptAccess" value="always"> <param name="bgcolor" value="#001122"> <param name="allowFullScreen" value="false"> <param name="wmode" value="transparent"> <param name="tabindex" value="1"> </object>'; var HLS = function HLS() { $traceurRuntime.defaultSuperCall(this, $HLS.prototype, arguments); }; var $HLS = HLS; ($traceurRuntime.createClass)(HLS, { get name() { return 'hls'; }, get tagName() { return 'object'; }, get template() { return JST.hls; }, get attributes() { return { 'data-hls': '', 'type': 'application/x-shockwave-flash' }; }, initialize: function(options) { $traceurRuntime.superCall(this, $HLS.prototype, "initialize", [options]); this.src = options.src; this.swfPath = options.swfPath || "assets/HLSPlayer.swf"; this.setupVisibility(); this.highDefinition = false; this.autoPlay = options.autoPlay; this.defaultSettings = { left: ["playstop"], default: [], right: ["fullscreen", "volume", "hd"] }; this.settings = _.extend({}, this.defaultSettings); this.addListeners(); }, setupVisibility: function() { var $__0 = this; this.visibility = new Visibility(); this.visibility.on('show', (function() { return $__0.visibleCallback(); })); this.visibility.on('hide', (function() { return $__0.hiddenCallback(); })); }, addListeners: function() { var $__0 = this; Mediator.on(this.uniqueId + ':flashready', (function() { return $__0.bootstrap(); })); Mediator.on(this.uniqueId + ':timeupdate', (function(params) { return $__0.updateTime(params); })); Mediator.on(this.uniqueId + ':playbackstate', (function(params) { return $__0.setPlaybackState(params); })); Mediator.on(this.uniqueId + ':highdefinition', (function(params) { return $__0.updateHighDefinition(params); })); }, stopListening: function() { $traceurRuntime.superCall(this, $HLS.prototype, "stopListening", []); Mediator.off(this.uniqueId + ':flashready'); Mediator.off(this.uniqueId + ':timeupdate'); Mediator.off(this.uniqueId + ':playbackstate'); Mediator.off(this.uniqueId + ':highdefinition'); }, safe: function(fn) { if (this.el.globoGetState && this.el.globoGetDuration && this.el.globoGetPosition && this.el.globoPlayerSmoothSetLevel && this.el.globoPlayerSetflushLiveURLCache) { return fn.apply(this); } }, hiddenCallback: function() { var $__0 = this; this.hiddenId = this.safe((function() { return setTimeout((function() { return $__0.el.globoPlayerSmoothSetLevel(0); }), 10000); })); }, visibleCallback: function() { var $__0 = this; this.safe((function() { if ($__0.hiddenId) { clearTimeout($__0.hiddenId); } if (!$__0.el.globoGetAutoLevel()) { $__0.el.globoPlayerSmoothSetLevel(-1); } })); }, bootstrap: function() { this.el.width = "100%"; this.el.height = "100%"; this.trigger('playback:ready', this.name); this.currentState = "IDLE"; this.el.globoPlayerSetflushLiveURLCache(true); this.autoPlay && this.play(); }, updateHighDefinition: function(params) { this.highDefinition = params.isHD; this.trigger('playback:highdefinitionupdate'); }, updateTime: function(params) { var $__0 = this; return this.safe((function() { var previousDvrEnabled = $__0.dvrEnabled; $__0.dvrEnabled = ($__0.playbackType === 'live' && params.duration > 240); var duration = $__0.getDuration(); if ($__0.playbackType === 'live') { var position = $__0.el.globoGetPosition(); if (position >= duration) { position = duration; } $__0.trigger('playback:timeupdate', position, duration, $__0.name); } else { $__0.trigger('playback:timeupdate', $__0.el.globoGetPosition(), duration, $__0.name); } if ($__0.dvrEnabled != previousDvrEnabled) { $__0.updateSettings(); } })); }, play: function() { var $__0 = this; this.safe((function() { if ($__0.el.currentState === 'PAUSED') { $__0.el.globoPlayerResume(); } else { $__0.firstPlay(); } $__0.trigger('playback:play', $__0.name); })); }, getPlaybackType: function() { if (this.playbackType) return this.playbackType; return null; }, getCurrentBitrate: function() { return this.safe(function() { var currentLevel = this.getLevels()[this.el.globoGetLevel()]; return currentLevel.bitrate; }); }, getLastProgramDate: function() { var programDate = this.el.globoGetLastProgramDate(); return programDate - 1.08e+7; }, isHighDefinition: function() { return this.highDefinition; }, getLevels: function() { var $__0 = this; return this.safe((function() { if (!$__0.levels || $__0.levels.length === 0) { $__0.levels = $__0.el.globoGetLevels(); } return $__0.levels; })); }, setPlaybackState: function(params) { if (params.state === "PLAYING_BUFFERING" && this.el.globoGetbufferLength() < 1 && this.currentState !== "PLAYING_BUFFERING") { this.trigger('playback:buffering', this.name); } else if (params.state === "PLAYING" && this.currentState === "PLAYING_BUFFERING") { this.trigger('playback:bufferfull', this.name); } else if (params.state === "IDLE") { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.globoGetDuration(), this.name); } this.currentState = params.state; this.updatePlaybackType(); }, updatePlaybackType: function() { var $__0 = this; this.safe((function() { if (!$__0.playbackType) { $__0.playbackType = $__0.el.globoGetType(); if ($__0.playbackType) { $__0.playbackType = $__0.playbackType.toLowerCase(); $__0.updateSettings(); } } })); }, firstPlay: function() { var $__0 = this; this.safe((function() { $__0.el.globoPlayerLoad($__0.src); $__0.el.globoPlayerPlay(); })); }, volume: function(value) { var $__0 = this; this.safe((function() { $__0.el.globoPlayerVolume(value); })); }, pause: function() { var $__0 = this; this.safe((function() { $__0.el.globoPlayerPause(); })); }, stop: function() { var $__0 = this; this.safe((function() { $__0.el.globoPlayerStop(); $__0.trigger('playback:timeupdate', 0, $__0.name); })); }, isPlaying: function() { var $__0 = this; return this.safe((function() { if ($__0.currentState) return !!($__0.currentState.match(/playing/i)); return false; })); }, getDuration: function() { var $__0 = this; return this.safe((function() { var duration = $__0.el.globoGetDuration(); if ($__0.playbackType === 'live') { duration = duration - 10; } return duration; })); }, seek: function(time) { var $__0 = this; this.safe((function() { if (time < 0) { $__0.el.globoPlayerSeek(time); } else { var duration = $__0.getDuration(); time = duration * time / 100; if ($__0.playbackType === 'live' && duration - time < 2) time = -1; $__0.el.globoPlayerSeek(time); } })); }, timeUpdate: function(time, duration) { this.trigger('playback:timeupdate', time, duration, this.name); }, destroy: function() { this.stopListening(); this.$el.remove(); }, setupFirefox: function() { var $el = this.$('embed'); $el.attr('data-hls', ''); this.setElement($el[0]); }, setupIE: function() { this.setElement($(_.template(objectIE)({ cid: this.cid, swfPath: this.swfPath }))); }, updateSettings: function() { this.settings = _.extend({}, this.defaultSettings); if (this.playbackType === "vod" || this.dvrEnabled) { this.settings.left = ["playpause", "position", "duration"]; this.settings.default = ["seekbar"]; } this.trigger('playback:settingsupdate', this.name); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.html(this.template({ cid: this.cid, swfPath: this.swfPath, playbackId: this.uniqueId })); this.$el.append(style); this.el.id = this.cid; if (Browser.isFirefox) { this.setupFirefox(); } else if (Browser.isLegacyIE) { this.setupIE(); } return this; } }, {}, UIPlugin); HLS.canPlay = function(resource) { return !!resource.match(/^http(.*).m3u8/); }; module.exports = HLS; },{"../../base/jst":12,"../../base/styler":15,"../../base/ui_plugin":"Z7u8cr","../../components/browser":"195Wj5","../../components/mediator":35,"underscore":6,"visibility":7}],40:[function(require,module,exports){ "use strict"; module.exports = require('./hls'); },{"./hls":39}],41:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var HTML5Audio = function HTML5Audio() { $traceurRuntime.defaultSuperCall(this, $HTML5Audio.prototype, arguments); }; var $HTML5Audio = HTML5Audio; ($traceurRuntime.createClass)(HTML5Audio, { get name() { return 'html5_audio'; }, get type() { return 'playback'; }, get tagName() { return 'audio'; }, get events() { return { 'timeupdate': 'timeUpdated', 'ended': 'ended' }; }, initialize: function(options) { this.el.src = options.src; this.render(); }, setContainer: function() { this.container.settings = { left: ['playpause'], right: ['volume'], default: ['position', 'seekbar', 'duration'] }; this.render(); this.params.autoPlay && this.play(); }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.play); this.listenTo(this.container, 'container:pause', this.pause); this.listenTo(this.container, 'container:seek', this.seek); this.listenTo(this.container, 'container:volume', this.volume); this.listenTo(this.container, 'container:stop', this.stop); }, play: function() { this.el.play(); }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); this.el.currentTime = 0; }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, ended: function() { this.trigger('container:timeupdate', 0); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, timeUpdated: function() { this.container.timeUpdated(this.el.currentTime, this.el.duration); }, render: function() { this.container.$el.append(this.el); return this; } }, {}, UIPlugin); HTML5Audio.canPlay = function(resource) { return !!resource.match(/(.*).mp3/); }; module.exports = HTML5Audio; },{"../../base/ui_plugin":"Z7u8cr"}],42:[function(require,module,exports){ "use strict"; module.exports = require('./html5_audio'); },{"./html5_audio":41}],43:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var Browser = require('../../components/browser'); var HTML5Video = function HTML5Video() { $traceurRuntime.defaultSuperCall(this, $HTML5Video.prototype, arguments); }; var $HTML5Video = HTML5Video; ($traceurRuntime.createClass)(HTML5Video, { get name() { return 'html5_video'; }, get type() { return 'playback'; }, get tagName() { return 'video'; }, get attributes() { return {'data-html5-video': ''}; }, get events() { return { 'timeupdate': 'timeUpdated', 'progress': 'progress', 'ended': 'ended', 'playing': 'playing', 'stalled': 'stalled', 'waiting': 'waiting', 'canplaythrough': 'bufferFull', 'loadedmetadata': 'loadedMetadata' }; }, initialize: function(options) { this.options = options; this.src = options.src; this.el.src = options.src; this.el.loop = options.loop; this.settings = { left: ['playpause', 'volume'], right: ['fullscreen'], default: ['position', 'seekbar', 'duration'] }; }, loadedMetadata: function(e) { this.trigger('playback:loadedmetadata', e.target.duration); }, getPlaybackType: function() { var type = this.src.indexOf("m3u8") > -1 ? 'live' : 'vod'; return type; }, play: function() { this.el.play(); }, pause: function() { this.el.pause(); }, stop: function() { this.pause(); if (this.el.readyState !== 0) { this.el.currentTime = 0; } }, volume: function(value) { this.el.volume = value / 100; }, mute: function() { this.el.volume = 0; }, unmute: function() { this.el.volume = 1; }, isMuted: function() { return !!this.el.volume; }, isPlaying: function() { return !this.el.paused && !this.el.ended; }, ended: function() { this.trigger('playback:ended', this.name); this.trigger('playback:timeupdate', 0, this.el.duration, this.name); }, stalled: function() { if (this.getPlaybackType() == 'vod') { this.trigger('playback:buffering', this.name); } }, waiting: function() { this.trigger('playback:buffering', this.name); }, bufferFull: function() { this.trigger('playback:bufferfull', this.name); }, destroy: function() { this.stop(); this.el.src = ''; this.$el.remove(); }, seek: function(seekBarValue) { var time = this.el.duration * (seekBarValue / 100); this.el.currentTime = time; }, getCurrentTime: function() { return this.el.currentTime; }, getDuration: function() { return this.el.duration; }, timeUpdated: function() { this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name); }, progress: function() { if (!this.el.buffered.length) return; var bufferedPos = 0; for (var i = 0; i < this.el.buffered.length; i++) { if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) { bufferedPos = i; break; } } this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name); }, playing: function() { this.trigger('playback:play', this.name); }, render: function() { var style = Styler.getStyleFor(this.name); this.$el.append(style); this.trigger('playback:ready', this.name); this.options.autoPlay && this.play(); return this; } }, {}, UIPlugin); HTML5Video.canPlay = function(resource) { return (!!resource.match(/(.*).mp4/) || Browser.isSafari); }; module.exports = HTML5Video; },{"../../base/styler":15,"../../base/ui_plugin":"Z7u8cr","../../components/browser":"195Wj5"}],44:[function(require,module,exports){ "use strict"; module.exports = require('./html5_video'); },{"./html5_video":43}],45:[function(require,module,exports){ "use strict"; module.exports = require('./log'); },{"./log":46}],46:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var $ = require('jquery'); var BOLD = 'font-weight: bold; font-size: 13px;'; var INFO = 'color: green;' + BOLD; var DEBUG = 'color: #222;' + BOLD; var ERROR = 'color: red;' + BOLD; var DEFAULT = ''; $(document).keydown(function(e) { if (e.ctrlKey && e.shiftKey && e.keyCode === 68) { window.DEBUG = !window.DEBUG; } }); var Log = function(klass) { this.klass = klass || 'Logger'; }; Log.info = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.error = function(klass, msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, klass, msg); }; Log.BLACKLIST = ['mediacontrol:show', 'mediacontrol:hide', 'playback:timeupdate', 'playback:progress', 'container:hover', 'container:timeupdate', 'container:progress']; Log.prototype = { log: function(msg) { this.info(msg); }, info: function(msg) { console.log('%s %cINFO%c [%s] %s', (new Date()).toLocaleTimeString(), INFO, DEFAULT, this.klass, msg); }, error: function(msg) { console.log('%s %cERROR%c [%s] %s', (new Date()).toLocaleTimeString(), ERROR, DEFAULT, this.klass, msg); } }; module.exports = Log; },{"../../base/base_object":"2HNVgz","jquery":4}],47:[function(require,module,exports){ "use strict"; module.exports = require('./poster'); },{"./poster":48}],48:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var $ = require('jquery'); var PosterPlugin = function PosterPlugin() { $traceurRuntime.defaultSuperCall(this, $PosterPlugin.prototype, arguments); }; var $PosterPlugin = PosterPlugin; ($traceurRuntime.createClass)(PosterPlugin, { get name() { return 'poster'; }, get template() { return JST.poster; }, get attributes() { return { 'class': 'player-poster', 'data-poster': '' }; }, get events() { return {'click': 'clicked'}; }, initialize: function(options) { $traceurRuntime.superCall(this, $PosterPlugin.prototype, "initialize", [options]); if (options.disableControlsOnPoster === undefined) options.disableControlsOnPoster = true; this.options = options; if (this.options.disableControlsOnPoster) this.container.disableMediaControl(); this.render(); }, bindEvents: function() { this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:ended', this.onStop); }, onBuffering: function() { this.hidePlayButton(); }, onPlay: function() { this.$el.hide(); if (this.options.disableControlsOnPoster) { this.container.enableMediaControl(); } }, onStop: function() { this.$el.show(); if (this.options.disableControlsOnPoster) { this.container.disableMediaControl(); } if (!this.options.hidePlayButton) { this.showPlayButton(); } }, hidePlayButton: function() { this.$playButton.hide(); }, showPlayButton: function() { this.$el.css({fontSize: this.$el.height()}); this.$playButton.show(); }, clicked: function() { this.container.play(); }, render: function() { var $__0 = this; var style = Styler.getStyleFor(this.name); this.$el.html(this.template()); this.$el.append(style); this.container.$el.append(this.el); this.$el.ready((function() { $__0.$el.css({fontSize: $__0.options.height || $__0.$el.height()}); })); var imgEl = this.$el.find('img')[0]; imgEl.src = this.options.poster || 'assets/default.png'; this.$playButton = $(this.$el.find('.play-wrapper')); if (this.options.hidePlayButton) this.$playButton.hide(); return this; } }, {}, UIPlugin); module.exports = PosterPlugin; },{"../../base/jst":12,"../../base/styler":15,"../../base/ui_plugin":"Z7u8cr","jquery":4}],49:[function(require,module,exports){ "use strict"; module.exports = require('./sequence'); },{"./sequence":50}],50:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var SequenceContainer = require('./sequence_container'); var _ = require('underscore'); var Utils = require('../../base/utils'); var Sequence = BaseObject.extend({ initialize: function(core) { this.core = core; this.sequenceContainer = new SequenceContainer(this.core.containers); this.core.mediaControl.setContainer(this.sequenceContainer); }, getExternalInterface: function() { return {}; } }); module.exports = Sequence; },{"../../base/base_object":"2HNVgz","../../base/utils":20,"./sequence_container":51,"underscore":6}],51:[function(require,module,exports){ "use strict"; var BaseObject = require('../../base/base_object'); var _ = require('underscore'); var SequenceContainer = BaseObject.extend({ name: 'SequenceContainer', initialize: function(containers) { this.containers = containers; this.plugins = []; this.containersRange = []; this.currentContainer = 0; this.checkpoint = 0; this.duration = 0; _.each(this.containers, this._setupContainers, this); this.containersToSetup = this.containers.length; this._bindChildEvents(this.getCurrentContainer()); this.getCurrentContainer().$el.show(); this.settings = this.getCurrentContainer().settings; }, _bindChildEvents: function(container) { this.listenTo(container, 'container:ended', this.playNextContainer); this.listenTo(container, 'container:timeupdate', this.timeUpdateProxy); this.listenTo(container, 'container:progress', this.progressProxy); }, _setupContainers: function(container) { container.$el.hide(); this._injectInChildPlugins(container.plugins); this.listenTo(container, 'container:loadedmetadata', this._setupDuration); }, _injectInChildPlugins: function(plugins) { _.each(plugins, function(plugin) { plugin.stopListening(); plugin.container = this; plugin.bindEvents(); }, this); }, _setupDuration: function(duration) { this.duration += duration; this.trigger('container:timeupdate', 0, this.duration); if (--this.containersToSetup === 0) { this._setupSeek(); } }, _setupSeek: function() { _.each(this.containers, function(container) { var containerDuration = container.playback.getDuration(); var totalPercent = (containerDuration * 100) / this.duration; this.containersRange.push(totalPercent); }, this); }, getPlaybackType: function() { return this.getCurrentContainer().getPlaybackType(); }, length: function() { return this.containers.length; }, playNextContainer: function() { this.getCurrentContainer().$el.hide(); this.stopListening(this.getCurrentContainer()); var nextContainer = this.getNextContainer(); this.trigger('container:next', this.currentContainer); this._bindChildEvents(nextContainer); if (this.currentContainer === 0) { this.checkpoint = 0; nextContainer.$el.show(); this.trigger('container:ended'); nextContainer.stop(); } else { nextContainer.play(); this.trigger('container:play'); this.trigger('container:settingsupdate'); this.trigger('container:timeupdate', this.checkpoint, this.duration); nextContainer.$el.show(); } }, timeUpdateProxy: function(position, duration) { this.trigger('container:timeupdate', position + this.checkpoint, this.duration, this.name); }, progressProxy: function(startPosition, endPosition, duration) { this.trigger('container:progress', startPosition, endPosition, this.duration, this.name); }, getCurrentContainer: function() { return this.containers[this.currentContainer]; }, getNextContainer: function() { this.checkpoint += this.getCurrentContainer().playback.getDuration(); this.currentContainer = ++this.currentContainer % this.containers.length; var nextContainer = this.containers[this.currentContainer]; this.settings = nextContainer.settings; return nextContainer; }, play: function() { this.getCurrentContainer().playback.play(); this.trigger('container:play', this.name); }, setVolume: function(value) { this.trigger('container:volume', value, this.name); this.getCurrentContainer().setVolume(value); }, pause: function() { this.getCurrentContainer().pause(); this.trigger('container:pause', this.name); }, stop: function() { this.getCurrentContainer().stop(); this.trigger('container:stop', this.name); }, playing: function() { this.trigger('container:playing', this.name); }, progress: function(startPosition, endPosition, duration) { this.trigger('container:progress', startPosition, endPosition, duration); }, _matchContainerIndex: function(percent) { var total = 0; for (var i = 0, l = this.containers.length; i < l; i++) { total += this.containersRange[i]; if (total >= percent) { return i; } } return this.containers.length - 1; }, jumpToContainer: function(index) { if (index === 0) { this.seekToContainer(index, 0); } else { var value = _.reduce(this.containersRange.slice(0, index), function(total, percent) { return total + percent; }); this.seekToContainer(index, value); } }, setCurrentTime: function(time) { var containerIndex = this._matchContainerIndex(time); this.seekToContainer(containerIndex, time); }, seekToContainer: function(containerIndex, time) { if (containerIndex === 0) { this.checkpoint = 0; } else { var slice = this.containers.slice(0, containerIndex); this.checkpoint = _.reduce(slice, function(duration, container) { return duration + container.playback.getDuration(); }, 0); var pastRange = _.reduce(this.containersRange.slice(0, containerIndex), function(total, percent) { return percent + total; }, 0); time = time - pastRange; } var containerSeek = time * 100 / this.containersRange[containerIndex]; var currentContainer = this.getCurrentContainer(); currentContainer.$el.hide(); this.stopListening(currentContainer); currentContainer.stop(); this.currentContainer = containerIndex; var newContainer = this.containers[containerIndex]; this.listenTo(newContainer, 'container:ended', this.playNextContainer); this.listenTo(newContainer, 'container:timeupdate', this.timeUpdateProxy); this.listenTo(newContainer, 'container:progress', this.progressProxy); newContainer.play(); this.trigger('container:settingsupdate'); this.trigger('container:play'); newContainer.setCurrentTime(containerSeek); newContainer.$el.show(); }, settingsUpdate: function() { this.settings = this.getCurrentContainer().settings; this.trigger('container:settingsupdate'); }, isPlaying: function() { return this.getCurrentContainer().isPlaying(); }, render: function() { this.el = _.map(this.containers, function(container) { return container.render().el; }); return this; } }); module.exports = SequenceContainer; },{"../../base/base_object":"2HNVgz","underscore":6}],52:[function(require,module,exports){ "use strict"; module.exports = require('./spinner_three_bounce'); },{"./spinner_three_bounce":53}],53:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var SpinnerThreeBouncePlugin = UIPlugin.extend({ name: 'spinner_three_bounce', attributes: { 'data-spinner': '', 'class': 'spinner-three-bounce' }, initialize: function(options) { SpinnerThreeBouncePlugin.super('initialize').call(this, options); this.template = JST[this.name]; this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stop', this.onStop); this.render(); }, onBuffering: function() { this.$el.show(); }, onBufferFull: function() { this.$el.hide(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); this.$el.html(this.template()); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }); module.exports = SpinnerThreeBouncePlugin; },{"../../base/jst":12,"../../base/styler":15,"../../base/ui_plugin":"Z7u8cr"}],54:[function(require,module,exports){ "use strict"; module.exports = require('./stats'); },{"./stats":55}],55:[function(require,module,exports){ "use strict"; var Plugin = require('../../base/plugin'); var $ = require("jquery"); var StatsPlugin = function StatsPlugin() { $traceurRuntime.defaultSuperCall(this, $StatsPlugin.prototype, arguments); }; var $StatsPlugin = StatsPlugin; ($traceurRuntime.createClass)(StatsPlugin, { get name() { return 'stats'; }, get type() { return 'stats'; }, initialize: function(options) { $traceurRuntime.superCall(this, $StatsPlugin.prototype, "initialize", [options]); this.setInitialAttrs(); this.reportInterval = options.reportInterval || 5000; this.state = "IDLE"; }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); this.listenTo(this.container, 'container:destroyed', this.onStop); this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval); this.listenTo(this.container, 'container:state:buffering', this.onBuffering); this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull); this.listenTo(this.container, 'container:stats:add', this.onStatsAdd); this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd); }, setReportInterval: function(reportInterval) { this.reportInterval = reportInterval; }, setInitialAttrs: function() { this.firstPlay = true; this.startupTime = 0; this.rebufferingTime = 0; this.watchingTime = 0; this.rebuffers = 0; this.externalMetrics = {}; }, onPlay: function() { this.state = "PLAYING"; this.watchingTimeInit = Date.now(); this.intervalId = setInterval(this.report.bind(this), this.reportInterval); }, onStop: function() { clearInterval(this.intervalId); this.state = "STOPPED"; }, onBuffering: function() { if (this.firstPlay) { this.startupTimeInit = Date.now(); } else { this.rebufferingTimeInit = Date.now(); } this.state = "BUFFERING"; this.rebuffers++; }, onBufferFull: function() { if (this.firstPlay) { this.firstPlay = false; this.startupTime = Date.now() - this.startupTimeInit; this.watchingTimeInit = Date.now(); } else { this.rebufferingTime += this.getRebufferingTime(); } this.rebufferingTimeInit = undefined; this.state = "PLAYING"; }, getRebufferingTime: function() { return Date.now() - this.rebufferingTimeInit; }, getWatchingTime: function() { var totalTime = (Date.now() - this.watchingTimeInit); return totalTime - this.rebufferingTime - this.startupTime; }, isRebuffering: function() { return !!this.rebufferingTimeInit; }, onStatsAdd: function(metric) { $.extend(this.externalMetrics, metric); }, getStats: function() { var metrics = { startupTime: this.startupTime, rebuffers: this.rebuffers, rebufferingTime: this.isRebuffering() ? this.rebufferingTime + this.getRebufferingTime() : this.rebufferingTime, watchingTime: this.isRebuffering() ? this.getWatchingTime() - this.getRebufferingTime() : this.getWatchingTime() }; $.extend(metrics, this.externalMetrics); return metrics; }, report: function() { this.container.statsReport(this.getStats()); } }, {}, Plugin); module.exports = StatsPlugin; },{"../../base/plugin":13,"jquery":4}],56:[function(require,module,exports){ "use strict"; module.exports = require('./watermark'); },{"./watermark":57}],57:[function(require,module,exports){ "use strict"; var UIPlugin = require('../../base/ui_plugin'); var Styler = require('../../base/styler'); var JST = require('../../base/jst'); var WaterMarkPlugin = function WaterMarkPlugin() { $traceurRuntime.defaultSuperCall(this, $WaterMarkPlugin.prototype, arguments); }; var $WaterMarkPlugin = WaterMarkPlugin; ($traceurRuntime.createClass)(WaterMarkPlugin, { get name() { return 'watermark'; }, get type() { return 'ui'; }, initialize: function(options) { $traceurRuntime.superCall(this, $WaterMarkPlugin.prototype, "initialize", [options]); this.template = JST[this.name]; this.position = options.position || "bottom-right"; this.imageUrl = options.watermark || 'assets/watermark.png'; this.render(); }, bindEvents: function() { this.listenTo(this.container, 'container:play', this.onPlay); this.listenTo(this.container, 'container:stop', this.onStop); }, onPlay: function() { if (!this.hidden) this.$el.show(); }, onStop: function() { this.$el.hide(); }, render: function() { this.$el.hide(); var templateOptions = { position: this.position, imageUrl: this.imageUrl }; this.$el.html(this.template(templateOptions)); var style = Styler.getStyleFor(this.name); this.container.$el.append(style); this.container.$el.append(this.$el); return this; } }, {}, UIPlugin); module.exports = WaterMarkPlugin; },{"../../base/jst":12,"../../base/styler":15,"../../base/ui_plugin":"Z7u8cr"}]},{},[3,36])
packages/material-ui-icons/lib/esm/FolderSharedOutlined.js
mbrookes/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V6h5.17l2 2H20v10zm-5-5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 4h8v-1c0-1.33-2.67-2-4-2s-4 .67-4 2v1z" }), 'FolderSharedOutlined');
client/js/app.js
charitycollective/charitytree
import React from 'react'; import { History } from 'react-router'; var LocalStorageMixin = require('react-localstorage'); import { loggedIn } from '../config/routes.js'; import {Navbar} from './navbar.js'; var App = exports.App = React.createClass({ displayName: 'App', mixins: [History, LocalStorageMixin], getInitialState: function () { return { loggedIn: false, searchText: "", searchCriteria: [], searchResults: [], projectId: "", orgId: "", currentOrganization: null, currentProject: null, userType: '' }; }, isLoggedIn: function () { this.setState({ loggedIn: loggedIn() }); }, setUserType: function(e) { console.log(e.target.value); this.setState( {userType: e.target.value }); this.props.history.pushState(null, `/signup`); }, componentDidMount: function () { if (this.state.searchText && window.location.pathname === "/search") { this.handleSearchSubmit(); } }, updateSearchCriteria: function(tags) { this.setState({ searchCriteria: tags }) }, navigateToOrganizationPage: function () { this.props.history.pushState(null, `/organization`); }, navigateToDonate: function () { this.props.history.pushState(null, `/donate`); }, navigateToBrowsePage: function () { this.props.history.pushState(null, `/browse`); }, navigateToProjectPage: function () { this.props.history.pushState(null, `/project`); }, updateInput: function (searchText) { this.setState({ searchText: searchText }); }, removeBrowseTag: function(tagName) { var searchCriteria = this.state.searchCriteria.slice(); var tagIdx = searchCriteria.indexOf(tagName); searchCriteria.splice(tagIdx, 1); this.setState({ searchCriteria: searchCriteria }); }, removeSearchTag: function(tagName) { var searchCriteria = this.state.searchCriteria.slice(); var tagIdx = searchCriteria.indexOf(tagName); searchCriteria.splice(tagIdx, 1); var searchText = ""; console.log("/searchCriteria.length:",searchCriteria.length); if (searchCriteria.length > 0) { searchText = searchCriteria.join(" "); } this.setState({ searchText: searchText, searchCriteria: searchCriteria }); var self = this; var i = setInterval(function () { if (searchCriteria === self.state.searchCriteria) { clearInterval(i); console.log("App/rST/self.state.searchCriteria:",self.state.searchCriteria); console.log("App/rST/self.state.searchText:",self.state.searchText); self.handleSearchSubmit(); } }, 100); }, handleSearchButton: function (searchText) { console.log("App/hSS/searchText:",searchText); this.setState({ searchText: searchText }); var self = this; var i = setInterval(function () { if (searchText === self.state.searchText) { clearInterval(i); console.log("App/hSS/this.state.searchText:",self.state.searchText); self.handleSearchSubmit(); } }, 100); }, handleSearchSubmit: function () { if (this.state.searchText) { var searchCriteria = this.state.searchText.split(" "); console.log("App/hSS/: searchCriteria",searchCriteria); $.ajax({ url: "/post_search", // dataType: 'json', method: "POST", data: {aofs: searchCriteria}, success: function (data) { this.setState({ searchText: this.state.searchText, searchCriteria: searchCriteria, searchResults: data.results }); this.props.history.pushState(null, `/search`); // console.log('Testing success time. Inside of success to AJAX') }.bind(this), error: function (xhr, status, err) { console.error(xhr, status, err.toString()); }.bind(this) }); } else { this.setState({ searchText: this.state.searchText, searchCriteria: [], searchResults: [] }); } }, getProject: function(projectId) { this.setState({ projectId: projectId }); var self = this; var i = setInterval(function () { if (projectId === self.state.projectId) { clearInterval(i); console.log("App/gP/this.state.projectId:",self.state.projectId); self.props.history.pushState(null, `/project`); } }, 100); }, setProject: function(project){ this.setState({ searchText: this.state.searchText, searchCriteria: this.state.searchCriteria, searchResults: this.state.searchResults, projectId: this.state.projectId, orgId: this.state.orgId, currentOrganization: this.state.currentOrganization, currentProject: project }); localStorage.projectId = this.state.projectId; this.navigateToProjectPage(); }, setOrganization: function(org){ console.log("App/sO/org:",org); this.setState({ searchText: this.state.searchText, searchCriteria: this.state.searchCriteria, searchResults: this.state.searchResults, projectId: this.state.projectId, orgId: this.state.orgId, currentOrganization: org }); this.navigateToOrganizationPage(); }, render: function () { return ( <div> <Navbar loggedIn={this.state.loggedIn} isLoggedIn={this.isLoggedIn} searchText={this.state.searchText} updateInput={this.updateInput} handleSearchSubmit={this.handleSearchSubmit}/> {this.props.children && React.cloneElement(this.props.children, { //State Props searchText: this.state.searchText, searchCriteria: this.state.searchCriteria, searchResults: this.state.searchResults, projectId: this.state.projectId, currentOrganization: this.state.currentOrganization, userType: this.state.userType, currentProject: this.state.currentProject, //Functions navigateToDonate: this.navigateToDonate, isLoggedIn: this.isLoggedIn, handleSearchButton: this.handleSearchButton, updateInput: this.updateInput, handleSearchSubmit: this.handleSearchSubmit, updateSearchCriteria: this.updateSearchCriteria, removeBrowseTag: this.removeBrowseTag, removeSearchTag: this.removeSearchTag, getProject: this.getProject, setProject: this.setProject, setOrganization: this.setOrganization, setUserType: this.setUserType, navigateToProjectPage: this.navigateToProjectPage, navigateToOrganizationPage: this.navigateToOrganizationPage } )} </div> ); } });
test/components/SideMenu.spec.js
Byte-Code/lm-digitalstore
import React from 'react'; import { shallow } from 'enzyme'; import SideMenu, { Button } from '../../app/components/SideMenu'; describe('SideMenu', () => { const result = shallow( <SideMenu /> ); it('should initially render closed', () => { expect(result.state('open')).toBe(false); expect(result).toMatchSnapshot(); }); it('the first button should be initially visible', () => { expect(result.find(Button).at(0).prop('isVisible')).toBe(true); }); it('should open once the first button is clicked', () => { result.find(Button).at(0).simulate('click'); expect(result.state('open')).toBe(true); expect(result).toMatchSnapshot(); }); it('the first button should not be visible now', () => { expect(result.find(Button).at(0).prop('isVisible')).toBe(false); }); it('should close again once the second button is clicked', () => { result.find(Button).at(1).simulate('click'); expect(result.state('open')).toBe(false); expect(result).toMatchSnapshot(); }); });
ajax/libs/react-redux-form/1.0.9/ReactReduxForm.js
him2him2/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("redux"),require("react-dom")):"function"==typeof define&&define.amd?define(["react","redux","react-dom"],t):"object"==typeof exports?exports.ReactReduxForm=t(require("react"),require("redux"),require("react-dom")):e.ReactReduxForm=t(e.React,e.Redux,e["react-dom"])}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){r(46),e.exports=r(46)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={BLUR:"rrf/blur",CHANGE:"rrf/change",FOCUS:"rrf/focus",RESET:"rrf/reset",VALIDATE:"rrf/validate",SET_DIRTY:"rrf/setDirty",SET_ERRORS:"rrf/setErrors",SET_INITIAL:"rrf/setInitial",SET_PENDING:"rrf/setPending",SET_PRISTINE:"rrf/setPristine",SET_SUBMITTED:"rrf/setSubmitted",SET_SUBMIT_FAILED:"rrf/setSubmitFailed",SET_TOUCHED:"rrf/setTouched",SET_UNTOUCHED:"rrf/setUntouched",SET_VALIDITY:"rrf/setValidity",SET_VALIDATING:"rrf/setValidating",SET_FIELDS_VALIDITY:"rrf/setFieldsValidity",SET_VIEW_VALUE:"rrf/setViewValue",RESET_VALIDITY:"rrf/resetValidity",BATCH:"rrf/batch",NULL:"rrf/null"};t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){var n=t;return t.length?((0,f["default"])(n,".")?n=n.slice(0,-1):(0,f["default"])(n,"[]")&&(n=n.slice(0,-2)),(0,a["default"])(e,n,r)):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(173),a=n(u),i=r(39),f=n(i)},function(e,t,r){function n(e){if(!a(e)||d.call(e)!=i||u(e))return!1;var t=o(e);if(null===t)return!0;var r=c.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&l.call(r)==s}var o=r(63),u=r(64),a=r(25),i="[object Object]",f=Object.prototype,l=Function.prototype.toString,c=f.hasOwnProperty,s=l.call(Object),d=f.toString;e.exports=n},function(e,t){"use strict";function r(e,t){var r={};return Object.keys(e||{}).forEach(function(n){r[n]=t(e[n],n,e)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function u(e,t,r,n){var u=t.length?(0,l["default"])(e,t,d.initialFieldState):e,a=u.hasOwnProperty("$form")?[].concat(o(t),["$form"]):t,f=(0,l["default"])(e,a,d.initialFieldState),c="function"==typeof r?r(f):r;if("$form"in u&&n){var p=(0,s["default"])(u,function(e,t){if("$form"===t)return i["default"].assign(f,c);var r="function"==typeof n?n(e,c):n;return i["default"].assign(e,r)});return t.length?i["default"].setIn(e,t,p):p}return i["default"].setIn(e,a,i["default"].assign(f,c))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(9),i=n(a),f=r(2),l=n(f),c=r(4),s=n(c),d=r(7)},function(e,t){var r=Array.isArray;e.exports=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function u(e,t){return!t.length&&e.$form?e.$form:(0,d["default"])(e,t,Z)}function a(e,t){return e?e+"."+t:t}function i(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=void 0;if(!(0,_["default"])(t)&&!(0,m["default"])(t))return v["default"].merge(Z,c({initialValue:t,value:t,model:e},r));n=(0,O["default"])(t,function(t,n){return i(a(e,n),t,r)});var o=v["default"].merge(Z,c({initialValue:t,value:t,model:e},r));return v["default"].set(n,"$form",o)}function f(e,t,r){return function(){var n=arguments.length<=0||void 0===arguments[0]?r:arguments[0],o=arguments[1];if(!o.model)return n;var u=(0,T["default"])(o.model);if(t.length&&!(0,y["default"])(u.slice(0,t.length),t))return n;var a=u.slice(t.length);return e(n,o,a)}}function l(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],n=r.plugins,u=void 0===n?[]:n,a=r.initialFieldState,l=(0,T["default"])(e),c=i(e,t,a),s=u.concat(ee).map(function(e){return f(e,l,c)});return(0,x["default"])(E["default"].apply(void 0,o(s)))}Object.defineProperty(t,"__esModule",{value:!0}),t.initialFieldState=void 0;var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.getField=u,t["default"]=l;var s=r(2),d=n(s),p=r(9),v=n(p),h=r(47),y=n(h),b=r(3),m=n(b),g=r(6),_=n(g),P=r(4),O=n(P),j=r(19),T=n(j),S=r(96),E=n(S),M=r(29),x=n(M),w=r(84),k=n(w),V=r(91),A=n(V),C=r(88),I=n(C),F=r(85),D=n(F),R=r(90),N=n(R),$=r(89),U=n($),L=r(83),H=n(L),B=r(94),G=n(B),K=r(86),q=n(K),Y=r(93),W=n(Y),z=r(92),J=n(z),Q=r(87),X=n(Q),Z=t.initialFieldState={focus:!1,pending:!1,pristine:!0,submitted:!1,submitFailed:!1,retouched:!1,touched:!1,validating:!1,validated:!1,validity:{},errors:{}},ee=[D["default"],H["default"],G["default"],N["default"],U["default"],k["default"],A["default"],I["default"],q["default"],W["default"],J["default"],X["default"]]},function(t,r){t.exports=e},function(e,t,r){"use strict";function n(e){return null!==e&&(Array.isArray(e)||o(e))}function o(e){return"object"==typeof e&&e.constructor===Object&&Object.getPrototypeOf(e)===Object.prototype}function u(e){for(var t=0,r=e.length,n=Array(r);t<r;t+=1)n[t]=e[t];return n}function a(e){for(var t,r=0,n=Object.keys(e),o=n.length,u={};r<o;r+=1)t=n[r],u[t]=e[t];return u}function i(e){return Array.isArray(e)?u(e):a(e)}function f(e){return n(e)&&(!Object.isFrozen(e),!1)?c(e,[]):e}function l(e){return e}function c(e,t){if(t.some(function(t){return t===e}))throw new Error("object has a reference cycle");return Object.freeze(e),t.push(e),Object.keys(e).forEach(function(r){var o=e[r];n(o)&&c(o,t)}),t.pop(),e}function s(e,t){return(t||[]).reduce(function(e,t){if(e)return e[t]},e)}function d(e,t){return Object.keys(t).reduce(function(e,r){return b.assoc(e,r,t[r])},e)}function p(e,t,r){return null==e||null==t?e:Object.keys(t).reduce(function(e,o){var u=t[o],a=e[o],i=r?r(a,u,o):u;return n(u)&&n(a)?(Object.isFrozen(i)&&Object.isFrozen(a),i===a?e:Array.isArray(u)?b.assoc(e,o,i):v(e,o,p(a,i,r))):v(e,o,i)},e)}function v(e,t,r){return e[t]===r?e:b.assoc(e,t,r)}function h(e,t){var r=t||0,n=e.length;n-=r,n=n<0?0:n;for(var o=new Array(n),u=0;u<n;u+=1)o[u]=e[u+r];return o}function y(e){return h(e,1)}var b=t;t.freeze=function(e){return e},t.thaw=function g(e){if(n(e)&&Object.isFrozen(e)){var t=i(e);return Object.keys(t).forEach(function(e){t[e]=g(t[e])}),t}return e},t.assoc=function(e,t,r){if(e[t]===r)return l(e);var n=i(e);return n[t]=f(r),l(n)},t.set=t.assoc,t.dissoc=function(e,t){var r=i(e);return delete r[t],l(r)},t.unset=t.dissoc,t.assocIn=function _(e,t,r){var n=t[0];return 1===t.length?b.assoc(e,n,r):b.assoc(e,n,_(e[n]||{},t.slice(1),r))},t.setIn=t.assocIn,t.getIn=s,t.updateIn=function(e,t,r){var n=s(e,t);return b.assocIn(e,t,r(n))},["push","unshift","pop","shift","reverse","sort"].forEach(function(e){t[e]=function(t,r){var n=u(t);return n[e](f(r)),l(n)},t[e].displayName="icepick."+e}),t.splice=function(e){var t=u(e),r=y(arguments).map(f);return t.splice.apply(t,r),l(t)},t.slice=function(e,t,r){var n=e.slice(t,r);return l(n)},["map","filter"].forEach(function(e){t[e]=function(t,r){var n=r[e](t);return l(n)},t[e].displayName="icepick."+e}),t.extend=t.assign=function(){var e=y(arguments).reduce(d,arguments[0]);return l(e)},t.merge=p;var m={value:function(){return this.val},thru:function(e){return this.val=f(e(this.val)),this}};Object.keys(t).forEach(function(e){m[e]=function(){var r=h(arguments);return r.unshift(this.val),this.val=t[e].apply(null,r),this}}),t.chain=function(e){var t=Object.create(m);return t.val=e,t},t._weCareAbout=n,t._slice=h},function(e,t,r){"use strict";function n(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 r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(43),a=n(u),i=r(73),f=n(i),l=r(42),c=n(l),s=o({},a["default"],f["default"],c["default"]);t["default"]=s},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(!e)return!0;if(!e.$form){var t=e.errors;return Array.isArray(t)||(0,a["default"])(t)?Object.keys(e.errors).every(function(t){var r=!e.errors[t];return r}):!t}return Object.keys(e).every(function(t){return o(e[t])})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u)},function(e,t){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function n(e,t){var n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2];if(r(e,t))return!0;if("object"!==("undefined"==typeof e?"undefined":u(e))||null===e||"object"!==("undefined"==typeof t?"undefined":u(t))||null===t)return!1;var o=Object.keys(e),i=Object.keys(t);if(o.length!==i.length)return!1;for(var f=0;f<o.length;f++)if(!(n.length&&~n.indexOf(o[f])||a.call(t,o[f])&&r(e[o[f]],t[o[f]])))return!1;return!0}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},u="function"==typeof Symbol&&"symbol"===o(Symbol.iterator)?function(e){return"undefined"==typeof e?"undefined":o(e)}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":"undefined"==typeof e?"undefined":o(e)},a=Object.prototype.hasOwnProperty;t["default"]=n},function(e,t){function r(e,t){for(var r=-1,n=e?e.length:0,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}e.exports=r},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){function n(e){return null!=e&&u(e.length)&&!o(e)}var o=r(40),u=r(175);e.exports=n},function(e,t,r){function n(e){return"symbol"==typeof e||o(e)&&i.call(e)==u}var o=r(25),u="[object Symbol]",a=Object.prototype,i=a.toString;e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=arguments.length<=2||void 0===arguments[2]?"":arguments[2],n=[],u=null;return Object.keys(e).some(function(o){var a=e[o];return a&&a.$form?""===a.$form.model?Object.keys(a).some(function(e){var n=a[e];return"$form"!==e&&!!n.$form&&!!(0,s["default"])(t,n.$form.model)&&(u=r?[r,o,e].join("."):[o,e].join("."),!0)}):!!(0,s["default"])(t,a.$form.model)&&(u=r?[r,o].join("."):o,!0):((0,l["default"])(a)&&n.push(o),!1)}),u?u:(n.some(function(n){return u=o(e[n],t,r?[r,n].join("."):n),!!u}),u?u:null)}function u(e,t){var r=o(e,t);return r?(0,i["default"])(e,r):null}Object.defineProperty(t,"__esModule",{value:!0}),t.getFormStateKey=o,t["default"]=u;var a=r(2),i=n(a),f=r(3),l=n(f),c=r(104),s=n(c);r(49)},function(e,t){"use strict";function r(e,t){return"function"==typeof e&&t?e(t):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=e;return(0,f["default"])(t,".")?t=t.slice(0,-1):(0,f["default"])(t,"[]")&&(t=t.slice(0,-2)),(0,a["default"])(t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(70),a=n(u),i=r(39),f=n(i)},function(e,t,r){function n(e,t){for(var r=e.length;r--;)if(o(e[r][0],t))return r;return-1}var o=r(172);e.exports=n},function(e,t,r){function n(e,t){var r=e.__data__;return o(t)?r["string"==typeof t?"string":"hash"]:r.map}var o=r(155);e.exports=n},function(e,t,r){var n=r(62),o=n(Object,"create");e.exports=o},function(e,t,r){function n(e){if("string"==typeof e||o(e))return e;var t=e+"";return"0"==t&&1/e==-u?"-0":t}var o=r(16),u=1/0;e.exports=n},function(e,t){function r(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}e.exports=r},function(e,t){function r(e){return!!e&&"object"==typeof e}e.exports=r},function(e,t,r){var n=r(13),o=r(119),u=r(58),a=r(59),i=r(60),f=r(143),l=r(23),c=i(function(e,t){return null==e?{}:(t=n(u(t,1),l),a(e,o(f(e),t)))});e.exports=c},function(e,t,r){"use strict";function n(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 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 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)}function i(e){return e.displayName||e.name||"Component"}function f(e,t){try{return e.apply(t)}catch(r){return M.value=r,M}}function l(e,t,r){var n=arguments.length<=3||void 0===arguments[3]?{}:arguments[3],l=Boolean(e),d=e||T,v=void 0;v="function"==typeof t?t:t?(0,b["default"])(t):S;var y=r||E,m=n.pure,g=void 0===m||m,_=n.withRef,O=void 0!==_&&_,w=g&&y!==E,k=x++;return function(e){function t(e,t,r){var n=y(e,t,r);return n}var r="Connect("+i(e)+")",n=function(n){function i(e,t){o(this,i);var a=u(this,n.call(this,e,t));a.version=k,a.store=e.store||t.store,(0,j["default"])(a.store,'Could not find "store" in either the context or '+('props of "'+r+'". ')+"Either wrap the root component in a <Provider>, "+('or explicitly pass "store" as a prop to "'+r+'".'));var f=a.store.getState();return a.state={storeState:f},a.clearCache(),a}return a(i,n),i.prototype.shouldComponentUpdate=function(){return!g||this.haveOwnPropsChanged||this.hasStoreStateChanged},i.prototype.computeStateProps=function(e,t){if(!this.finalMapStateToProps)return this.configureFinalMapState(e,t);var r=e.getState(),n=this.doStatePropsDependOnOwnProps?this.finalMapStateToProps(r,t):this.finalMapStateToProps(r);return n},i.prototype.configureFinalMapState=function(e,t){var r=d(e.getState(),t),n="function"==typeof r;return this.finalMapStateToProps=n?r:d,this.doStatePropsDependOnOwnProps=1!==this.finalMapStateToProps.length,n?this.computeStateProps(e,t):r},i.prototype.computeDispatchProps=function(e,t){if(!this.finalMapDispatchToProps)return this.configureFinalMapDispatch(e,t);var r=e.dispatch,n=this.doDispatchPropsDependOnOwnProps?this.finalMapDispatchToProps(r,t):this.finalMapDispatchToProps(r);return n},i.prototype.configureFinalMapDispatch=function(e,t){var r=v(e.dispatch,t),n="function"==typeof r;return this.finalMapDispatchToProps=n?r:v,this.doDispatchPropsDependOnOwnProps=1!==this.finalMapDispatchToProps.length,n?this.computeDispatchProps(e,t):r},i.prototype.updateStatePropsIfNeeded=function(){var e=this.computeStateProps(this.store,this.props);return!(this.stateProps&&(0,h["default"])(e,this.stateProps)||(this.stateProps=e,0))},i.prototype.updateDispatchPropsIfNeeded=function(){var e=this.computeDispatchProps(this.store,this.props);return!(this.dispatchProps&&(0,h["default"])(e,this.dispatchProps)||(this.dispatchProps=e,0))},i.prototype.updateMergedPropsIfNeeded=function(){var e=t(this.stateProps,this.dispatchProps,this.props);return!(this.mergedProps&&w&&(0,h["default"])(e,this.mergedProps)||(this.mergedProps=e,0))},i.prototype.isSubscribed=function(){return"function"==typeof this.unsubscribe},i.prototype.trySubscribe=function(){l&&!this.unsubscribe&&(this.unsubscribe=this.store.subscribe(this.handleChange.bind(this)),this.handleChange())},i.prototype.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null)},i.prototype.componentDidMount=function(){this.trySubscribe()},i.prototype.componentWillReceiveProps=function(e){g&&(0,h["default"])(e,this.props)||(this.haveOwnPropsChanged=!0)},i.prototype.componentWillUnmount=function(){this.tryUnsubscribe(),this.clearCache()},i.prototype.clearCache=function(){this.dispatchProps=null,this.stateProps=null,this.mergedProps=null,this.haveOwnPropsChanged=!0,this.hasStoreStateChanged=!0,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,this.renderedElement=null,this.finalMapDispatchToProps=null,this.finalMapStateToProps=null},i.prototype.handleChange=function(){if(this.unsubscribe){var e=this.store.getState(),t=this.state.storeState;if(!g||t!==e){if(g&&!this.doStatePropsDependOnOwnProps){var r=f(this.updateStatePropsIfNeeded,this);if(!r)return;r===M&&(this.statePropsPrecalculationError=M.value),this.haveStatePropsBeenPrecalculated=!0}this.hasStoreStateChanged=!0,this.setState({storeState:e})}}},i.prototype.getWrappedInstance=function(){return(0,j["default"])(O,"To access the wrapped instance, you need to specify { withRef: true } as the fourth argument of the connect() call."),this.refs.wrappedInstance},i.prototype.render=function(){var t=this.haveOwnPropsChanged,r=this.hasStoreStateChanged,n=this.haveStatePropsBeenPrecalculated,o=this.statePropsPrecalculationError,u=this.renderedElement;if(this.haveOwnPropsChanged=!1,this.hasStoreStateChanged=!1,this.haveStatePropsBeenPrecalculated=!1,this.statePropsPrecalculationError=null,o)throw o;var a=!0,i=!0;g&&u&&(a=r||t&&this.doStatePropsDependOnOwnProps,i=t&&this.doDispatchPropsDependOnOwnProps);var f=!1,l=!1;n?f=!0:a&&(f=this.updateStatePropsIfNeeded()),i&&(l=this.updateDispatchPropsIfNeeded());var d=!0;return d=!!(f||l||t)&&this.updateMergedPropsIfNeeded(),!d&&u?u:(O?this.renderedElement=(0,s.createElement)(e,c({},this.mergedProps,{ref:"wrappedInstance"})):this.renderedElement=(0,s.createElement)(e,this.mergedProps),this.renderedElement)},i}(s.Component);return n.displayName=r,n.WrappedComponent=e,n.contextTypes={store:p["default"]},n.propTypes={store:p["default"]},(0,P["default"])(n,e)}}var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.__esModule=!0,t["default"]=l;var s=r(8),d=r(185),p=n(d),v=r(184),h=n(v),y=r(187),b=n(y),m=r(186),g=(n(m),r(3)),_=(n(g),r(108)),P=n(_),O=r(109),j=n(O),T=function(e){return{}},S=function(e){return{dispatch:e}},E=function(e,t,r){return c({},r,e,t)},M={value:null},x=0},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return"string"==typeof e||"number"==typeof e?""+e:""}function u(e){return(0,i["default"])(e.model)?!!e.modelValue&&e.modelValue.some(function(t){return t===e.value}):!!e.modelValue}Object.defineProperty(t,"__esModule",{value:!0});var a=r(51),i=n(a),f=r(9),l=n(f),c=r(10),s=n(c),d={value:function(e){return e.defaultValue||e.hasOwnProperty("value")?e.value:o(e.viewValue)},name:function(e){return e.name||e.model}},p={"default":d,checkbox:{name:function(e){return e.name||e.model},checked:function(e){return e.defaultChecked?e.checked:u(e)},changeAction:function(e){return function(t){var r=e.modelValue,n=e.value;if((0,i["default"])(t)){var o=r||[],u=(o||[]).filter(function(e){return e!==n}),a=u.length===o.length?l["default"].push(o,n):u;return s["default"].change(t,a)}return s["default"].change(t,!r)}}},radio:{name:function(e){return e.name||e.model},checked:function(e){return e.defaultChecked?e.checked:e.modelValue===e.value},value:function(e){return e.value}},select:{name:function(e){return e.name||e.model},value:function(e){return e.modelValue}},text:d,textarea:d,file:{name:function(e){return e.name||e.model}},reset:{onClick:function(e){return function(t){t.preventDefault(),e.dispatch(s["default"].reset(e.model))}}},label:{htmlFor:function(e){return e.htmlFor||e.model}}};t["default"]=p},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return function(){var r=arguments.length<=0||void 0===arguments[0]?t:arguments[0],n=arguments[1];return n.type===a["default"].BATCH?n.actions.reduce(e,r):e(r,n)}}Object.defineProperty(t,"__esModule",{value:!0});var u=r(1),a=n(u);t["default"]=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return l["default"].setIn(e,t,r)}function u(){var e=arguments.length<=0||void 0===arguments[0]?i["default"]:arguments[0],t=arguments.length<=1||void 0===arguments[1]?o:arguments[1],r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n){var o=arguments.length<=1||void 0===arguments[1]?r:arguments[1],u=(0,p["default"])(n),a=function(){var r=arguments.length<=0||void 0===arguments[0]?o:arguments[0],n=arguments[1];if(!n.model)return r;var a=(0,p["default"])(n.model);if(!(0,s["default"])(a.slice(0,u.length),u))return r;var i=a.slice(u.length);switch(n.type){case h["default"].CHANGE:case h["default"].LOAD:return i.length?e(r,i)===n.value?r:t(r,i,n.value):n.value;case h["default"].RESET:return i.length?e(r,i)===e(o,i)?r:t(r,i,e(o,i)):o;default:return r}};return(0,b["default"])(a,o)}}Object.defineProperty(t,"__esModule",{value:!0}),t.createModeler=void 0;var a=r(2),i=n(a),f=r(9),l=n(f),c=r(47),s=n(c),d=r(19),p=n(d),v=r(1),h=n(v),y=r(29),b=n(y),m=u();t.createModeler=u,t["default"]=m},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=(0,s["default"])(e,t);if(!t.length)return r;var n=(0,f["default"])(r.$form.model),o=(0,f["default"])(t).slice(n.length),u=(0,a["default"])(r,o,l.initialFieldState);return u&&"$form"in u?u.$form:u?u:l.initialFieldState}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(2),a=n(u),i=r(19),f=n(i),l=r(7),c=r(17),s=n(c)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=(0,a["default"])(t);return"function"==typeof e?e(r):(0,f["default"])(e,function(e){return o(e,r)})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(33),a=n(u),i=r(4),f=n(i)},function(e,t){"use strict";function r(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function n(e){return!!(e&&e.stopPropagation&&e.preventDefault)}function o(e){var t=e.target;if(!t){if(!e.nativeEvent)return;return e.nativeEvent.text}return"file"===t.type?[].concat(r(t.files))||t.dataTransfer&&[].concat(r(t.dataTransfer.files)):t.multiple?[].concat(r(t.selectedOptions)).map(function(e){return e.value}):t.value}function u(e){return n(e)?o(e):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return Array.isArray(e)?e:Array.from(e)}function u(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];return function(t){var n=e.split(/\[\]\.?/),u=o(n),a=u[0],i=u.slice(1),l=a,s=(0,c["default"])(t,l);return r.forEach(function(e,t){var r=i[t],n=(0,d["default"])(e),o=r?(0,f["default"])(s,n)+"."+r:""+(0,f["default"])(s,n);s=(0,c["default"])(s,o),l+="."+o}),l}}function a(e){return function(t){for(var r=arguments.length,n=Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];return"function"==typeof t?function(r,o){var u=t(o());r(e.apply(void 0,[u].concat(n)))}:e.apply(void 0,[t].concat(n))}}Object.defineProperty(t,"__esModule",{value:!0}),t.trackable=t.track=void 0;var i=r(97),f=n(i),l=r(2),c=n(l),s=r(52),d=n(s);t.track=u,t.trackable=a},function(e,t){function r(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}e.exports=r},function(e,t,r){var n=r(123),o=r(140),u=o(n);e.exports=u},function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},function(e,t,r){var n=r(142),o="object"==typeof self&&self&&self.Object===Object&&self,u=n||o||Function("return this")();e.exports=u},function(e,t,r){function n(e,t,r){e=i(e),t=u(t);var n=e.length;r=void 0===r?n:o(a(r),0,n);var f=r;return r-=t.length,r>=0&&e.slice(r,f)==t}var o=r(118),u=r(61),a=r(182),i=r(71);e.exports=n},function(e,t,r){function n(e){var t=o(e)?f.call(e):"";return t==u||t==a}var o=r(24),u="[object Function]",a="[object GeneratorFunction]",i=Object.prototype,f=i.toString;e.exports=n},function(e,r){e.exports=t},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=t.filter(function(e){return!!e});return r.length?r.length&&r.every(s["default"])?1===r.length?r[0]:{type:i["default"].BATCH,model:e,actions:r}:function(t){var n=(0,l["default"])(r,function(e){return"function"!=typeof e}),o=u(n,2),a=o[0],f=o[1];a.length>1?t({type:i["default"].BATCH,model:e,actions:a}):1===a.length&&t(a[0]),f.forEach(t)}:d}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){var r=[],n=!0,o=!1,u=void 0;try{for(var a,i=e[Symbol.iterator]();!(n=(a=i.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(f){o=!0,u=f}finally{try{!n&&i["return"]&&i["return"]()}finally{if(o)throw u}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=r(1),i=n(a),f=r(103),l=n(f),c=r(3),s=n(c),d={type:i["default"].NULL};t["default"]={batch:o}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(2),i=n(a),f=r(4),l=n(f),c=r(1),s=n(c),d=r(42),p=n(d),v=r(32),h=n(v),y=r(102),b=n(y),m=r(101),g=n(m),_=r(34),P=r(17),O=n(P),j=r(11),T=n(j),S=(0,_.trackable)(function(e){return{type:s["default"].FOCUS,model:e}}),E=(0,_.trackable)(function(e){return{type:s["default"].BLUR,model:e}}),M=(0,_.trackable)(function(e){return{type:s["default"].SET_PRISTINE,model:e}}),x=(0,_.trackable)(function(e){return{type:s["default"].SET_DIRTY,model:e}}),w=(0,_.trackable)(function(e){return{type:s["default"].SET_INITIAL,model:e}}),k=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_PENDING,model:e,pending:t}}),V=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_VALIDATING,model:e,validating:t}}),A=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return o({type:r.errors?s["default"].SET_ERRORS:s["default"].SET_VALIDITY,model:e},r.errors?"errors":"validity",t)}),C=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return{type:s["default"].SET_FIELDS_VALIDITY,model:e,fieldsValidity:t,options:r}}),I=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return A(e,t,u({},r,{errors:!0}))}),F=(0,_.trackable)(function(e,t,r){return C(e,t,u({},r,{errors:!0}))}),D=(0,_.trackable)(function(e){return{type:s["default"].RESET_VALIDITY,model:e}}),R=D,N=(0,_.trackable)(function(e){return{type:s["default"].SET_TOUCHED,model:e}}),$=(0,_.trackable)(function(e){return{type:s["default"].SET_UNTOUCHED,model:e}}),U=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e);r(V(e,!0));var u=function(t){r(A(e,t))},a=t(o,u);"undefined"!=typeof a&&u(a)}}),L=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_SUBMITTED,model:e,submitted:t}}),H=(0,_.trackable)(function(e){var t=arguments.length<=1||void 0===arguments[1]||arguments[1];return{type:s["default"].SET_SUBMIT_FAILED,model:e,submitFailed:t}}),B=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n){n(k(e,!0));var o=r.fields?F:I;return t.then(function(t){n(p["default"].batch(e,[L(e,!0),A(e,t)]))})["catch"](function(t){n(p["default"].batch(e,[H(e),o(e,t)]))}),t}}),G=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return B(e,t,u({},r,{fields:!0}))}),K=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e),u=(0,h["default"])(t,o);r(A(e,u))}}),q=(0,_.trackable)(function(e,t){return function(r,n){var o=(0,i["default"])(n(),e),u=(0,h["default"])(t,o);r(A(e,u,{errors:!0}))}}),Y=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return function(n,o){var u=(0,i["default"])(o(),e),a=(0,l["default"])(t,function(e,t){var r=t?(0,i["default"])(u,t):u,n=(0,h["default"])(e,r);return n}),f=r.onValid,c=r.onInvalid;if(f||c){var s=(0,O["default"])(o(),e),d=!(s&&!a.hasOwnProperty(""))||(0,T["default"])(s),p=r.errors?!(0,g["default"])(a):(0,b["default"])(a);f&&d&&p?f():c&&c()}var v=r.errors?F:C;n(v(e,a))}}),W=(0,_.trackable)(function(e,t){var r=arguments.length<=2||void 0===arguments[2]?{}:arguments[2];return Y(e,t,u({},r,{errors:!0}))});t["default"]={blur:E,focus:S,submit:B,submitFields:G,setDirty:x,setErrors:I,setInitial:w,setPending:k,setValidating:V,setPristine:M,setSubmitted:L,setSubmitFailed:H,setTouched:N,setUntouched:$,setValidity:A,setFieldsValidity:C,setFieldsErrors:F,resetValidity:D,resetErrors:R,validate:K,validateErrors:q,validateFields:Y,validateFieldsErrors:W,asyncSetValidity:U}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(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 f(e,t){var r=t.model,n=t.mapProps,o=t.getter,u=void 0===o?O["default"]:o,a=t.controlProps,i=void 0===a?(0,A["default"])(t,Object.keys(te)):a;if(!n)return t;var f=(0,G["default"])(r,e),l=(0,H["default"])(e,f);return{model:r,modelValue:u(e,f),fieldValue:l,controlProps:i}}function l(e){return~["radio","checkbox"].indexOf(e.type)}Object.defineProperty(t,"__esModule",{value:!0});var c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),d=r(8),p=r(188),v=r(27),h=n(v),y=r(41),b=r(14),m=n(b),g=r(12),_=n(g),P=r(2),O=n(P),j=r(54),T=n(j),S=r(4),E=n(S),M=r(3),x=n(M),w=r(9),k=n(w),V=r(26),A=n(V),C=r(72),I=n(C),F=r(33),D=n(F),R=r(32),N=n(R),$=r(50),U=n($),L=r(31),H=n(L),B=r(18),G=n(B),K=r(105),q=n(K),Y=r(10),W=n(Y),z=r(11),J=n(z),Q=r(28),X=n(Q),Z=r(78),ee=n(Z),te={model:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]),modelValue:d.PropTypes.any,viewValue:d.PropTypes.any,control:d.PropTypes.any,onLoad:d.PropTypes.func,onSubmit:d.PropTypes.func,fieldValue:d.PropTypes.object,mapProps:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),changeAction:d.PropTypes.func,updateOn:d.PropTypes.string,validateOn:d.PropTypes.string,validators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),asyncValidateOn:d.PropTypes.string,asyncValidators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),errors:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),controlProps:d.PropTypes.object,component:d.PropTypes.any,dispatch:d.PropTypes.func,parser:d.PropTypes.func,formatter:d.PropTypes.func,getter:d.PropTypes.func, ignore:d.PropTypes.arrayOf(d.PropTypes.string),dynamic:d.PropTypes.bool},re=function(e){function t(e){u(this,t);var r=a(this,Object.getPrototypeOf(t).call(this,e));return r.getChangeAction=r.getChangeAction.bind(r),r.getValidateAction=r.getValidateAction.bind(r),r.handleKeyPress=r.handleKeyPress.bind(r),r.createEventHandler=r.createEventHandler.bind(r),r.handleFocus=r.createEventHandler("focus").bind(r),r.handleBlur=r.createEventHandler("blur").bind(r),r.handleUpdate=r.createEventHandler("change").bind(r),r.handleChange=r.handleChange.bind(r),r.handleLoad=r.handleLoad.bind(r),r.getMappedProps=r.getMappedProps.bind(r),r.attachNode=r.attachNode.bind(r),r.state={viewValue:e.modelValue,mappedProps:{}},r}return i(t,e),s(t,[{key:"componentWillMount",value:function(){var e=this.props,t=this.props.mapProps;this.setState({mappedProps:this.getMappedProps(e,t)})}},{key:"componentDidMount",value:function(){this.attachNode(),this.handleLoad()}},{key:"componentWillReceiveProps",value:function(e){var t=e.mapProps,r=e.modelValue;this.setState({viewValue:r,mappedProps:this.getMappedProps(e,t)})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,I["default"])(this,e,t)}},{key:"componentDidUpdate",value:function(e,t){var r=this.props,n=r.modelValue,o=r.fieldValue,u=r.validateOn,a=r.validators,i=r.errors,f=this.state.viewValue;(a||i)&&o&&!o.validated&&n!==e.modelValue&&"change"===u&&this.validate(),o.focus?document&&document.activeElement!==this.node&&this.node.focus&&this.node.focus():document&&document.activeElement===this.node&&this.node.blur&&this.node.blur(),t.viewValue!==f&&this.updateMappedProps()}},{key:"componentWillUnmount",value:function(){var e=this.props,t=e.model,r=e.fieldValue,n=e.dispatch;r&&((0,J["default"])(r)||n(W["default"].resetValidity(t)))}},{key:"getMappedProps",value:function(e,t){var r=this.state.viewValue,n=c({},e,e.controlProps,{onFocus:this.handleFocus,onBlur:this.handleBlur,onChange:this.handleChange,onKeyPress:this.handleKeyPress,viewValue:r});return(0,x["default"])(t)?k["default"].merge(n,(0,E["default"])(t,function(e,t){return"function"==typeof e&&"component"!==t?e(n):e})):t(n)}},{key:"getChangeAction",value:function(e){var t=this.props,r=t.model,n=t.controlProps,o=this.state.mappedProps.changeAction,u=void 0===o?W["default"].change:o,a=l(n)?n.value:e;return u(r,(0,D["default"])(a))}},{key:"getValidateAction",value:function(e){var t=this.props,r=t.validators,n=t.errors,o=t.model,u=t.fieldValue,a=this.getNodeErrors();if(r||n){var i=(0,N["default"])(r,e),f=(0,T["default"])((0,N["default"])(n,e),a),l=r?(0,T["default"])((0,U["default"])(i),f):f;if(!u||!(0,_["default"])(l,u.errors))return W["default"].setErrors(o,l)}else if(a)return W["default"].setErrors(o,a);return!1}},{key:"getAsyncValidateAction",value:function(e){var t=this.props,r=t.asyncValidators,n=t.fieldValue,u=t.model;return!!r&&function(t){return(0,E["default"])(r,function(r,a){return t(W["default"].asyncSetValidity(u,function(t,u){var i=function(e){var t=k["default"].merge(n.validity,o({},a,e));u(t)};r((0,D["default"])(e),i)}))}),e}}},{key:"getNodeErrors",value:function(){var e=this.node;if(!e||!e.willValidate)return null;var t={};return ee["default"].forEach(function(r){t[r]=e.validity[r]}),t}},{key:"updateMappedProps",value:function(){var e=this.props.mapProps;this.setState({mappedProps:this.getMappedProps(this.props,e)})}},{key:"handleChange",value:function(e){this.setState({viewValue:(0,D["default"])(e)}),this.handleUpdate(e)}},{key:"handleKeyPress",value:function(e){"Enter"===e.key&&this.handleSubmit(e)}},{key:"handleLoad",value:function(){var e=this.props,t=e.model,r=e.modelValue,n=e.fieldValue,o=e.controlProps,u=void 0===o?{}:o,a=e.onLoad,i=e.dispatch,f=[],l=void 0;u.hasOwnProperty("defaultValue")?l=u.defaultValue:u.hasOwnProperty("defaultChecked")&&(l=u.defaultChecked),"undefined"!=typeof l?(f.push(this.getValidateAction(l)),f.push(W["default"].change(t,l))):f.push(this.getValidateAction(r)),i(W["default"].batch(t,f)),a&&a(r,n,this.node)}},{key:"handleSubmit",value:function(e){var t=this.props.dispatch;t(this.getChangeAction(e))}},{key:"createEventHandler",value:function(e){var t=this,r=this.props,n=r.dispatch,o=r.model,u=r.updateOn,a=r.validateOn,i=r.asyncValidateOn,f=r.controlProps,c=void 0===f?{}:f,s=r.parser,d=r.ignore,p={focus:W["default"].focus,blur:W["default"].blur}[e],v={focus:c.onFocus,blur:c.onBlur,change:c.onChange}[e],h=function(r){var f=p?[p(o)]:[];a===e&&f.push(t.getValidateAction(r)),i===e&&f.push(t.getAsyncValidateAction(r)),u===e&&f.push(t.getChangeAction(r));var l=f.filter(function(e){return!!e});return l.length&&n(W["default"].batch(o,l)),r};return function(t){return~d.indexOf(e)?v?v(t):t:l(c)?(0,y.compose)(h,(0,q["default"])(v||m["default"]))(t):(0,y.compose)(h,s,D["default"],(0,q["default"])(v||m["default"]))(t)}}},{key:"attachNode",value:function(){var e=(0,p.findDOMNode)(this);e&&(this.node=e)}},{key:"validate",value:function(){var e=this.props,t=e.model,r=e.modelValue,n=e.fieldValue,o=e.validators,u=e.errors,a=e.dispatch;if(!o&&!u)return r;var i=(0,N["default"])(o,r),f=(0,N["default"])(u,r),l=o?(0,T["default"])((0,U["default"])(i),f):f;return(0,_["default"])(l,n.errors)||a(W["default"].setErrors(t,l)),r}},{key:"render",value:function(){var e=this.props,t=e.controlProps,r=void 0===t?{}:t,n=e.component,o=e.control,u=(0,A["default"])(this.state.mappedProps,Object.keys(te));return o?(0,d.cloneElement)(o,c({},u,{onKeyPress:this.handleKeyPress})):(0,d.createElement)(n,c({},r,u,{onKeyPress:this.handleKeyPress}),r.children)}}]),t}(d.Component);re.propTypes=te,re.defaultProps={changeAction:W["default"].change,updateOn:"change",parser:m["default"],formatter:m["default"],controlProps:{},getter:O["default"],ignore:[],dynamic:!1};var ne=(0,h["default"])(f)(re);ne.text=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.text.defaultProps=c({},ne.defaultProps,{component:"input",mapProps:X["default"].text}),ne.radio=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.radio.defaultProps=c({},ne.defaultProps,{component:"input",type:"radio",mapProps:X["default"].radio}),ne.checkbox=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.checkbox.defaultProps=c({},ne.defaultProps,{component:"input",type:"checkbox",mapProps:X["default"].checkbox}),ne.file=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.file.defaultProps=c({},ne.defaultProps,{component:"input",type:"file",mapProps:X["default"].file}),ne.select=function(e){function t(){return u(this,t),a(this,Object.getPrototypeOf(t).apply(this,arguments))}return i(t,e),t}(ne),ne.select.defaultProps=c({},ne.defaultProps,{component:"select",mapProps:X["default"].select}),t["default"]=ne},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(){var e=arguments.length<=0||void 0===arguments[0]?a["default"]:arguments[0];return function(t,r){var n=void 0;try{n=t(void 0,f["default"])}catch(o){n=null}var u=e(r,n);return function(){var e=arguments.length<=0||void 0===arguments[0]?n:arguments[0],r=arguments[1],o=u(e,r);return t(o,r)}}}Object.defineProperty(t,"__esModule",{value:!0}),t.createModelReducerEnhancer=void 0;var u=r(30),a=n(u),i=r(77),f=n(i),l=o(a["default"]);t.createModelReducerEnhancer=o,t["default"]=l},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t["default"]=e,t}function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.track=t.getField=t.utils=t.form=t.batched=t.modeled=t.createFieldClass=t.Errors=t.Form=t.Control=t.Field=t.controls=t.actionTypes=t.actions=t.initialFieldState=t.combineForms=t.modelReducer=t.formReducer=void 0;var u=r(10),a=o(u),i=r(1),f=o(i),l=r(75),c=o(l),s=r(44),d=o(s),p=r(76),v=o(p),h=r(74),y=o(h),b=r(28),m=o(b),g=r(45),_=o(g),P=r(29),O=o(P),j=r(7),T=o(j),S=r(95),E=o(S),M=r(30),x=o(M),w=r(34),k=r(49),V=n(k),A=r(79),C=o(A);t.formReducer=T["default"],t.modelReducer=x["default"],t.combineForms=E["default"],t.initialFieldState=j.initialFieldState,t.actions=a["default"],t.actionTypes=f["default"],t.controls=m["default"],t.Field=c["default"],t.Control=d["default"],t.Form=v["default"],t.Errors=y["default"],t.createFieldClass=l.createFieldClass,t.modeled=_["default"],t.batched=O["default"],t.form=C["default"],t.utils=V,t.getField=j.getField,t.track=w.track},function(e,t){"use strict";function r(e,t){return e&&t&&e.length===t.length&&e.every(function(e,r){return e===t[r]})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=e.children,n=t.children;if(i["default"].Children.count(r)!==i["default"].Children.count(n)||!i["default"].Children.count(r)||!i["default"].Children.count(n))return!0;var o=i["default"].Children.toArray(r),a=i["default"].Children.toArray(n);return[].concat(o).some(function(e,t){var r=a[t];return e.props&&r.props?u(e,r.props,r.state):!(0,s["default"])(e,r)})}function u(e,t,r){return e.props.children?(0,l["default"])(e,t,r)&&o(e.props,t):(0,l["default"])(e,t,r)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(8),i=n(a),f=r(72),l=n(f),c=r(12),s=n(c)},function(e,t){},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e)?(0,f["default"])(e,o):!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(4),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e,"[]")}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(39),a=n(u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return function(t){return t===e||Object.keys(e).every(function(r){return e[r]===t[r]})}}function u(e){return function(t){return t&&!!t[e]}}function a(e){return"function"==typeof e?e:null===e?l["default"]:"object"===("undefined"==typeof e?"undefined":i(e))?o(e):u(e)}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};t["default"]=a;var f=r(14),l=n(f)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=Array.isArray(e)?a["default"]:f["default"];return r(e,t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(13),a=n(u),i=r(131),f=n(i)},function(e,t){"use strict";function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e){return e&&"object"===("undefined"==typeof e?"undefined":u(e))&&!Array.isArray(e)&&null!==e}function o(e,t){return n(e)&&n(t)&&Object.keys(t).forEach(function(u){n(t[u])?(e[u]||Object.assign(e,r({},u,{})),o(e[u],t[u])):Object.assign(e,r({},u,t[u]))}),e}Object.defineProperty(t,"__esModule",{value:!0});var u="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"]=o},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(162),u=r(163),a=r(164),i=r(165),f=r(166);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){var n=r(38),o=n.Symbol;e.exports=o},function(e,t,r){function n(e,t){var r=a(e)||f(e)||u(e)?o(e.length,String):[],n=r.length,l=!!n;for(var s in e)!t&&!c.call(e,s)||l&&("length"==s||i(s,n))||r.push(s);return r}var o=r(134),u=r(68),a=r(6),i=r(153),f=r(176),l=Object.prototype,c=l.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t,r,a,i){var f=-1,l=e.length;for(r||(r=u),i||(i=[]);++f<l;){var c=e[f];t>0&&r(c)?t>1?n(c,t-1,r,a,i):o(i,c):a||(i[i.length]=c)}return i}var o=r(35),u=r(152);e.exports=n},function(e,t,r){function n(e,t){return e=Object(e),o(e,t,function(t,r){return r in e})}var o=r(132);e.exports=n},function(e,t,r){function n(e,t){return t=u(void 0===t?e.length-1:t,0),function(){for(var r=arguments,n=-1,a=u(r.length-t,0),i=Array(a);++n<a;)i[n]=r[t+n];n=-1;for(var f=Array(t+1);++n<t;)f[n]=r[n];return f[t]=i,o(e,this,f)}}var o=r(114),u=Math.max;e.exports=n},function(e,t,r){function n(e){if("string"==typeof e)return e;if(u(e))return f?f.call(e):"";var t=e+"";return"0"==t&&1/e==-a?"-0":t}var o=r(56),u=r(16),a=1/0,i=o?o.prototype:void 0,f=i?i.toString:void 0;e.exports=n},function(e,t,r){function n(e,t){var r=u(e,t);return o(r)?r:void 0}var o=r(128),u=r(146);e.exports=n},function(e,t,r){var n=r(37),o=n(Object.getPrototypeOf,Object);e.exports=o},function(e,t){function r(e){var t=!1;if(null!=e&&"function"!=typeof e.toString)try{t=!!(e+"")}catch(r){}return t}e.exports=r},function(e,t){function r(e){var t=e&&e.constructor,r="function"==typeof t&&t.prototype||n;return e===r}var n=Object.prototype;e.exports=r},function(e,t,r){var n=r(179),o=r(71),u=/^\./,a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,i=/\\(\\)?/g,f=n(function(e){e=o(e);var t=[];return u.test(e)&&t.push(""),e.replace(a,function(e,r,n,o){t.push(n?o.replace(i,"$1"):r||e)}),t});e.exports=f},function(e,t){function r(e){for(var t=-1,r=e?e.length:0,n=0,o=[];++t<r;){var u=e[t];u&&(o[n++]=u)}return o}e.exports=r},function(e,t,r){function n(e){return o(e)&&i.call(e,"callee")&&(!l.call(e,"callee")||f.call(e)==u)}var o=r(174),u="[object Arguments]",a=Object.prototype,i=a.hasOwnProperty,f=a.toString,l=a.propertyIsEnumerable;e.exports=n},function(e,t){function r(){return[]}e.exports=r},function(e,t,r){function n(e){return a(e)?o(e,l):i(e)?[e]:u(f(e))}var o=r(13),u=r(138),a=r(6),i=r(16),f=r(66),l=r(23);e.exports=n},function(e,t,r){function n(e){return null==e?"":o(e)}var o=r(61);e.exports=n},function(e,t,r){"use strict";function n(e,t,r){return!o(e.props,t)||!o(e.state,r)}var o=r(107);e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function u(){var e=arguments.length<=0||void 0===arguments[0]?O:arguments[0],t=function(t,r){var n=arguments.length<=2||void 0===arguments[2]?{}:arguments[2],o=a({silent:!1,multi:(0,y["default"])(t)},n);return a({type:m["default"].CHANGE,model:t,value:e.getValue(r)},o)},r=function(t,r){var n=arguments.length<=2||void 0===arguments[2]?function(e){return e===r}:arguments[2];return function(u,a){var i=e.get(a(),t,[]),f=i.filter(function(e){return!n(e)}),l=i.length===f.length?[].concat(o(i),[r]):f;u({type:m["default"].CHANGE,model:t,value:l})}},n=function(t){var r=arguments.length<=1||void 0===arguments[1]?null:arguments[1];return function(n,u){var a=e.get(u(),t),i=[].concat(o(a||[]),[r]);n({type:m["default"].CHANGE,model:t,value:i})}},u=function(t){return function(r,n){var o=!e.get(n(),t);r({type:m["default"].CHANGE,model:t,value:o})}},i=function(t){var r=arguments.length<=1||void 0===arguments[1]?c["default"]:arguments[1];return function(n,o){var u=e.get(o(),t),a=u.filter(r);n({type:m["default"].CHANGE,model:t,value:a})}},f=function(e){return{type:m["default"].RESET,model:e}},l=function(t){var r=arguments.length<=1||void 0===arguments[1]?c["default"]:arguments[1];return function(n,o){var u=e.get(o(),t,[]),a=u.map(r);n({type:m["default"].CHANGE,model:t,value:a})}},s=function(t,r){return function(n,o){var u=e.get(o(),t,[]);n({type:m["default"].CHANGE,model:t,value:e.splice(u,r,1),removeKeys:[r]})}},d=function(t,r,n){return function(o,u){var a=e.get(u(),t,[]);if(r>=a.length||n>=a.length)throw new Error("Error moving array item: invalid bounds "+r+", "+n);var i=a[r],f=e.splice(a,r,1),l=e.splice(f,n,0,i);o({type:m["default"].CHANGE,model:t,value:l})}},p=function(t,r){return function(n,o){var u=e.get(o(),t,{});n({type:m["default"].CHANGE,model:t,value:e.merge(u,r)})}},v=function(t){var r=arguments.length<=1||void 0===arguments[1]?[]:arguments[1];return function(n,o){var u=e.get(o(),t,{}),a="string"==typeof r?[r]:r,i=a.reduce(function(t,r){return e.remove(t,r)},u);n({type:m["default"].CHANGE,model:t,value:i,removeKeys:a})}},h=function(e,r){return t(e,r,{silent:!0})};return(0,_["default"])({change:t,filter:i,map:l,merge:p,push:n,remove:s,move:d,reset:f,toggle:u,xor:r,load:h,omit:v},P.trackable)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=r(2),f=n(i),l=r(14),c=n(l),s=r(9),d=n(s),p=r(33),v=n(p),h=r(51),y=n(h),b=r(1),m=n(b),g=r(4),_=n(g),P=r(34),O={get:f["default"],getValue:v["default"],splice:d["default"].splice,merge:d["default"].merge,remove:d["default"].dissoc};t["default"]=u()},function(e,t,r){"use strict";function n(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 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 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)}function i(e,t){var r=arguments.length<=2||void 0===arguments[2]||arguments[2];return"function"==typeof r?r(e,t):(0,T["default"])(r)||"object"===("undefined"==typeof r?"undefined":c(r))||"string"==typeof r?(0,O["default"])(r)(e):!!r}function f(e,t){var r=t.model,n=(0,I["default"])(r,e),o=(0,k["default"])(e,n).$form,u=(0,A["default"])(e,n);return{model:n,modelValue:(0,y["default"])(e,n),formValue:o,fieldValue:u}}Object.defineProperty(t,"__esModule",{value:!0});var l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),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},s=r(8),d=n(s),p=r(27),v=n(p),h=r(2),y=n(h),b=r(53),m=n(b),g=r(67),_=n(g),P=r(52),O=n(P),j=r(6),T=n(j),S=r(3),E=n(S),M=r(26),x=n(M),w=r(17),k=n(w),V=r(31),A=n(V),C=r(18),I=n(C),F=r(11),D=n(F),R=function(e){function t(){return o(this,t),u(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),l(t,[{key:"shouldComponentUpdate",value:function(e){var t=e.fieldValue,r=e.formValue;return t!==this.props.fieldValue||r!==this.props.formValue}},{key:"mapErrorMessages",value:function(e){var t=this,r=this.props.messages;if("string"==typeof e)return this.renderError(e,"error");if(!e)return null;var n=(0,_["default"])((0,m["default"])(e,function(e,n){var o=r[n];if(e){if(o)return t.renderError(o,n);if("string"==typeof e)return t.renderError(e,n);if((0,E["default"])(e))return t.mapErrorMessages(e)}return!1})).reduce(function(e,t){return e.concat(t)},[]);return n.length?n:null}},{key:"renderError",value:function(e,t){var r=this.props,n=r.component,o=r.model,u=r.modelValue,a=r.fieldValue,i=r.fieldValue.errors,f={key:t,model:o,modelValue:u,fieldValue:a},l="function"==typeof e?e(u,i[t]):e;if(!l)return null;var c="function"==typeof n?f:{key:t};return d["default"].createElement(n,c,l)}},{key:"render",value:function(){var e=this.props,r=e.fieldValue,n=e.formValue,o=e.show,u=e.wrapper,a="function"==typeof u?this.props:(0,x["default"])(this.props,Object.keys(t.propTypes));if(!i(r,n,o))return null;var f=(0,D["default"])(r)?null:this.mapErrorMessages(r.errors);return f?d["default"].createElement(u,a,f):null}}]),t}(s.Component);R.propTypes={modelValue:s.PropTypes.any,formValue:s.PropTypes.object,fieldValue:s.PropTypes.object,model:s.PropTypes.string.isRequired,messages:s.PropTypes.objectOf(s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.bool])),show:s.PropTypes.any,wrapper:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.element]),component:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.func,s.PropTypes.element]),dispatch:s.PropTypes.func},R.defaultProps={wrapper:"div",component:"span",messages:{},show:!0},t["default"]=(0,v["default"])(f)(R)},function(e,t,r){"use strict";function n(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 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 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)}function i(e,t){var r=t.model,n=(0,D["default"])(r,e),o=(0,N["default"])(e,n);return{model:r,fieldValue:o}}function f(e,t,r){var n=r.controlPropsMap,o=Object.keys(n).filter(function(t){var r=n[t];return!(!(0,_["default"])(r)||!r.component)&&e.type===r.component});if(o.length)return o[0];try{var u=e.constructor.displayName||e.type.displayName||e.type.name||e.type;return"input"===u&&(u=n[e.props.type]?e.props.type:"text"),n[u]?u:null}catch(a){return}}function l(){var e=arguments.length<=0||void 0===arguments[0]?{}:arguments[0],t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r={controlPropsMap:s({},k["default"],e)},n=function(e){function t(){return o(this,t),u(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),c(t,[{key:"shouldComponentUpdate",value:function(e){var t=this.props.dynamic;return t?(0,A["default"])(this,e):(0,I["default"])(this,e)}},{key:"createControlComponent",value:function(e){var t=this.props;if(!e||!e.props||e instanceof x["default"])return e;var n=f(e,t,r),o=t.mapProps,u=void 0===o?r.controlPropsMap[n]:o,a=(0,O["default"])(t,Object.keys($));return u?p["default"].createElement(x["default"],s({},a,{control:e,controlProps:e.props,component:e.type,mapProps:u})):p["default"].cloneElement(e,null,this.mapChildrenToControl(e.props.children))}},{key:"mapChildrenToControl",value:function(e){var t=this;return p["default"].Children.count(e)>1?p["default"].Children.map(e,function(e){return t.createControlComponent(e)}):this.createControlComponent(e)}},{key:"render",value:function(){var e=this,t=this.props,r=t.component,n=t.children,o=t.fieldValue,u=(0,m["default"])(t,Object.keys($)),a="function"==typeof n?n(o):n;return p["default"].createElement(r,u,p["default"].Children.map(a,function(t){return e.createControlComponent(t)}))}}]),t}(d.Component);return n.propTypes=$,n.defaultProps=s({updateOn:"change",validateOn:"change",asyncValidateOn:"blur",parser:y["default"],changeAction:E["default"].change,dynamic:!1,component:"div"},t),(0,T["default"])(i)(n)}Object.defineProperty(t,"__esModule",{value:!0}),t.createFieldClass=t.controlPropsMap=void 0;var c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d=r(8),p=n(d),v=r(2),h=(n(v),r(14)),y=n(h),b=r(26),m=n(b),g=r(3),_=n(g),P=r(180),O=n(P),j=r(27),T=n(j),S=r(10),E=n(S),M=r(44),x=n(M),w=r(28),k=n(w),V=r(48),A=n(V),C=r(106),I=n(C),F=r(18),D=n(F),R=r(31),N=n(R),$={model:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]).isRequired,component:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.string]),parser:d.PropTypes.func,updateOn:d.PropTypes.oneOf(["change","blur","focus"]),changeAction:d.PropTypes.func,validators:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),asyncValidators:d.PropTypes.object,validateOn:d.PropTypes.string,asyncValidateOn:d.PropTypes.string,errors:d.PropTypes.oneOfType([d.PropTypes.func,d.PropTypes.object]),mapProps:d.PropTypes.func,componentMap:d.PropTypes.object,dynamic:d.PropTypes.bool,dispatch:d.PropTypes.func,getter:d.PropTypes.func,fieldValue:d.PropTypes.object};t.controlPropsMap=k["default"],t.createFieldClass=l,t["default"]=l(k["default"])},function(e,t,r){"use strict";function n(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 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 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)}function i(e,t){var r=t.model,n=(0,R["default"])(r,e);return{modelValue:(0,b["default"])(e,n),formValue:(0,F["default"])(e,n)}}Object.defineProperty(t,"__esModule",{value:!0});var f=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c=r(8),s=n(c),d=r(27),p=n(d),v=r(12),h=n(v),y=r(2),b=n(y),m=r(4),g=n(m),_=r(54),P=n(_),O=r(14),j=n(O),T=r(26),S=n(T),E=r(10),M=n(E),x=r(32),w=n(x),k=r(50),V=n(k),A=r(100),C=n(A),I=r(17),F=n(I),D=r(18),R=n(D),N=r(7),$=r(11),U=n($),L=r(48),H=n(L),B=function(e){function t(e){o(this,t);var r=u(this,Object.getPrototypeOf(t).call(this,e));return r.handleSubmit=r.handleSubmit.bind(r),r.handleReset=r.handleReset.bind(r),r.handleValidSubmit=r.handleValidSubmit.bind(r),r.handleInvalidSubmit=r.handleInvalidSubmit.bind(r),r.attachNode=r.attachNode.bind(r),r}return a(t,e),l(t,[{key:"componentDidMount",value:function(){"change"===this.props.validateOn&&this.validate(this.props,!0)}},{key:"componentWillReceiveProps",value:function(e){var t=this.props.validateOn;"change"===t&&this.validate(e)}},{key:"shouldComponentUpdate",value:function(e){return(0,H["default"])(this,e)}},{key:"attachNode",value:function(e){e&&(this._node=e,this._node.submit=this.handleSubmit)}},{key:"validate",value:function(e){var t=!(arguments.length<=1||void 0===arguments[1])&&arguments[1],r=this.props,n=r.validators,o=r.errors,u=r.model,a=r.dispatch,i=r.formValue,f=r.modelValue;if(i){if(!n&&!o&&f!==e.modelValue)return void((0,U["default"])(i)||a(M["default"].setValidity(u,!0)));var l=!1,c=(0,g["default"])(n,function(r,n){var o=n?(0,b["default"])(e.modelValue,n):e.modelValue,u=n?(0,b["default"])(f,n):f,a=(0,N.getField)(i,n).validity;if(!t&&o===u)return a;var c=(0,w["default"])(r,o);return(0,h["default"])(c,a)||(l=!0),c}),s=(0,g["default"])(o,function(r,n){var o=n?(0,b["default"])(e.modelValue,n):e.modelValue,u=n?(0,b["default"])(f,n):f,a=(0,N.getField)(i,n).errors;if(!t&&o===u)return(0,N.getField)(i,n).errors;var c=(0,w["default"])(r,o);return(0,h["default"])(c,a)||(l=!0),c}),d=(0,P["default"])((0,V["default"])(c),s);c.hasOwnProperty("")||s.hasOwnProperty("")||(d[""]=!1),l&&a(M["default"].setFieldsErrors(u,d))}}},{key:"handleValidSubmit",value:function(){var e=this.props,t=e.dispatch,r=e.model,n=e.modelValue,o=e.onSubmit,u=void 0===o?j["default"]:o;return t(M["default"].setPending(r)),u(n)}},{key:"handleInvalidSubmit",value:function(){var e=this.props,t=e.dispatch,r=e.model;t(M["default"].setSubmitFailed(r))}},{key:"handleReset",value:function(e){e&&e.preventDefault();var t=this.props,r=t.model,n=t.dispatch;n(M["default"].reset(r))}},{key:"handleSubmit",value:function(e){e&&e.preventDefault();var t=this.props,r=t.model,n=t.modelValue,o=t.formValue,u=t.onSubmit,a=t.dispatch,i=t.validators,f=t.errors,l=!o||o.valid;if(!i&&u&&l)return u(n),n;var c={onValid:this.handleValidSubmit,onInvalid:this.handleInvalidSubmit},s=i?(0,P["default"])((0,C["default"])(i),f):f;return a(M["default"].validateFieldsErrors(r,s,c)),n}},{key:"render",value:function(){var e=this.props,r=e.component,n=e.children,o=e.formValue,u=(0,S["default"])(this.props,Object.keys(t.propTypes)),a="function"==typeof n?n(o):n;return s["default"].createElement(r,f({},u,{onSubmit:this.handleSubmit,onReset:this.handleReset,ref:this.attachNode}),a)}}]),t}(c.Component);B.propTypes={component:c.PropTypes.any,validators:c.PropTypes.object,errors:c.PropTypes.object,validateOn:c.PropTypes.oneOf(["change","submit"]),model:c.PropTypes.string.isRequired,modelValue:c.PropTypes.any,formValue:c.PropTypes.object,onSubmit:c.PropTypes.func,dispatch:c.PropTypes.func,children:c.PropTypes.node},B.defaultProps={validateOn:"change",component:"form"},t["default"]=(0,p["default"])(i)(B)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={type:null};t["default"]=r},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"];t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return u({},e,{get valid(){return(0,i["default"])(e)},get pending(){return(0,l["default"])(e)},get touched(){return(0,s["default"])(e)},get retouched(){return(0,p["default"])(e)}})}Object.defineProperty(t,"__esModule",{value:!0}),t.isRetouched=t.isTouched=t.isPending=t.isValid=void 0;var u=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t["default"]=o;var a=r(11),i=n(a),f=r(80),l=n(f),c=r(82),s=n(c),d=r(81),p=n(d);t.isValid=i["default"],t.isPending=l["default"],t.isTouched=s["default"],t.isRetouched=p["default"]},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.pending)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.retouched)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e){return!!e&&(e.$form?Object.keys(e).some(function(t){return r(e[t])}):e.touched)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){if(t.type!==a["default"].BLUR&&t.type!==a["default"].SET_TOUCHED)return e;var n=(0,c["default"])(e,r).$form;return(0,f["default"])(e,r,function(e){return{focus:t.type!==a["default"].BLUR&&e.focus,touched:!0,retouched:!(!n.submitted&&!n.submitFailed)}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(98),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=void 0,n=t.value,u=t.removeKeys,f=t.silent;if((0,h["default"])(e.value,n))return e; if(f)return s["default"].set(e,"value",n);if(u){var l=function(){var t=[];return Object.keys(e).forEach(function(r){~u.indexOf(+r)||"$form"===r||(t[r]=e[r])}),{v:i({},(0,g["default"])(t),{$form:e.$form})}}();if("object"===("undefined"==typeof l?"undefined":a(l)))return l.v}if(Array.isArray(n))r=function(e,t){return Array.prototype.map.call(e,t).filter(function(e){return!!e})};else{if(!(0,b["default"])(n))return s["default"].merge(e,{value:n,pristine:!1,validated:!1,retouched:!!e.submitted||e.retouched});r=function(e,t){return(0,P["default"])(e,t)}}var c=r(n,function(t,r){var n=e[r];return!!n&&(Object.hasOwnProperty.call(n,"$form")?o(n,t):(0,h["default"])(t,n.value)?n:s["default"].merge(n,{value:t,pristine:!1,validated:!1,retouched:!!e.submitted||n.retouched}))}),d=s["default"].merge(e.$form||O.initialFieldState,{pristine:!1,validated:!1,retouched:!!e.submitted||(e.$form||O.initialFieldState).retouched});return s["default"].set(c,"$form",s["default"].set(d,"value",n))}function u(e,t,r){if(t.type!==l["default"].CHANGE)return e;var n=(0,p["default"])(e,r,O.initialFieldState),u=o(n,t);return r.length?s["default"].setIn(e,r,u):u}Object.defineProperty(t,"__esModule",{value:!0});var 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=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t["default"]=u;var f=r(1),l=n(f),c=r(9),s=n(c),d=r(2),p=n(d),v=r(12),h=n(v),y=r(3),b=n(y),m=r(67),g=n(m),_=r(4),P=n(_),O=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].FOCUS?e:(0,f["default"])(e,r,{focus:!0})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_PENDING?e:(0,f["default"])(e,r,function(){return{pending:t.pending,submitted:!1,submitFailed:!1,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].RESET&&t.type!==a["default"].SET_INITIAL?e:(0,f["default"])(e,r,l.initialFieldState,l.initialFieldState)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].RESET_VALIDITY?e:(0,f["default"])(e,r,{validity:l.initialFieldState.validity,errors:l.initialFieldState.errors},{validity:l.initialFieldState.validity,errors:l.initialFieldState.errors})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i),l=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_DIRTY?e:(0,f["default"])(e,r,{pristine:!1})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_PRISTINE?e:(0,f["default"])(e,r,{pristine:!0},{pristine:!0})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t,r){var n;if(t.type===s["default"].SET_FIELDS_VALIDITY)return(0,i["default"])(t.fieldsValidity,function(e,r){return l["default"].setValidity(r,e,t.options)}).reduce(function(e,t){return u(e,t,(0,P["default"])(t.model))},e);if(t.type===s["default"].SET_VALIDATING)return(0,g["default"])(e,r,{validating:t.validating,validated:!t.validating});if(t.type!==s["default"].SET_VALIDITY&&t.type!==s["default"].SET_ERRORS)return e;var a=t.type===s["default"].SET_ERRORS,f=a?t.errors:t.validity,c=(0,p["default"])(f)?(0,h["default"])(f,b["default"]):!f;return(0,g["default"])(e,r,(n={},o(n,a?"errors":"validity",f),o(n,a?"validity":"errors",c),o(n,"validating",!1),o(n,"validated",!0),n))}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=u;var a=r(53),i=n(a),f=r(43),l=n(f),c=r(1),s=n(c),d=r(3),p=n(d),v=r(4),h=n(v),y=r(99),b=n(y),m=r(5),g=n(m),_=r(19),P=n(_)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_SUBMIT_FAILED?e:(0,f["default"])(e,r,function(e){return{pending:!1,submitted:e.submitted&&!t.submitFailed,submitFailed:!!t.submitFailed,touched:!0,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){if(t.type!==a["default"].SET_SUBMITTED)return e;var n=!!t.submitted;return(0,f["default"])(e,r,function(e){return{pending:!1,submitted:n,submitFailed:!n&&e.submitFailed,touched:!0,retouched:!1}},function(e,t){return{submitted:n,submitFailed:!n&&t.submitFailed,retouched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t.type!==a["default"].SET_UNTOUCHED?e:(0,f["default"])(e,r,function(){return{focus:!1,touched:!1}})}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(1),a=n(u),i=r(5),f=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],r=Object.keys(e),n={},u={},i=a({},h,t),l=i.key,s=i.plugins;return r.forEach(function(t){var r=e[t];if("function"==typeof r){var o=void 0;try{o=r(void 0,v)}catch(a){o=null}n[t]=(0,f["default"])(r,t),u[t]=o}else n[t]=(0,c["default"])(t,r),u[t]=r}),(0,p.combineReducers)(a({},n,o({},l,(0,d["default"])("",u,{plugins:s}))))}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t["default"]=u;var i=r(45),f=n(i),l=r(30),c=n(l),s=r(7),d=n(s),p=r(41),v={type:null},h={key:"forms",plugins:[]}},function(e,t){"use strict";function r(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return function(e,r){return t.reduceRight(function(e,t){return t(e,r)},e)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t){"use strict";function r(e,t){var r=void 0;return Object.keys(e).some(function(n){var o=t(e[n],n,e);return!!o&&(r=n,!0)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=t.slice(0,-1);return r.length?(0,a["default"])(e,r):e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(2),a=n(u)},function(e,t){"use strict";function r(e){return!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return"function"==typeof e?function(t){return!e(t)}:(0,a["default"])(e,o)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(4),a=n(u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=Array.isArray(e)?f["default"]:c["default"];return(0,a["default"])(e)?t(e,o):!!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(117),f=n(i),l=r(133),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){return(0,a["default"])(e)?(0,f["default"])(e,o):!!e}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(3),a=n(u),i=r(120),f=n(i)},function(e,t){"use strict";function r(e,t){var r=[[],[]];return e.forEach(function(n,o){t(n,o,e)?r[0].push(n):r[1].push(n)}),r}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(e===t)return!0;var r=(0,a["default"])(e),n=(0,a["default"])(t),o=n.every(function(e,t){return r[t]===e});return o}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(70),a=n(u)},function(e,t){"use strict";function r(e){return function(t){return t&&t.persist&&t.persist(),e(t),t}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return!(0,i["default"])(e.props,t,["children"])||u.Children.count(e.props.children)!==u.Children.count(t.children)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var u=r(8),a=r(12),i=n(a)},function(e,t){"use strict";function r(e,t){return e===t?0!==e||1/e===1/t:e!==e&&t!==t}function n(e,t){if(r(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),u=Object.keys(t);if(n.length!==u.length)return!1;for(var a=0;a<n.length;a++)if(!o.call(t,n[a])||!r(e[n[a]],t[n[a]]))return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=n},function(e,t){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,u){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var i=0;i<a.length;++i)if(!(r[a[i]]||n[a[i]]||u&&u[a[i]]))try{e[a[i]]=t[a[i]]}catch(f){}}return e}},function(e,t,r){"use strict";var n=function(e,t,r,n,o,u,a,i){if(!e){var f;if(void 0===t)f=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[r,n,o,u,a,i],c=0;f=new Error(t.replace(/%s/g,function(){return l[c++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}};e.exports=n},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(147),u=r(148),a=r(149),i=r(150),f=r(151);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(157),u=r(158),a=r(159),i=r(160),f=r(161);n.prototype.clear=o,n.prototype["delete"]=u,n.prototype.get=a,n.prototype.has=i,n.prototype.set=f,e.exports=n},function(e,t,r){var n=r(62),o=r(38),u=n(o,"Map");e.exports=u},function(e,t,r){function n(e){var t=-1,r=e?e.length:0;for(this.__data__=new o;++t<r;)this.add(e[t])}var o=r(55),u=r(169),a=r(170);n.prototype.add=n.prototype.push=u,n.prototype.has=a,e.exports=n},function(e,t){function r(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}e.exports=r},function(e,t,r){function n(e,t){var r=e?e.length:0;return!!r&&o(e,t,0)>-1}var o=r(126);e.exports=n},function(e,t){function r(e,t,r){for(var n=-1,o=e?e.length:0;++n<o;)if(r(t,e[n]))return!0;return!1}e.exports=r},function(e,t){function r(e,t){for(var r=-1,n=e?e.length:0;++r<n;)if(t(e[r],r,e))return!0;return!1}e.exports=r},function(e,t){function r(e,t,r){return e===e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e}e.exports=r},function(e,t,r){function n(e,t,r,n){var s=-1,d=u,p=!0,v=e.length,h=[],y=t.length;if(!v)return h;r&&(t=i(t,f(r))),n?(d=a,p=!1):t.length>=c&&(d=l,p=!1,t=new o(t));e:for(;++s<v;){var b=e[s],m=r?r(b):b;if(b=n||0!==b?b:0,p&&m===m){for(var g=y;g--;)if(t[g]===m)continue e;h.push(b)}else d(t,m,n)||h.push(b)}return h}var o=r(113),u=r(115),a=r(116),i=r(13),f=r(135),l=r(136),c=200;e.exports=n},function(e,t,r){function n(e,t){var r=!0;return o(e,function(e,n,o){return r=!!t(e,n,o)}),r}var o=r(36);e.exports=n},function(e,t){function r(e,t,r,n){for(var o=e.length,u=r+(n?1:-1);n?u--:++u<o;)if(t(e[u],u,e))return u;return-1}e.exports=r},function(e,t,r){var n=r(141),o=n();e.exports=o},function(e,t,r){function n(e,t){return e&&o(e,t,u)}var o=r(122),u=r(177);e.exports=n},function(e,t,r){function n(e,t){t=u(t,e)?[t]:o(t);for(var r=0,n=t.length;null!=e&&r<n;)e=e[a(t[r++])];return r&&r==n?e:void 0}var o=r(137),u=r(154),a=r(23);e.exports=n},function(e,t,r){function n(e,t,r){var n=t(e);return u(e)?n:o(n,r(e))}var o=r(35),u=r(6);e.exports=n},function(e,t,r){function n(e,t,r){if(t!==t)return o(e,u,r);for(var n=r-1,a=e.length;++n<a;)if(e[n]===t)return n;return-1}var o=r(121),u=r(127);e.exports=n},function(e,t){function r(e){return e!==e}e.exports=r},function(e,t,r){function n(e){if(!i(e)||a(e))return!1;var t=o(e)||u(e)?v:c;return t.test(f(e))}var o=r(40),u=r(64),a=r(156),i=r(24),f=r(171),l=/[\\^$.*+?()[\]{}|]/g,c=/^\[object .+?Constructor\]$/,s=Object.prototype,d=Function.prototype.toString,p=s.hasOwnProperty,v=RegExp("^"+d.call(p).replace(l,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=n},function(e,t,r){function n(e){if(!o(e))return u(e);var t=[];for(var r in Object(e))i.call(e,r)&&"constructor"!=r&&t.push(r);return t}var o=r(65),u=r(167),a=Object.prototype,i=a.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){if(!o(e))return a(e);var t=u(e),r=[];for(var n in e)("constructor"!=n||!t&&f.call(e,n))&&r.push(n);return r}var o=r(24),u=r(65),a=r(168),i=Object.prototype,f=i.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t){var r=-1,n=u(e)?Array(e.length):[];return o(e,function(e,o,u){n[++r]=t(e,o,u)}),n}var o=r(36),u=r(15);e.exports=n},function(e,t){function r(e,t,r){for(var n=-1,o=t.length,u={};++n<o;){var a=t[n],i=e[a];r(i,a)&&(u[a]=i)}return u}e.exports=r},function(e,t,r){function n(e,t){var r;return o(e,function(e,n,o){return r=t(e,n,o),!r}),!!r}var o=r(36);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}e.exports=r},function(e,t){function r(e){return function(t){return e(t)}}e.exports=r},function(e,t){function r(e,t){return e.has(t)}e.exports=r},function(e,t,r){function n(e){return o(e)?e:u(e)}var o=r(6),u=r(66);e.exports=n},function(e,t){function r(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}e.exports=r},function(e,t,r){var n=r(38),o=n["__core-js_shared__"];e.exports=o},function(e,t,r){function n(e,t){return function(r,n){if(null==r)return r;if(!o(r))return e(r,n);for(var u=r.length,a=t?u:-1,i=Object(r);(t?a--:++a<u)&&n(i[a],a,i)!==!1;);return r}}var o=r(15);e.exports=n},function(e,t){function r(e){return function(t,r,n){for(var o=-1,u=Object(t),a=n(t),i=a.length;i--;){var f=a[e?i:++o];if(r(u[f],f,u)===!1)break}return t}}e.exports=r},function(e,t){(function(t){var r="object"==typeof t&&t&&t.Object===Object&&t;e.exports=r}).call(t,function(){return this}())},function(e,t,r){function n(e){return o(e,a,u)}var o=r(125),u=r(145),a=r(178);e.exports=n},function(e,t,r){var n=r(37),o=r(69),u=Object.getOwnPropertySymbols,a=u?n(u,Object):o;e.exports=a},function(e,t,r){var n=r(35),o=r(63),u=r(144),a=r(69),i=Object.getOwnPropertySymbols,f=i?function(e){for(var t=[];e;)n(t,u(e)),e=o(e);return t}:a;e.exports=f},function(e,t){function r(e,t){return null==e?void 0:e[t]}e.exports=r},function(e,t,r){function n(){this.__data__=o?o(null):{}}var o=r(22);e.exports=n},function(e,t){function r(e){return this.has(e)&&delete this.__data__[e]}e.exports=r},function(e,t,r){function n(e){var t=this.__data__;if(o){var r=t[e];return r===u?void 0:r}return i.call(t,e)?t[e]:void 0}var o=r(22),u="__lodash_hash_undefined__",a=Object.prototype,i=a.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){var t=this.__data__;return o?void 0!==t[e]:a.call(t,e)}var o=r(22),u=Object.prototype,a=u.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__;return r[e]=o&&void 0===t?u:t,this}var o=r(22),u="__lodash_hash_undefined__";e.exports=n},function(e,t,r){function n(e){return a(e)||u(e)||!!(i&&e&&e[i])}var o=r(56),u=r(68),a=r(6),i=o?o.isConcatSpreadable:void 0;e.exports=n},function(e,t){function r(e,t){return t=null==t?n:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var n=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=r},function(e,t,r){function n(e,t){if(o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!u(e))||i.test(e)||!a.test(e)||null!=t&&e in Object(t)}var o=r(6),u=r(16),a=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;e.exports=n},function(e,t){function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=r},function(e,t,r){function n(e){return!!u&&u in e}var o=r(139),u=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=n},function(e,t){function r(){this.__data__=[]}e.exports=r},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():a.call(t,r,1),!0}var o=r(20),u=Array.prototype,a=u.splice;e.exports=n},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);return r<0?void 0:t[r][1]}var o=r(20);e.exports=n},function(e,t,r){function n(e){return o(this.__data__,e)>-1}var o=r(20);e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__,n=o(r,e);return n<0?r.push([e,t]):r[n][1]=t,this}var o=r(20);e.exports=n},function(e,t,r){function n(){this.__data__={hash:new o,map:new(a||u),string:new o}}var o=r(110),u=r(111),a=r(112);e.exports=n},function(e,t,r){function n(e){return o(this,e)["delete"](e)}var o=r(21);e.exports=n},function(e,t,r){function n(e){return o(this,e).get(e)}var o=r(21);e.exports=n},function(e,t,r){function n(e){return o(this,e).has(e)}var o=r(21);e.exports=n},function(e,t,r){function n(e,t){return o(this,e).set(e,t),this}var o=r(21);e.exports=n},function(e,t,r){var n=r(37),o=n(Object.keys,Object);e.exports=o},function(e,t){function r(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}e.exports=r},function(e,t){function r(e){return this.__data__.set(e,n),this}var n="__lodash_hash_undefined__";e.exports=r},function(e,t){function r(e){return this.__data__.has(e)}e.exports=r},function(e,t){function r(e){if(null!=e){try{return n.call(e)}catch(t){}try{return e+""}catch(t){}}return""}var n=Function.prototype.toString;e.exports=r},function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},function(e,t,r){function n(e,t,r){var n=null==e?void 0:o(e,t);return void 0===n?r:n}var o=r(124);e.exports=n},function(e,t,r){function n(e){return u(e)&&o(e)}var o=r(15),u=r(25);e.exports=n},function(e,t){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}var n=9007199254740991;e.exports=r},function(e,t,r){function n(e){return"string"==typeof e||!o(e)&&u(e)&&f.call(e)==a}var o=r(6),u=r(25),a="[object String]",i=Object.prototype,f=i.toString;e.exports=n},function(e,t,r){function n(e){return a(e)?o(e):u(e)}var o=r(57),u=r(129),a=r(15);e.exports=n},function(e,t,r){function n(e){return a(e)?o(e,!0):u(e)}var o=r(57),u=r(130),a=r(15);e.exports=n},function(e,t,r){function n(e,t){if("function"!=typeof e||t&&"function"!=typeof t)throw new TypeError(u);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],u=r.cache;if(u.has(o))return u.get(o);var a=e.apply(this,n);return r.cache=u.set(o,a),a};return r.cache=new(n.Cache||o),r}var o=r(55),u="Expected a function";n.Cache=o,e.exports=n},function(e,t,r){var n=r(13),o=r(58),u=r(59),a=r(60),i=r(23),f=a(function(e,t){return null==e?{}:u(e,n(o(t,1),i))});e.exports=f},function(e,t,r){function n(e){if(!e)return 0===e?e:0;if(e=o(e),e===u||e===-u){var t=e<0?-1:1;return t*a}return e===e?e:0}var o=r(183),u=1/0,a=1.7976931348623157e308;e.exports=n},function(e,t,r){function n(e){var t=o(e),r=t%1;return t===t?r?t-r:t:0}var o=r(181);e.exports=n},function(e,t,r){function n(e){if("number"==typeof e)return e;if(a(e))return i;if(u(e)){var t=o(e.valueOf)?e.valueOf():e;e=u(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(f,"");var r=c.test(e);return r||s.test(e)?d(e.slice(2),r?2:8):l.test(e)?i:+e}var o=r(40),u=r(24),a=r(16),i=NaN,f=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,c=/^0b[01]+$/i,s=/^0o[0-7]+$/i,d=parseInt;e.exports=n},function(e,t){"use strict";function r(e,t){if(e===t)return!0;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(var o=Object.prototype.hasOwnProperty,u=0;u<r.length;u++)if(!o.call(t,r[u])||e[r[u]]!==t[r[u]])return!1;return!0}t.__esModule=!0,t["default"]=r},function(e,t,r){"use strict";t.__esModule=!0;var n=r(8);t["default"]=n.PropTypes.shape({subscribe:n.PropTypes.func.isRequired,dispatch:n.PropTypes.func.isRequired,getState:n.PropTypes.func.isRequired})},function(e,t){"use strict";function r(e){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(e);try{throw new Error(e)}catch(t){}}t.__esModule=!0,t["default"]=r},function(e,t,r){"use strict";function n(e){return function(t){return(0,o.bindActionCreators)(e,t)}}t.__esModule=!0,t["default"]=n;var o=r(41)},function(e,t){e.exports=r}])});
app/javascript/mastodon/components/permalink.js
Arukas/mastodon
import React from 'react'; import PropTypes from 'prop-types'; export default class Permalink extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { className: PropTypes.string, href: PropTypes.string.isRequired, to: PropTypes.string.isRequired, children: PropTypes.node, }; handleClick = (e) => { if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) { e.preventDefault(); this.context.router.history.push(this.props.to); } } render () { const { href, children, className, ...other } = this.props; return ( <a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}> {children} </a> ); } }
assets/jqwidgets/demos/react/app/listbox/checkboxes/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxListBox from '../../../jqwidgets-react/react_jqxlistbox.js'; class App extends React.Component { componentDidMount() { this.refs.myListBox.checkIndex(0); this.refs.myListBox.checkIndex(1); this.refs.myListBox.checkIndex(2); this.refs.myListBox.checkIndex(5); this.refs.myListBox.on('checkChange', (event) => { let eventsContainer = document.getElementById('Events'); let checkedItemsContainer = document.getElementById('CheckedItems'); if (event.args.checked) { eventsContainer.innerHTML = 'Checked: ' + event.args.label; } else { eventsContainer.innerHTML = 'Unchecked: ' + event.args.label; } let items = this.refs.myListBox.getCheckedItems(); let checkedItems = ''; for (let i = 0; i < items.length; i++) { if (i < items.length - 1) { checkedItems += items[i].label + ', '; } else checkedItems += items[i].label; } checkedItemsContainer.innerHTML = checkedItems; }); } render() { let source = [ 'Affogato', 'Americano', 'Bicerin', 'Breve', 'Cafe Bombon', 'Cafe au lait', 'Caffe Corretto', 'Cafe Crema', 'Caffe Latte', 'Caffe macchiato', 'Cafe melange', 'Coffee milk', 'Cafe mocha', 'Cappuccino', 'Carajillo', 'Cortado', 'Cuban espresso', 'Espresso', 'Eiskaffee', 'The Flat White', 'Frappuccino', 'Galao', 'Greek frappe coffee', 'Iced Coffee', 'Indian filter coffee', 'Instant coffee', 'Irish coffee', 'Liqueur coffee' ]; return ( <div> <JqxListBox ref='myListBox' width={200} height={250} source={source} checkboxes={true} /> <div style={{ marginTop: 20, fontSize: 13, fontFamily: 'Verdana' }} id='Events' /> <div style={{ marginTop: 10, fontSize: 13, fontFamily: 'Verdana' }} id='CheckedItems' /> </div> ) } } ReactDOM.render(<App />, document.getElementById('app'));
index.js
afghl/dribble-demo
import 'babel-polyfill' import './sass/main.scss' import React from 'react' import { render } from 'react-dom' import { Provider } from 'react-redux' import App from './containers/App' import configureStore from './store/configureStore' const store = configureStore() render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
packager/blacklist.js
Andreyco/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'; var path = require('path'); // Don't forget to everything listed here to `package.json` // modulePathIgnorePatterns. var sharedBlacklist = [ /node_modules[/\\]react[/\\]dist[/\\].*/, /website\/node_modules\/.*/, // TODO(jkassens, #9876132): Remove this rule when it's no longer needed. 'Libraries/Relay/relay/tools/relayUnstableBatchedUpdates.js', /heapCapture\/bundle\.js/, ]; function escapeRegExp(pattern) { if (Object.prototype.toString.call(pattern) === '[object RegExp]') { return pattern.source.replace(/\//g, path.sep); } else if (typeof pattern === 'string') { var escaped = pattern.replace(/[\-\[\]\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); // convert the '/' into an escaped local file separator return escaped.replace(/\//g,'\\' + path.sep); } else { throw new Error('Unexpected packager blacklist pattern: ' + pattern); } } function blacklist(additionalBlacklist) { return new RegExp('(' + (additionalBlacklist || []).concat(sharedBlacklist) .map(escapeRegExp) .join('|') + ')$' ); } module.exports = blacklist;
ajax/libs/jQRangeSlider/5.6.0/jQRangeSliderBar.min.js
stefanneculai/cdnjs
(function(b,c){b.widget("ui.rangeSliderBar",b.ui.rangeSliderDraggable,{options:{leftHandle:null,rightHandle:null,bounds:{min:0,max:100},type:"rangeSliderHandle",range:false,drag:function(){},stop:function(){},values:{min:0,max:20},wheelSpeed:4,wheelMode:null},_values:{min:0,max:20},_waitingToInit:2,_wheelTimeout:false,_create:function(){b.ui.rangeSliderDraggable.prototype._create.apply(this);this.element.css("position","absolute").css("top",0).addClass("ui-rangeSlider-bar");this.options.leftHandle.bind("initialize",b.proxy(this._onInitialized,this)).bind("mousestart",b.proxy(this._cache,this)).bind("stop",b.proxy(this._onHandleStop,this));this.options.rightHandle.bind("initialize",b.proxy(this._onInitialized,this)).bind("mousestart",b.proxy(this._cache,this)).bind("stop",b.proxy(this._onHandleStop,this));this._bindHandles();this._values=this.options.values;this._setWheelModeOption(this.options.wheelMode)},destroy:function(){this.options.leftHandle.unbind(".bar");this.options.rightHandle.unbind(".bar");this.options=null;b.ui.rangeSliderDraggable.prototype.destroy.apply(this)},_setOption:function(d,e){if(d==="range"){this._setRangeOption(e)}else{if(d==="wheelSpeed"){this._setWheelSpeedOption(e)}else{if(d==="wheelMode"){this._setWheelModeOption(e)}}}},_setRangeOption:function(f){if(typeof f!=="object"||f===null){f=false}if(f===false&&this.options.range===false){return}if(f!==false){var e=a(f.min,this.options.range.min),d=a(f.max,this.options.range.max);this.options.range={min:e,max:d}}else{this.options.range=false}this._setLeftRange();this._setRightRange()},_setWheelSpeedOption:function(d){if(typeof d==="number"&&d>0){this.options.wheelSpeed=d}},_setWheelModeOption:function(d){if(d===null||d===false||d==="zoom"||d==="scroll"){if(this.options.wheelMode!==d){this.element.parent().unbind("mousewheel.bar")}this._bindMouseWheel(d);this.options.wheelMode=d}},_bindMouseWheel:function(d){if(d==="zoom"){this.element.parent().bind("mousewheel.bar",b.proxy(this._mouseWheelZoom,this))}else{if(d==="scroll"){this.element.parent().bind("mousewheel.bar",b.proxy(this._mouseWheelScroll,this))}}},_setLeftRange:function(){if(this.options.range===false){return false}var d=this._values.max,e={min:false,max:false};if((this.options.range.min||false)!==false){e.max=this._leftHandle("substract",d,this.options.range.min)}else{e.max=false}if((this.options.range.max||false)!==false){e.min=this._leftHandle("substract",d,this.options.range.max)}else{e.min=false}this._leftHandle("option","range",e)},_setRightRange:function(){var e=this._values.min,d={min:false,max:false};if((this.options.range.min||false)!==false){d.min=this._rightHandle("add",e,this.options.range.min)}else{d.min=false}if((this.options.range.max||false)!==false){d.max=this._rightHandle("add",e,this.options.range.max)}else{d.max=false}this._rightHandle("option","range",d)},_deactivateRange:function(){this._leftHandle("option","range",false);this._rightHandle("option","range",false)},_reactivateRange:function(){this._setRangeOption(this.options.range)},_onInitialized:function(){this._waitingToInit--;if(this._waitingToInit===0){this._initMe()}},_initMe:function(){this._cache();this.min(this._values.min);this.max(this._values.max);var e=this._leftHandle("position"),d=this._rightHandle("position")+this.options.rightHandle.width();this.element.offset({left:e});this.element.css("width",d-e)},_leftHandle:function(){return this._handleProxy(this.options.leftHandle,arguments)},_rightHandle:function(){return this._handleProxy(this.options.rightHandle,arguments)},_handleProxy:function(e,d){var f=Array.prototype.slice.call(d);return e[this.options.type].apply(e,f)},_cache:function(){b.ui.rangeSliderDraggable.prototype._cache.apply(this);this._cacheHandles()},_cacheHandles:function(){this.cache.rightHandle={};this.cache.rightHandle.width=this.options.rightHandle.width();this.cache.rightHandle.offset=this.options.rightHandle.offset();this.cache.leftHandle={};this.cache.leftHandle.offset=this.options.leftHandle.offset()},_mouseStart:function(d){b.ui.rangeSliderDraggable.prototype._mouseStart.apply(this,[d]);this._deactivateRange()},_mouseStop:function(d){b.ui.rangeSliderDraggable.prototype._mouseStop.apply(this,[d]);this._cacheHandles();this._values.min=this._leftHandle("value");this._values.max=this._rightHandle("value");this._reactivateRange();this._leftHandle().trigger("stop");this._rightHandle().trigger("stop")},_onDragLeftHandle:function(d,e){this._cacheIfNecessary();if(e.element[0]!==this.options.leftHandle[0]){return}if(this._switchedValues()){this._switchHandles();this._onDragRightHandle(d,e);return}this._values.min=e.value;this.cache.offset.left=e.offset.left;this.cache.leftHandle.offset=e.offset;this._positionBar()},_onDragRightHandle:function(d,e){this._cacheIfNecessary();if(e.element[0]!==this.options.rightHandle[0]){return}if(this._switchedValues()){this._switchHandles();this._onDragLeftHandle(d,e);return}this._values.max=e.value;this.cache.rightHandle.offset=e.offset;this._positionBar()},_positionBar:function(){var d=this.cache.rightHandle.offset.left+this.cache.rightHandle.width-this.cache.leftHandle.offset.left;this.cache.width.inner=d;this.element.css("width",d).offset({left:this.cache.leftHandle.offset.left})},_onHandleStop:function(){this._setLeftRange();this._setRightRange()},_switchedValues:function(){if(this.min()>this.max()){var d=this._values.min;this._values.min=this._values.max;this._values.max=d;return true}return false},_switchHandles:function(){var d=this.options.leftHandle;this.options.leftHandle=this.options.rightHandle;this.options.rightHandle=d;this._leftHandle("option","isLeft",true);this._rightHandle("option","isLeft",false);this._bindHandles();this._cacheHandles()},_bindHandles:function(){this.options.leftHandle.unbind(".bar").bind("sliderDrag.bar update.bar moving.bar",b.proxy(this._onDragLeftHandle,this));this.options.rightHandle.unbind(".bar").bind("sliderDrag.bar update.bar moving.bar",b.proxy(this._onDragRightHandle,this))},_constraintPosition:function(f){var d={},e;d.left=b.ui.rangeSliderDraggable.prototype._constraintPosition.apply(this,[f]);d.left=this._leftHandle("position",d.left);e=this._rightHandle("position",d.left+this.cache.width.outer-this.cache.rightHandle.width);d.width=e-d.left+this.cache.rightHandle.width;return d},_applyPosition:function(d){b.ui.rangeSliderDraggable.prototype._applyPosition.apply(this,[d.left]);this.element.width(d.width)},_mouseWheelZoom:function(i,j,e,d){if(!this.enabled){return false}var f=this._values.min+(this._values.max-this._values.min)/2,g={},h={};if(this.options.range===false||this.options.range.min===false){g.max=f;h.min=f}else{g.max=f-this.options.range.min/2;h.min=f+this.options.range.min/2}if(this.options.range!==false&&this.options.range.max!==false){g.min=f-this.options.range.max/2;h.max=f+this.options.range.max/2}this._leftHandle("option","range",g);this._rightHandle("option","range",h);clearTimeout(this._wheelTimeout);this._wheelTimeout=setTimeout(b.proxy(this._wheelStop,this),200);this.zoomIn(d*this.options.wheelSpeed);return false},_mouseWheelScroll:function(f,g,e,d){if(!this.enabled){return false}if(this._wheelTimeout===false){this.startScroll()}else{clearTimeout(this._wheelTimeout)}this._wheelTimeout=setTimeout(b.proxy(this._wheelStop,this),200);this.scrollLeft(d*this.options.wheelSpeed);return false},_wheelStop:function(){this.stopScroll();this._wheelTimeout=false},min:function(d){return this._leftHandle("value",d)},max:function(d){return this._rightHandle("value",d)},startScroll:function(){this._deactivateRange()},stopScroll:function(){this._reactivateRange();this._triggerMouseEvent("stop");this._leftHandle().trigger("stop");this._rightHandle().trigger("stop")},scrollLeft:function(d){d=d||1;if(d<0){return this.scrollRight(-d)}d=this._leftHandle("moveLeft",d);this._rightHandle("moveLeft",d);this.update();this._triggerMouseEvent("scroll")},scrollRight:function(d){d=d||1;if(d<0){return this.scrollLeft(-d)}d=this._rightHandle("moveRight",d);this._leftHandle("moveRight",d);this.update();this._triggerMouseEvent("scroll")},zoomIn:function(e){e=e||1;if(e<0){return this.zoomOut(-e)}var d=this._rightHandle("moveLeft",e);if(e>d){d=d/2;this._rightHandle("moveRight",d)}this._leftHandle("moveRight",d);this.update();this._triggerMouseEvent("zoom")},zoomOut:function(e){e=e||1;if(e<0){return this.zoomIn(-e)}var d=this._rightHandle("moveRight",e);if(e>d){d=d/2;this._rightHandle("moveLeft",d)}this._leftHandle("moveLeft",d);this.update();this._triggerMouseEvent("zoom")},values:function(e,d){if(typeof e!=="undefined"&&typeof d!=="undefined"){var f=Math.min(e,d),g=Math.max(e,d);this._deactivateRange();this.options.leftHandle.unbind(".bar");this.options.rightHandle.unbind(".bar");this._values.min=this._leftHandle("value",f);this._values.max=this._rightHandle("value",g);this._bindHandles();this._reactivateRange();this.update()}return{min:this._values.min,max:this._values.max}},update:function(){this._values.min=this.min();this._values.max=this.max();this._cache();this._positionBar()}});function a(e,d){if(typeof e==="undefined"){return d||false}return e}}(jQuery));
src/app/navbar.js
m-vdb/m-vdb.github.io
import React, { Component } from 'react'; import { profileLinks } from './constants'; import mailIcon from '../img/mail.svg'; import githubIcon from '../img/github.svg'; import linkedinIcon from '../img/linkedin.svg'; class NavBar extends Component { render() { return ( <nav className="navbar navbar-links"> <ul> <li> <a href={profileLinks.github}> <img src={githubIcon} alt="Github" className="link-icon" /> </a> </li> <li> <a href={profileLinks.email}> <img src={mailIcon} alt="Contact me" className="link-icon link-icon-email" /> </a> </li> <li> <a href={profileLinks.linkedin}> <img src={linkedinIcon} alt="LinkedIn" className="link-icon" /> </a> </li> </ul> </nav> ); } } export default NavBar;
src/animations/flip/app.js
SodhanaLibrary/react-examples
import React from 'react'; import './app.css'; import classNames from 'classNames'; export default class App extends React.Component { constructor(props) { super(props); this.animate = this.animate.bind(this); this.state = { animate:false } } animate() { this.setState({ animate:!this.state.animate }) } render() { return ( <div> <button onClick={this.animate}>Animate</button> <div style={{ height:this.state.animate ? '0px':'71px' }} className={classNames({"parent--fold":this.state.animate}, "parent")}> <div className="child"> <div>Hi this is sample text</div> <br/> <br/> <div>Hi this is sample text</div> </div> </div> </div> ) } }
src/App.js
heikela/react-redux-immutable-trial
import React, { Component } from 'react'; import GraphComponent from './graph/Graph'; import { SeriesComponent, NaiveSeriesComponent } from './series/SeriesComponent'; import { Provider, connect } from 'react-redux'; import ControlButton from './ControlButton'; import { store } from './store'; import { setupDataStream } from './dataSource/dataSource'; import { addItems } from './series/seriesActions'; import { zoomConnector } from './zooming/ZoomConnector'; const Graph = zoomConnector(GraphComponent); const SeriesContainer = connect( state => ({items: state.getIn(['series', 'chartItems'])}) )(/naive/.test(window.location.href) ? NaiveSeriesComponent : SeriesComponent); const autoScrollAfter = /scroll/.test(window.location.href) ? 100 : 0 class App extends Component { render() { const addItemsAction = addItems(1000); return ( <Provider store={store}> <div className="App"> <Graph width={600} height={600} x1={0} y1={0} x2={200} y2={200} series={(state => state.get('series'))} zooming={(state => state.get('zooming'))} > <SeriesContainer/> </Graph> <p> <ControlButton action={addItemsAction} > Add a thousand points </ControlButton> </p> </div> </Provider> ); } } setupDataStream(store.dispatch, autoScrollAfter); export default App;
interface/modules/zend_modules/public/js/lib/jquery-1.8.0.min.js
ravian766/openemr
/*! jQuery v@1.8.0 jquery.com | jquery.org/license */ (function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bX(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bV.length;while(e--){b=bV[e]+c;if(b in a)return b}return d}function bY(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function bZ(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bY(c)&&(e[f]=p._data(c,"olddisplay",cb(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b$(a,b,c){var d=bO.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function b_(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bU[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bU[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bU[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bU[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bU[e]+"Width"))||0));return f}function ca(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bP.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+b_(a,b,c||(f?"border":"content"),e)+"px"}function cb(a){if(bR[a])return bR[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bR[a]=c,c}function ch(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||cd.test(a)?d(a,e):ch(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ch(a+"["+e+"]",b[e],c,d);else d(a,b)}function cy(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h<i;h++)d=g[h],f=/^\+/.test(d),f&&(d=d.substr(1)||"*"),e=a[d]=a[d]||[],e[f?"unshift":"push"](c)}}function cz(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h,i=a[f],j=0,k=i?i.length:0,l=a===cu;for(;j<k&&(l||!h);j++)h=i[j](c,d,e),typeof h=="string"&&(!l||g[h]?h=b:(c.dataTypes.unshift(h),h=cz(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cz(a,c,d,e,"*",g)),h}function cA(a,c){var d,e,f=p.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((f[d]?a:e||(e={}))[d]=c[d]);e&&p.extend(!0,a,e)}function cB(a,c,d){var e,f,g,h,i=a.contents,j=a.dataTypes,k=a.responseFields;for(f in k)f in d&&(c[k[f]]=d[f]);while(j[0]==="*")j.shift(),e===b&&(e=a.mimeType||c.getResponseHeader("content-type"));if(e)for(f in i)if(i[f]&&i[f].test(e)){j.unshift(f);break}if(j[0]in d)g=j[0];else{for(f in d){if(!j[0]||a.converters[f+" "+j[0]]){g=f;break}h||(h=f)}g=g||h}if(g)return g!==j[0]&&j.unshift(g),d[g]}function cC(a,b){var c,d,e,f,g=a.dataTypes.slice(),h=g[0],i={},j=0;a.dataFilter&&(b=a.dataFilter(b,a.dataType));if(g[1])for(c in a.converters)i[c.toLowerCase()]=a.converters[c];for(;e=g[++j];)if(e!=="*"){if(h!=="*"&&h!==e){c=i[h+" "+e]||i["* "+e];if(!c)for(d in i){f=d.split(" ");if(f[1]===e){c=i[h+" "+f[0]]||i["* "+f[0]];if(c){c===!0?c=i[d]:i[d]!==!0&&(e=f[0],g.splice(j--,0,e));break}}}if(c!==!0)if(c&&a["throws"])b=c(b);else try{b=c(b)}catch(k){return{state:"parsererror",error:c?k:"No conversion from "+h+" to "+e}}}h=e}return{state:"success",data:b}}function cK(){try{return new a.XMLHttpRequest}catch(b){}}function cL(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cT(){return setTimeout(function(){cM=b},0),cM=p.now()}function cU(a,b){p.each(b,function(b,c){var d=(cS[b]||[]).concat(cS["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cV(a,b,c){var d,e=0,f=0,g=cR.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cM||cT(),c=Math.max(0,j.startTime+j.duration-b),d=1-(c/j.duration||0),e=0,f=j.tweens.length;for(;e<f;e++)j.tweens[e].run(d);return h.notifyWith(a,[j,d,c]),d<1&&f?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:p.extend({},b),opts:p.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:cM||cT(),duration:c.duration,tweens:[],createTween:function(b,c,d){var e=p.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(e),e},stop:function(b){var c=0,d=b?j.tweens.length:0;for(;c<d;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;cW(k,j.opts.specialEasing);for(;e<g;e++){d=cR[e].call(j,a,k,j.opts);if(d)return d}return cU(j,k),p.isFunction(j.opts.start)&&j.opts.start.call(a,j),p.fx.timer(p.extend(i,{anim:j,queue:j.opts.queue,elem:a})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}function cW(a,b){var c,d,e,f,g;for(c in a){d=p.camelCase(c),e=b[d],f=a[c],p.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=p.cssHooks[d];if(g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}}function cX(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bY(a);c.queue||(j=p._queueHooks(a,"fx"),j.unqueued==null&&(j.unqueued=0,k=j.empty.fire,j.empty.fire=function(){j.unqueued||k()}),j.unqueued++,l.always(function(){l.always(function(){j.unqueued--,p.queue(a,"fx").length||j.empty.fire()})})),a.nodeType===1&&("height"in b||"width"in b)&&(c.overflow=[m.overflow,m.overflowX,m.overflowY],p.css(a,"display")==="inline"&&p.css(a,"float")==="none"&&(!p.support.inlineBlockNeedsLayout||cb(a.nodeName)==="inline"?m.display="inline-block":m.zoom=1)),c.overflow&&(m.overflow="hidden",p.support.shrinkWrapBlocks||l.done(function(){m.overflow=c.overflow[0],m.overflowX=c.overflow[1],m.overflowY=c.overflow[2]}));for(d in b){f=b[d];if(cO.exec(f)){delete b[d];if(f===(q?"hide":"show"))continue;o.push(d)}}g=o.length;if(g){h=p._data(a,"fxshow")||p._data(a,"fxshow",{}),q?p(a).show():l.done(function(){p(a).hide()}),l.done(function(){var b;p.removeData(a,"fxshow",!0);for(b in n)p.style(a,b,n[b])});for(d=0;d<g;d++)e=o[d],i=l.createTween(e,q?h[e]:0),n[e]=h[e]||p.style(a,e),e in h||(h[e]=i.start,q&&(i.end=i.start,i.start=e==="width"||e==="height"?1:0))}}function cY(a,b,c,d,e){return new cY.prototype.init(a,b,c,d,e)}function cZ(a,b){var c,d={height:a},e=0;for(;e<4;e+=2-b)c=bU[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function c_(a){return p.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}var c,d,e=a.document,f=a.location,g=a.navigator,h=a.jQuery,i=a.$,j=Array.prototype.push,k=Array.prototype.slice,l=Array.prototype.indexOf,m=Object.prototype.toString,n=Object.prototype.hasOwnProperty,o=String.prototype.trim,p=function(a,b){return new p.fn.init(a,b,c)},q=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,r=/\S/,s=/\s+/,t=r.test(" ")?/^[\s\xA0]+|[\s\xA0]+$/g:/^\s+|\s+$/g,u=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.0",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,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(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i<j;i++)if((a=arguments[i])!=null)for(c in a){d=h[c],e=a[c];if(h===e)continue;k&&e&&(p.isPlainObject(e)||(f=p.isArray(e)))?(f?(f=!1,g=d&&p.isArray(d)?d:[]):g=d&&p.isPlainObject(d)?d:{},h[c]=p.extend(k,g,e)):e!==b&&(h[c]=e)}return h},p.extend({noConflict:function(b){return a.$===p&&(a.$=i),b&&a.jQuery===p&&(a.jQuery=h),p},isReady:!1,readyWait:1,holdReady:function(a){a?p.readyWait++:p.ready(!0)},ready:function(a){if(a===!0?--p.readyWait:p.isReady)return;if(!e.body)return setTimeout(p.ready,1);p.isReady=!0;if(a!==!0&&--p.readyWait>0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f<g;)if(c.apply(a[f++],d)===!1)break}else if(h){for(e in a)if(c.call(a[e],e,a[e])===!1)break}else for(;f<g;)if(c.call(a[f],f,a[f++])===!1)break;return a},trim:o?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":a.toString().replace(t,"")},makeArray:function(a,b){var c,d=b||[];return a!=null&&(c=p.type(a),a.length==null||c==="string"||c==="function"||c==="regexp"||p.isWindow(a)?j.call(d,a):p.merge(d,a)),d},inArray:function(a,b,c){var d;if(b){if(l)return l.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=c.length,e=a.length,f=0;if(typeof d=="number")for(;f<d;f++)a[e++]=c[f];else while(c[f]!==b)a[e++]=c[f++];return a.length=e,a},grep:function(a,b,c){var d,e=[],f=0,g=a.length;c=!!c;for(;f<g;f++)d=!!b(a[f],f),c!==d&&e.push(a[f]);return e},map:function(a,c,d){var e,f,g=[],h=0,i=a.length,j=a instanceof p||i!==b&&typeof i=="number"&&(i>0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h<i;h++)e=c(a[h],h,d),e!=null&&(g[g.length]=e);else for(f in a)e=c(a[f],f,d),e!=null&&(g[g.length]=e);return g.concat.apply([],g)},guid:1,proxy:function(a,c){var d,e,f;return typeof c=="string"&&(d=a[c],c=a,a=d),p.isFunction(a)?(e=k.call(arguments,2),f=function(){return a.apply(c,e.concat(k.call(arguments)))},f.guid=a.guid=a.guid||f.guid||p.guid++,f):b},access:function(a,c,d,e,f,g,h){var i,j=d==null,k=0,l=a.length;if(d&&typeof d=="object"){for(k in d)p.access(a,c,k,d[k],1,g,e);f=1}else if(e!==b){i=h===b&&p.isFunction(e),j&&(i?(i=c,c=function(a,b,c){return i.call(p(a),c)}):(c.call(a,e),c=null));if(c)for(;k<l;k++)c(a[k],d,i?e.call(a[k],k,c(a[k],d)):e,h);f=1}return f?a:j?c.call(a):l?c(a[0],d):g},now:function(){return(new Date).getTime()}}),p.ready.promise=function(b){if(!d){d=p.Deferred();if(e.readyState==="complete"||e.readyState!=="loading"&&e.addEventListener)setTimeout(p.ready,1);else if(e.addEventListener)e.addEventListener("DOMContentLoaded",D,!1),a.addEventListener("load",p.ready,!1);else{e.attachEvent("onreadystatechange",D),a.attachEvent("onload",p.ready);var c=!1;try{c=a.frameElement==null&&e.documentElement}catch(f){}c&&c.doScroll&&function g(){if(!p.isReady){try{c.doScroll("left")}catch(a){return setTimeout(g,50)}p.ready()}}()}}return d.promise(b)},p.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){E["[object "+b+"]"]=b.toLowerCase()}),c=p(e);var F={};p.Callbacks=function(a){a=typeof a=="string"?F[a]||G(a):p.extend({},a);var c,d,e,f,g,h,i=[],j=!a.once&&[],k=function(b){c=a.memory&&b,d=!0,h=f||0,f=0,g=i.length,e=!0;for(;i&&h<g;h++)if(i[h].apply(b[0],b[1])===!1&&a.stopOnFalse){c=!1;break}e=!1,i&&(j?j.length&&k(j.shift()):c?i=[]:l.disable())},l={add:function(){if(i){var b=i.length;(function d(b){p.each(b,function(b,c){p.isFunction(c)&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&d(c)})})(arguments),e?g=i.length:c&&(f=b,k(c))}return this},remove:function(){return i&&p.each(arguments,function(a,b){var c;while((c=p.inArray(b,i,c))>-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return typeof a=="object"?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b<d;b++)c[b]&&p.isFunction(c[b].promise)?c[b].promise().done(g(b,j,c)).fail(f.reject).progress(g(b,i,h)):--e}return e||f.resolveWith(j,c),f.promise()}}),p.support=function(){var b,c,d,f,g,h,i,j,k,l,m,n=e.createElement("div");n.setAttribute("className","t"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length||!d)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,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%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="<div></div>",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/^(?:\{.*\}|\[.*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||++p.uuid:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e<f;e++)delete d[b[e]];if(!(c?K:p.isEmptyObject)(d))return}}if(!c){delete h[i].data;if(!K(h[i]))return}g?p.cleanData([a],!0):p.support.deleteExpando||h!=h.window?delete h[i]:h[i]=null},_data:function(a,b,c){return p.data(a,b,c,!0)},acceptData:function(a){var b=a.nodeName&&p.noData[a.nodeName.toLowerCase()];return!b||b!==!0&&a.getAttribute("classid")===b}}),p.fn.extend({data:function(a,c){var d,e,f,g,h,i=this[0],j=0,k=null;if(a===b){if(this.length){k=p.data(i);if(i.nodeType===1&&!p._data(i,"parsedAttrs")){f=i.attributes;for(h=f.length;j<h;j++)g=f[j].name,g.indexOf("data-")===0&&(g=p.camelCase(g.substring(5)),J(i,g,k[g]));p._data(i,"parsedAttrs",!0)}}return k}return typeof a=="object"?this.each(function(){p.data(this,a)}):(d=a.split(".",2),d[1]=d[1]?"."+d[1]:"",e=d[1]+"!",p.access(this,function(c){if(c===b)return k=this.triggerHandler("getData"+e,[d[0]]),k===b&&i&&(k=p.data(i,a),k=J(i,a,k)),k===b&&d[1]?this.data(d[0]):k;d[1]=c,this.each(function(){var b=p(this);b.triggerHandler("setData"+e,d),p.data(this,a,c),b.triggerHandler("changeData"+e,d)})},null,c,arguments.length>1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.shift(),e=p._queueHooks(a,b),f=function(){p.dequeue(a,b)};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),delete e.stop,d.call(a,f,e)),!c.length&&e&&e.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length<d?p.queue(this[0],a):c===b?this:this.each(function(){var b=p.queue(this,a,c);p._queueHooks(this,a),a==="fx"&&b[0]!=="inprogress"&&p.dequeue(this,a)})},dequeue:function(a){return this.each(function(){p.dequeue(this,a)})},delay:function(a,b){return a=p.fx?p.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){var d,e=1,f=p.Deferred(),g=this,h=this.length,i=function(){--e||f.resolveWith(g,[g])};typeof a!="string"&&(c=a,a=b),a=a||"fx";while(h--)(d=p._data(g[h],a+"queueHooks"))&&d.empty&&(e++,d.empty.add(i));return i(),f.promise(c)}});var L,M,N,O=/[\t\r\n]/g,P=/\r/g,Q=/^(?:button|input)$/i,R=/^(?:button|input|object|select|textarea)$/i,S=/^a(?:rea|)$/i,T=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,U=p.support.getSetAttribute;p.fn.extend({attr:function(a,b){return p.access(this,p.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{f=" "+e.className+" ";for(g=0,h=b.length;g<h;g++)~f.indexOf(" "+b[g]+" ")||(f+=b[g]+" ");e.className=p.trim(f)}}}return this},removeClass:function(a){var c,d,e,f,g,h,i;if(p.isFunction(a))return this.each(function(b){p(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(s);for(h=0,i=this.length;h<i;h++){e=this[h];if(e.nodeType===1&&e.className){d=(" "+e.className+" ").replace(O," ");for(f=0,g=c.length;f<g;f++)while(d.indexOf(" "+c[f]+" ")>-1)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(O," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c<d;c++){e=h[c];if(e.selected&&(p.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!p.nodeName(e.parentNode,"optgroup"))){b=p(e).val();if(i)return b;g.push(b)}}return i&&!g.length&&h.length?p(h[f]).val():g},set:function(a,b){var c=p.makeArray(b);return p(a).find("option").each(function(){this.selected=p.inArray(p(this).val(),c)>=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,""+d),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g<d.length;g++)e=d[g],e&&(c=p.propFix[e]||e,f=T.test(e),f||p.attr(a,e,""),a.removeAttribute(U?e:c),f&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(Q.test(a.nodeName)&&a.parentNode)p.error("type property can't be changed");else if(!p.support.radioValue&&b==="radio"&&p.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}},value:{get:function(a,b){return L&&p.nodeName(a,"button")?L.get(a,b):b in a?a.value:null},set:function(a,b,c){if(L&&p.nodeName(a,"button"))return L.set(a,b,c);a.value=b}}},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(a,c,d){var e,f,g,h=a.nodeType;if(!a||h===3||h===8||h===2)return;return g=h!==1||!p.isXMLDoc(a),g&&(c=p.propFix[c]||c,f=p.propHooks[c]),d!==b?f&&"set"in f&&(e=f.set(a,d,c))!==b?e:a[c]=d:f&&"get"in f&&(e=f.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):R.test(a.nodeName)||S.test(a.nodeName)&&a.href?0:b}}}}),M={get:function(a,c){var d,e=p.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;return b===!1?p.removeAttr(a,c):(d=p.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase())),c}},U||(N={name:!0,id:!0,coords:!0},L=p.valHooks.button={get:function(a,c){var d;return d=a.getAttributeNode(c),d&&(N[c]?d.value!=="":d.specified)?d.value:b},set:function(a,b,c){var d=a.getAttributeNode(c);return d||(d=e.createAttribute(c),a.setAttributeNode(d)),d.value=b+""}},p.each(["width","height"],function(a,b){p.attrHooks[b]=p.extend(p.attrHooks[b],{set:function(a,c){if(c==="")return a.setAttribute(b,"auto"),c}})}),p.attrHooks.contenteditable={get:L.get,set:function(a,b,c){b===""&&(b="false"),L.set(a,b,c)}}),p.support.hrefNormalized||p.each(["href","src","width","height"],function(a,c){p.attrHooks[c]=p.extend(p.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),p.support.style||(p.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),p.support.optSelected||(p.propHooks.selected=p.extend(p.propHooks.selected,{get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}})),p.support.enctype||(p.propFix.enctype="encoding"),p.support.checkOn||p.each(["radio","checkbox"],function(){p.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),p.each(["radio","checkbox"],function(){p.valHooks[this]=p.extend(p.valHooks[this],{set:function(a,b){if(p.isArray(b))return a.checked=p.inArray(p(a).val(),b)>=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j<c.length;j++){k=W.exec(c[j])||[],l=k[1],m=(k[2]||"").split(".").sort(),r=p.event.special[l]||{},l=(f?r.delegateType:r.bindType)||l,r=p.event.special[l]||{},n=p.extend({type:l,origType:k[1],data:e,handler:d,guid:d.guid,selector:f,namespace:m.join(".")},o),q=i[l];if(!q){q=i[l]=[],q.delegateCount=0;if(!r.setup||r.setup.call(a,e,m,h)===!1)a.addEventListener?a.addEventListener(l,h,!1):a.attachEvent&&a.attachEvent("on"+l,h)}r.add&&(r.add.call(a,n),n.handler.guid||(n.handler.guid=d.guid)),f?q.splice(q.delegateCount++,0,n):q.push(n),p.event.global[l]=!0}a=null},global:{},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,q,r=p.hasData(a)&&p._data(a);if(!r||!(m=r.events))return;b=p.trim(_(b||"")).split(" ");for(f=0;f<b.length;f++){g=W.exec(b[f])||[],h=i=g[1],j=g[2];if(!h){for(h in m)p.event.remove(a,h+b[f],c,d,!0);continue}n=p.event.special[h]||{},h=(d?n.delegateType:n.bindType)||h,o=m[h]||[],k=o.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(l=0;l<o.length;l++)q=o[l],(e||i===q.origType)&&(!c||c.guid===q.guid)&&(!j||j.test(q.namespace))&&(!d||d===q.selector||d==="**"&&q.selector)&&(o.splice(l--,1),q.selector&&o.delegateCount--,n.remove&&n.remove.call(a,q));o.length===0&&k!==o.length&&((!n.teardown||n.teardown.call(a,j,r.handle)===!1)&&p.removeEvent(a,h,r.handle),delete m[h])}p.isEmptyObject(m)&&(delete r.handle,p.removeData(a,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,f,g){if(!f||f.nodeType!==3&&f.nodeType!==8){var h,i,j,k,l,m,n,o,q,r,s=c.type||c,t=[];if($.test(s+p.event.triggered))return;s.indexOf("!")>=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j<q.length&&!c.isPropagationStopped();j++)k=q[j][0],c.type=q[j][1],o=(p._data(k,"events")||{})[c.type]&&p._data(k,"handle"),o&&o.apply(k,d),o=m&&k[m],o&&p.acceptData(k)&&o.apply(k,d)===!1&&c.preventDefault();return c.type=s,!g&&!c.isDefaultPrevented()&&(!n._default||n._default.apply(f.ownerDocument,d)===!1)&&(s!=="click"||!p.nodeName(f,"a"))&&p.acceptData(f)&&m&&f[s]&&(s!=="focus"&&s!=="blur"||c.target.offsetWidth!==0)&&!p.isWindow(f)&&(l=f[m],l&&(f[m]=null),p.event.triggered=s,f[s](),p.event.triggered=b,l&&(f[m]=l)),c.result}return},dispatch:function(c){c=p.event.fix(c||a.event);var d,e,f,g,h,i,j,k,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=[].slice.call(arguments),s=!c.exclusive&&!c.namespace,t=p.event.special[c.type]||{},u=[];r[0]=c,c.delegateTarget=this;if(t.preDispatch&&t.preDispatch.call(this,c)===!1)return;if(q&&(!c.button||c.type!=="click")){g=p(this),g.context=this;for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){i={},k=[],g[0]=f;for(d=0;d<q;d++)l=o[d],m=l.selector,i[m]===b&&(i[m]=g.is(m)),i[m]&&k.push(l);k.length&&u.push({elem:f,matches:k})}}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){j=u[d],c.currentTarget=j.elem;for(e=0;e<j.matches.length&&!c.isImmediatePropagationStopped();e++){l=j.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,h=((p.event.special[l.origType]||{}).handle||l.handler).apply(j.elem,r),h!==b&&(c.result=h,h===!1&&(c.preventDefault(),c.stopPropagation()))}}return t.postDispatch&&t.postDispatch.call(this,c),c.result},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(a,b){return a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,c){var d,f,g,h=c.button,i=c.fromElement;return a.pageX==null&&c.clientX!=null&&(d=a.target.ownerDocument||e,f=d.documentElement,g=d.body,a.pageX=c.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=c.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?c.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0),a}},fix:function(a){if(a[p.expando])return a;var b,c,d=a,f=p.event.fixHooks[a.type]||{},g=f.props?this.props.concat(f.props):this.props;a=p.Event(d);for(b=g.length;b;)c=g[--b],a[c]=d[c];return a.target||(a.target=d.srcElement||e),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,f.filter?f.filter(a,d):a},special:{ready:{setup:p.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){p.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=p.extend(new p.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?p.event.trigger(e,null,b):p.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},p.event.handle=p.event.dispatch,p.removeEvent=e.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]=="undefined"&&(a[d]=null),a.detachEvent(d,c))},p.Event=function(a,b){if(this instanceof p.Event)a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?bb:ba):this.type=a,b&&p.extend(this,b),this.timeStamp=a&&a.timeStamp||p.now(),this[p.expando]=!0;else return new p.Event(a,b)},p.Event.prototype={preventDefault:function(){this.isDefaultPrevented=bb;var a=this.originalEvent;if(!a)return;a.preventDefault?a.preventDefault():a.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=bb;var a=this.originalEvent;if(!a)return;a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()},isDefaultPrevented:ba,isPropagationStopped:ba,isImmediatePropagationStopped:ba},p.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){p.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj,g=f.selector;if(!e||e!==d&&!p.contains(d,e))a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b;return c}}}),p.support.submitBubbles||(p.event.special.submit={setup:function(){if(p.nodeName(this,"form"))return!1;p.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=p.nodeName(c,"input")||p.nodeName(c,"button")?c.form:b;d&&!p._data(d,"_submit_attached")&&(p.event.add(d,"submit._submit",function(a){a._submit_bubble=!0}),p._data(d,"_submit_attached",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&p.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){if(p.nodeName(this,"form"))return!1;p.event.remove(this,"._submit")}}),p.support.changeBubbles||(p.event.special.change={setup:function(){if(V.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")p.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),p.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),p.event.simulate("change",this,a,!0)});return!1}p.event.add(this,"beforeactivate._change",function(a){var b=a.target;V.test(b.nodeName)&&!p._data(b,"_change_attached")&&(p.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&p.event.simulate("change",this.parentNode,a,!0)}),p._data(b,"_change_attached",!0))})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){return p.event.remove(this,"._change"),V.test(this.nodeName)}}),p.support.focusinBubbles||p.each({focus:"focusin",blur:"focusout"},function(a,b){var c=0,d=function(a){p.event.simulate(b,a.target,p.event.fix(a),!0)};p.event.special[b]={setup:function(){c++===0&&e.addEventListener(a,d,!0)},teardown:function(){--c===0&&e.removeEventListener(a,d,!0)}}}),p.fn.extend({on:function(a,c,d,e,f){var g,h;if(typeof a=="object"){typeof c!="string"&&(d=d||c,c=b);for(h in a)this.on(h,c,d,a[h],f);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=ba;else if(!e)return this;return f===1&&(g=e,e=function(a){return p().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=p.guid++)),this.each(function(){p.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,c,d){var e,f;if(a&&a.preventDefault&&a.handleObj)return e=a.handleObj,p(a.delegateTarget).off(e.namespace?e.origType+"."+e.namespace:e.origType,e.selector,e.handler),this;if(typeof a=="object"){for(f in a)this.off(f,c,a[f]);return this}if(c===!1||typeof c=="function")d=c,c=b;return d===!1&&(d=ba),this.each(function(){p.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){return p(this.context).on(a,this.selector,b,c),this},die:function(a,b){return p(this.context).off(a,this.selector||"**",b),this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a||"**",c)},trigger:function(a,b){return this.each(function(){p.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return p.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||p.guid++,d=0,e=function(c){var e=(p._data(this,"lastToggle"+a.guid)||0)%d;return p._data(this,"lastToggle"+a.guid,e+1),c.preventDefault(),b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),p.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(a,b){p.fn[b]=function(a,c){return c==null&&(c=a,a=null),arguments.length>0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bd(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)Z(a,b[e],c,d)}function be(a,b,c,d,e,f){var g,h=$.setFilters[b.toLowerCase()];return h||Z.error(b),(a||!(g=e))&&bd(a||"*",d,g=[],e),g.length>0?h(g,c,f):[]}function bf(a,c,d,e,f){var g,h,i,j,k,l,m,n,p=0,q=f.length,s=L.POS,t=new RegExp("^"+s.source+"(?!"+r+")","i"),u=function(){var a=1,c=arguments.length-2;for(;a<c;a++)arguments[a]===b&&(g[a]=b)};for(;p<q;p++){s.exec(""),a=f[p],j=[],i=0,k=e;while(g=s.exec(a)){n=s.lastIndex=g.index+g[0].length;if(n>i){m=a.slice(i,g.index),i=n,l=[c],B.test(m)&&(k&&(l=k),k=e);if(h=H.test(m))m=m.slice(0,-5).replace(B,"$&*");g.length>1&&g[0].replace(t,u),k=be(m,g[1],g[2],l,k,h)}}k?(j=j.concat(k),(m=a.slice(i))&&m!==")"?B.test(m)?bd(m,j,d,e):Z(m,c,d,e?e.concat(k):k):o.apply(d,j)):Z(a,c,d,e)}return q===1?d:Z.uniqueSort(d)}function bg(a,b,c){var d,e,f,g=[],i=0,j=D.exec(a),k=!j.pop()&&!j.pop(),l=k&&a.match(C)||[""],m=$.preFilter,n=$.filter,o=!c&&b!==h;for(;(e=l[i])!=null&&k;i++){g.push(d=[]),o&&(e=" "+e);while(e){k=!1;if(j=B.exec(e))e=e.slice(j[0].length),k=d.push({part:j.pop().replace(A," "),captures:j});for(f in n)(j=L[f].exec(e))&&(!m[f]||(j=m[f](j,b,c)))&&(e=e.slice(j.shift().length),k=d.push({part:f,captures:j}));if(!k)break}}return k||Z.error(a),g}function bh(a,b,e){var f=b.dir,g=m++;return a||(a=function(a){return a===e}),b.first?function(b,c){while(b=b[f])if(b.nodeType===1)return a(b,c)&&b}:function(b,e){var h,i=g+"."+d,j=i+"."+c;while(b=b[f])if(b.nodeType===1){if((h=b[q])===j)return b.sizset;if(typeof h=="string"&&h.indexOf(i)===0){if(b.sizset)return b}else{b[q]=j;if(a(b,e))return b.sizset=!0,b;b.sizset=!1}}}}function bi(a,b){return a?function(c,d){var e=b(c,d);return e&&a(e===!0?c:e,d)}:b}function bj(a,b,c){var d,e,f=0;for(;d=a[f];f++)$.relative[d.part]?e=bh(e,$.relative[d.part],b):(d.captures.push(b,c),e=bi(e,$.filter[d.part].apply(null,d.captures)));return e}function bk(a){return function(b,c){var d,e=0;for(;d=a[e];e++)if(d(b,c))return!0;return!1}}var c,d,e,f,g,h=a.document,i=h.documentElement,j="undefined",k=!1,l=!0,m=0,n=[].slice,o=[].push,q=("sizcache"+Math.random()).replace(".",""),r="[\\x20\\t\\r\\n\\f]",s="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",t=s.replace("w","w#"),u="([*^$|!~]?=)",v="\\["+r+"*("+s+")"+r+"*(?:"+u+r+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+t+")|)|)"+r+"*\\]",w=":("+s+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)",x=":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)",y=r+"*([\\x20\\t\\r\\n\\f>+~])"+r+"*",z="(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|"+v+"|"+w.replace(2,7)+"|[^\\\\(),])+",A=new RegExp("^"+r+"+|((?:^|[^\\\\])(?:\\\\.)*)"+r+"+$","g"),B=new RegExp("^"+y),C=new RegExp(z+"?(?="+r+"*,|$)","g"),D=new RegExp("^(?:(?!,)(?:(?:^|,)"+r+"*"+z+")*?|"+r+"*(.*?))(\\)|$)"),E=new RegExp(z.slice(19,-6)+"\\x20\\t\\r\\n\\f>+~])+|"+y,"g"),F=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,G=/[\x20\t\r\n\f]*[+~]/,H=/:not\($/,I=/h\d/i,J=/input|select|textarea|button/i,K=/\\(?!\\)/g,L={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),NAME:new RegExp("^\\[name=['\"]?("+s+")['\"]?\\]"),TAG:new RegExp("^("+s.replace("[-","[-\\*")+")"),ATTR:new RegExp("^"+v),PSEUDO:new RegExp("^"+w),CHILD:new RegExp("^:(only|nth|last|first)-child(?:\\("+r+"*(even|odd|(([+-]|)(\\d*)n|)"+r+"*(?:([+-]|)"+r+"*(\\d+)|))"+r+"*\\)|)","i"),POS:new RegExp(x,"ig"),needsContext:new RegExp("^"+r+"*[>+~]|"+x,"i")},M={},N=[],O={},P=[],Q=function(a){return a.sizzleFilter=!0,a},R=function(a){return function(b){return b.nodeName.toLowerCase()==="input"&&b.type===a}},S=function(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}},T=function(a){var b=!1,c=h.createElement("div");try{b=a(c)}catch(d){}return c=null,b},U=T(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),V=T(function(a){a.id=q+0,a.innerHTML="<a name='"+q+"'></a><div name='"+q+"'></div>",i.insertBefore(a,i.firstChild);var b=h.getElementsByName&&h.getElementsByName(q).length===2+h.getElementsByName(q+0).length;return g=!h.getElementById(q),i.removeChild(a),b}),W=T(function(a){return a.appendChild(h.createComment("")),a.getElementsByTagName("*").length===0}),X=T(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==j&&a.firstChild.getAttribute("href")==="#"}),Y=T(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||a.getElementsByClassName("e").length===0?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length!==1)}),Z=function(a,b,c,d){c=c||[],b=b||h;var e,f,g,i,j=b.nodeType;if(j!==1&&j!==9)return[];if(!a||typeof a!="string")return c;g=ba(b);if(!g&&!d)if(e=F.exec(a))if(i=e[1]){if(j===9){f=b.getElementById(i);if(!f||!f.parentNode)return c;if(f.id===i)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(i))&&bb(b,f)&&f.id===i)return c.push(f),c}else{if(e[2])return o.apply(c,n.call(b.getElementsByTagName(a),0)),c;if((i=e[3])&&Y&&b.getElementsByClassName)return o.apply(c,n.call(b.getElementsByClassName(i),0)),c}return bm(a,b,c,d,g)},$=Z.selectors={cacheLength:50,match:L,order:["ID","TAG"],attrHandle:{},createPseudo:Q,find:{ID:g?function(a,b,c){if(typeof b.getElementById!==j&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==j&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==j&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:W?function(a,b){if(typeof b.getElementsByTagName!==j)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(K,""),a[3]=(a[4]||a[5]||"").replace(K,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||Z.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&Z.error(a[0]),a},PSEUDO:function(a){var b,c=a[4];return L.CHILD.test(a[0])?null:(c&&(b=D.exec(c))&&b.pop()&&(a[0]=a[0].slice(0,b[0].length-c.length-1),c=b[0].slice(0,-1)),a.splice(2,3,c||a[3]),a)}},filter:{ID:g?function(a){return a=a.replace(K,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(K,""),function(b){var c=typeof b.getAttributeNode!==j&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(K,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=M[a];return b||(b=M[a]=new RegExp("(^|"+r+")"+a+"("+r+"|$)"),N.push(a),N.length>$.cacheLength&&delete M[N.shift()]),function(a){return b.test(a.className||typeof a.getAttribute!==j&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return b?function(d){var e=Z.attr(d,a),f=e+"";if(e==null)return b==="!=";switch(b){case"=":return f===c;case"!=":return f!==c;case"^=":return c&&f.indexOf(c)===0;case"*=":return c&&f.indexOf(c)>-1;case"$=":return c&&f.substr(f.length-c.length)===c;case"~=":return(" "+f+" ").indexOf(c)>-1;case"|=":return f===c||f.substr(0,c.length+1)===c+"-"}}:function(b){return Z.attr(b,a)!=null}},CHILD:function(a,b,c,d){if(a==="nth"){var e=m++;return function(a){var b,f,g=0,h=a;if(c===1&&d===0)return!0;b=a.parentNode;if(b&&(b[q]!==e||!a.sizset)){for(h=b.firstChild;h;h=h.nextSibling)if(h.nodeType===1){h.sizset=++g;if(h===a)break}b[q]=e}return f=a.sizset-d,c===0?f===0:f%c===0&&f/c>=0}}return function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b,c,d){var e=$.pseudos[a]||$.pseudos[a.toLowerCase()];return e||Z.error("unsupported pseudo: "+a),e.sizzleFilter?e(b,c,d):e}},pseudos:{not:Q(function(a,b,c){var d=bl(a.replace(A,"$1"),b,c);return function(a){return!d(a)}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!$.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},contains:Q(function(a){return function(b){return(b.textContent||b.innerText||bc(b)).indexOf(a)>-1}}),has:Q(function(a){return function(b){return Z(a,b).length>0}}),header:function(a){return I.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:R("radio"),checkbox:R("checkbox"),file:R("file"),password:R("password"),image:R("image"),submit:S("submit"),reset:S("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return J.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b,c){return c?a.slice(1):[a[0]]},last:function(a,b,c){var d=a.pop();return c?a:[d]},even:function(a,b,c){var d=[],e=c?1:0,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},odd:function(a,b,c){var d=[],e=c?0:1,f=a.length;for(;e<f;e=e+2)d.push(a[e]);return d},lt:function(a,b,c){return c?a.slice(+b):a.slice(0,+b)},gt:function(a,b,c){return c?a.slice(0,+b+1):a.slice(+b+1)},eq:function(a,b,c){var d=a.splice(+b,1);return c?a:d}}};$.setFilters.nth=$.setFilters.eq,$.filters=$.pseudos,X||($.attrHandle={href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}}),V&&($.order.push("NAME"),$.find.NAME=function(a,b){if(typeof b.getElementsByName!==j)return b.getElementsByName(a)}),Y&&($.order.splice(1,0,"CLASS"),$.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!==j&&!c)return b.getElementsByClassName(a)});try{n.call(i.childNodes,0)[0].nodeType}catch(_){n=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}var ba=Z.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},bb=Z.contains=i.compareDocumentPosition?function(a,b){return!!(a.compareDocumentPosition(b)&16)}:i.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc=Z.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=bc(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=bc(b);return c};Z.attr=function(a,b){var c,d=ba(a);return d||(b=b.toLowerCase()),$.attrHandle[b]?$.attrHandle[b](a):U||d?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},Z.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},[0,0].sort(function(){return l=0}),i.compareDocumentPosition?e=function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:(e=function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],g=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return f(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)g.unshift(j),j=j.parentNode;c=e.length,d=g.length;for(var l=0;l<c&&l<d;l++)if(e[l]!==g[l])return f(e[l],g[l]);return l===c?f(a,g[l],-1):f(e[l],b,1)},f=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}),Z.uniqueSort=function(a){var b,c=1;if(e){k=l,a.sort(e);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1)}return a};var bl=Z.compile=function(a,b,c){var d,e,f,g=O[a];if(g&&g.context===b)return g;e=bg(a,b,c);for(f=0;d=e[f];f++)e[f]=bj(d,b,c);return g=O[a]=bk(e),g.context=b,g.runs=g.dirruns=0,P.push(a),P.length>$.cacheLength&&delete O[P.shift()],g};Z.matches=function(a,b){return Z(a,null,null,b)},Z.matchesSelector=function(a,b){return Z(b,null,null,[a]).length>0};var bm=function(a,b,e,f,g){a=a.replace(A,"$1");var h,i,j,k,l,m,p,q,r,s=a.match(C),t=a.match(E),u=b.nodeType;if(L.POS.test(a))return bf(a,b,e,f,s);if(f)h=n.call(f,0);else if(s&&s.length===1){if(t.length>1&&u===9&&!g&&(s=L.ID.exec(t[0]))){b=$.find.ID(s[1],b,g)[0];if(!b)return e;a=a.slice(t.shift().length)}q=(s=G.exec(t[0]))&&!s.index&&b.parentNode||b,r=t.pop(),m=r.split(":not")[0];for(j=0,k=$.order.length;j<k;j++){p=$.order[j];if(s=L[p].exec(m)){h=$.find[p]((s[1]||"").replace(K,""),q,g);if(h==null)continue;m===r&&(a=a.slice(0,a.length-r.length)+m.replace(L[p],""),a||o.apply(e,n.call(h,0)));break}}}if(a){i=bl(a,b,g),d=i.dirruns++,h==null&&(h=$.find.TAG("*",G.test(a)&&b.parentNode||b));for(j=0;l=h[j];j++)c=i.runs++,i(l,b)&&e.push(l)}return e};h.querySelectorAll&&function(){var a,b=bm,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[],f=[":active"],g=i.matchesSelector||i.mozMatchesSelector||i.webkitMatchesSelector||i.oMatchesSelector||i.msMatchesSelector;T(function(a){a.innerHTML="<select><option selected></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+r+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),T(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+r+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=e.length&&new RegExp(e.join("|")),bm=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a)))if(d.nodeType===9)try{return o.apply(f,n.call(d.querySelectorAll(a),0)),f}catch(i){}else if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){var j=d.getAttribute("id"),k=j||q,l=G.test(a)&&d.parentNode||d;j?k=k.replace(c,"\\$&"):d.setAttribute("id",k);try{return o.apply(f,n.call(l.querySelectorAll(a.replace(C,"[id='"+k+"'] $&")),0)),f}catch(i){}finally{j||d.removeAttribute("id")}}return b(a,d,f,g,h)},g&&(T(function(b){a=g.call(b,"div");try{g.call(b,"[test!='']:sizzle"),f.push($.match.PSEUDO)}catch(c){}}),f=new RegExp(f.join("|")),Z.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!ba(b)&&!f.test(c)&&(!e||!e.test(c)))try{var h=g.call(b,c);if(h||a||b.document&&b.document.nodeType!==11)return h}catch(i){}return Z(c,null,null,[b]).length>0})}(),Z.attr=p.attr,p.find=Z,p.expr=Z.selectors,p.expr[":"]=p.expr.pseudos,p.unique=Z.uniqueSort,p.text=Z.getText,p.isXMLDoc=Z.isXML,p.contains=Z.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b<c;b++)if(p.contains(h[b],this))return!0});g=this.pushStack("","find",a);for(b=0,c=this.length;b<c;b++){d=g.length,p.find(a,this[b],g);if(b>0)for(e=d;e<g.length;e++)for(f=0;f<d;f++)if(g[f]===g[e]){g.splice(e--,1);break}}return g},has:function(a){var b,c=p(a,this),d=c.length;return this.filter(function(){for(b=0;b<d;b++)if(p.contains(this,c[b]))return!0})},not:function(a){return this.pushStack(bj(this,a,!1),"not",a)},filter:function(a){return this.pushStack(bj(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?bf.test(a)?p(a,this.context).index(this[0])>=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d<e;d++){c=this[d];while(c&&c.ownerDocument&&c!==b&&c.nodeType!==11){if(g?g.index(c)>-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/<tbody/i,br=/<|&#?\w+;/,bs=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,bu=new RegExp("<(?:"+bl+")[\\s/>]","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,bz={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,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X<div>","</div>"]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(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){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1></$2>");try{for(;d<e;d++)c=this[d]||{},c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),c.innerHTML=a);c=0}catch(f){}}c&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(a){return bh(this[0])?this.length?this.pushStack(p(p.isFunction(a)?a():a),"replaceWith",a):this:p.isFunction(a)?this.each(function(b){var c=p(this),d=c.html();c.replaceWith(a.call(this,b,d))}):(typeof a!="string"&&(a=p(a).detach()),this.each(function(){var b=this.nextSibling,c=this.parentNode;p(this).remove(),b?p(b).before(a):p(c).append(a)}))},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){a=[].concat.apply([],a);var e,f,g,h,i=0,j=a[0],k=[],l=this.length;if(!p.support.checkClone&&l>1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i<l;i++)d.call(c&&p.nodeName(this[i],"table")?bC(this[i],"tbody"):this[i],i===h?g:p.clone(g,!0,!0))}g=f=null,k.length&&p.each(k,function(a,b){b.src?p.ajax?p.ajax({url:b.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):p.error("no ajax"):p.globalEval((b.text||b.textContent||b.innerHTML||"").replace(by,"")),b.parentNode&&b.parentNode.removeChild(b)})}return this}}),p.buildFragment=function(a,c,d){var f,g,h,i=a[0];return c=c||e,c=(c[0]||c).ownerDocument||c[0]||c,typeof c.createDocumentFragment=="undefined"&&(c=e),a.length===1&&typeof i=="string"&&i.length<512&&c===e&&i.charAt(0)==="<"&&!bt.test(i)&&(p.support.checkClone||!bw.test(i))&&(p.support.html5Clone||!bu.test(i))&&(g=!0,f=p.fragments[i],h=f!==b),f||(f=c.createDocumentFragment(),p.clean(a,c,f,d),g&&(p.fragments[i]=h&&f)),{fragment:f,cacheable:g}},p.fragments={},p.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){p.fn[a]=function(c){var d,e=0,f=[],g=p(c),h=g.length,i=this.length===1&&this[0].parentNode;if((i==null||i&&i.nodeType===11&&i.childNodes.length===1)&&h===1)return g[b](this[0]),this;for(;e<h;e++)d=(e>0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=0,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(g=b===e&&bA;(h=a[s])!=null;s++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{g=g||bk(b),l=l||g.appendChild(b.createElement("div")),h=h.replace(bo,"<$1></$2>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]==="<table>"&&!m?l.childNodes:[];for(f=n.length-1;f>=0;--f)p.nodeName(n[f],"tbody")&&!n[f].childNodes.length&&n[f].parentNode.removeChild(n[f])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l=g.lastChild}h.nodeType?t.push(h):t=p.merge(t,h)}l&&(g.removeChild(l),h=l=g=null);if(!p.support.appendChecked)for(s=0;(h=t[s])!=null;s++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(s=0;(h=t[s])!=null;s++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[s+1,0].concat(r)),s+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^margin/,bO=new RegExp("^("+q+")(.*)$","i"),bP=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bQ=new RegExp("^([-+])=("+q+")","i"),bR={},bS={position:"absolute",visibility:"hidden",display:"block"},bT={letterSpacing:0,fontWeight:400,lineHeight:1},bU=["Top","Right","Bottom","Left"],bV=["Webkit","O","Moz","ms"],bW=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return bZ(this,!0)},hide:function(){return bZ(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bW.apply(this,arguments):this.each(function(){(c?a:bY(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bX(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bQ.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bX(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bT&&(f=bT[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(a,b){var c,d,e,f,g=getComputedStyle(a,null),h=a.style;return g&&(c=g[b],c===""&&!p.contains(a.ownerDocument.documentElement,a)&&(c=p.style(a,b)),bP.test(c)&&bN.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=c,c=g.width,h.width=d,h.minWidth=e,h.maxWidth=f)),c}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bP.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth!==0||bH(a,"display")!=="none"?ca(a,b,d):p.swap(a,bS,function(){return ca(a,b,d)})},set:function(a,c,d){return b$(a,c,d?b_(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bP.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bU[d]+b]=e[d]||e[d-2]||e[0];return f}},bN.test(a)||(p.cssHooks[a+b].set=b$)});var cc=/%20/g,cd=/\[\]$/,ce=/\r?\n/g,cf=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,cg=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||cg.test(this.nodeName)||cf.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(ce,"\r\n")}}):{name:b.name,value:c.replace(ce,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ch(d,a[d],c,f);return e.join("&").replace(cc,"+")};var ci,cj,ck=/#.*$/,cl=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cm=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,cn=/^(?:GET|HEAD)$/,co=/^\/\//,cp=/\?/,cq=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cr=/([?&])_=[^&]*/,cs=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,ct=p.fn.load,cu={},cv={},cw=["*/"]+["*"];try{ci=f.href}catch(cx){ci=e.createElement("a"),ci.href="",ci=ci.href}cj=cs.exec(ci.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&ct)return ct.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("<div>").append(a.replace(cq,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cA(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cA(a,b),a},ajaxSettings:{url:ci,isLocal:cm.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cw},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cy(cu),ajaxTransport:cy(cv),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cB(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cC(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=""+(c||y),k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cl.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(ck,"").replace(co,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=cs.exec(l.url.toLowerCase()),l.crossDomain=!(!i||i[1]==cj[1]&&i[2]==cj[2]&&(i[3]||(i[1]==="http:"?80:443))==(cj[3]||(cj[1]==="http:"?80:443)))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cz(cu,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!cn.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cp.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cr,"$1_="+z);l.url=A+(A===l.url?(cp.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cw+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cz(cv,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cD=[],cE=/\?/,cF=/(=)\?(?=&|$)|\?\?/,cG=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cD.pop()||p.expando+"_"+cG++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cF.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cF.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cF,"$1"+f):m?c.data=i.replace(cF,"$1"+f):k&&(c.url+=(cE.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cD.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cH,cI=a.ActiveXObject?function(){for(var a in cH)cH[a](0,1)}:!1,cJ=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cK()||cL()}:cK,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cI&&delete cH[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cJ,cI&&(cH||(cH={},p(a).unload(cI)),cH[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cM,cN,cO=/^(?:toggle|show|hide)$/,cP=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cQ=/queueHooks$/,cR=[cX],cS={"*":[function(a,b){var c,d,e,f=this.createTween(a,b),g=cP.exec(b),h=f.cur(),i=+h||0,j=1;if(g){c=+g[2],d=g[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&i){i=p.css(f.elem,a,!0)||c||1;do e=j=j||".5",i=i/j,p.style(f.elem,a,i+d),j=f.cur()/h;while(j!==1&&j!==e)}f.unit=d,f.start=i,f.end=g[1]?i+(g[1]+1)*c:c}return f}]};p.Animation=p.extend(cV,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d<e;d++)c=a[d],cS[c]=cS[c]||[],cS[c].unshift(b)},prefilter:function(a,b){b?cR.unshift(a):cR.push(a)}}),p.Tween=cY,cY.prototype={constructor:cY,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(p.cssNumber[c]?"":"px")},cur:function(){var a=cY.propHooks[this.prop];return a&&a.get?a.get(this):cY.propHooks._default.get(this)},run:function(a){var b,c=cY.propHooks[this.prop];return this.pos=b=p.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration),this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):cY.propHooks._default.set(this),this}},cY.prototype.init.prototype=cY.prototype,cY.propHooks={_default:{get:function(a){var b;return a.elem[a.prop]==null||!!a.elem.style&&a.elem.style[a.prop]!=null?(b=p.css(a.elem,a.prop,!1,""),!b||b==="auto"?0:b):a.elem[a.prop]},set:function(a){p.fx.step[a.prop]?p.fx.step[a.prop](a):a.elem.style&&(a.elem.style[p.cssProps[a.prop]]!=null||p.cssHooks[a.prop])?p.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},cY.propHooks.scrollTop=cY.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},p.each(["toggle","show","hide"],function(a,b){var c=p.fn[b];p.fn[b]=function(d,e,f){return d==null||typeof d=="boolean"||!a&&p.isFunction(d)&&p.isFunction(e)?c.apply(this,arguments):this.animate(cZ(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bY).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=p.isEmptyObject(a),f=p.speed(b,c,d),g=function(){var b=cV(this,p.extend({},a),f);e&&b.stop(!0)};return e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,c,d){var e=function(a){var b=a.stop;delete a.stop,b(d)};return typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,c=a!=null&&a+"queueHooks",f=p.timers,g=p._data(this);if(c)g[c]&&g[c].stop&&e(g[c]);else for(c in g)g[c]&&g[c].stop&&cQ.test(c)&&e(g[c]);for(c=f.length;c--;)f[c].elem===this&&(a==null||f[c].queue===a)&&(f[c].anim.stop(d),b=!1,f.splice(c,1));(b||!d)&&p.dequeue(this,a)})}}),p.each({slideDown:cZ("show"),slideUp:cZ("hide"),slideToggle:cZ("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){p.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),p.speed=function(a,b,c){var d=a&&typeof a=="object"?p.extend({},a):{complete:c||!c&&b||p.isFunction(a)&&a,duration:a,easing:c&&b||b&&!p.isFunction(b)&&b};d.duration=p.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in p.fx.speeds?p.fx.speeds[d.duration]:p.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";return d.old=d.complete,d.complete=function(){p.isFunction(d.old)&&d.old.call(this),d.queue&&p.dequeue(this,d.queue)},d},p.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},p.timers=[],p.fx=cY.prototype.init,p.fx.tick=function(){var a,b=p.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||p.fx.stop()},p.fx.timer=function(a){a()&&p.timers.push(a)&&!cN&&(cN=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cN),cN=null},p.fx.speeds={slow:600,fast:200,_default:400},p.fx.step={},p.expr&&p.expr.filters&&(p.expr.filters.animated=function(a){return p.grep(p.timers,function(b){return a===b.elem}).length});var c$=/^(?:body|html)$/i;p.fn.offset=function(a){if(arguments.length)return a===b?this:this.each(function(b){p.offset.setOffset(this,a,b)});var c,d,e,f,g,h,i,j,k,l,m=this[0],n=m&&m.ownerDocument;if(!n)return;return(e=n.body)===m?p.offset.bodyOffset(m):(d=n.documentElement,p.contains(d,m)?(c=m.getBoundingClientRect(),f=c_(n),g=d.clientTop||e.clientTop||0,h=d.clientLeft||e.clientLeft||0,i=f.pageYOffset||d.scrollTop,j=f.pageXOffset||d.scrollLeft,k=c.top+i-g,l=c.left+j-h,{top:k,left:l}):{top:0,left:0})},p.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;return p.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(p.css(a,"marginTop"))||0,c+=parseFloat(p.css(a,"marginLeft"))||0),{top:b,left:c}},setOffset:function(a,b,c){var d=p.css(a,"position");d==="static"&&(a.style.position="relative");var e=p(a),f=e.offset(),g=p.css(a,"top"),h=p.css(a,"left"),i=(d==="absolute"||d==="fixed")&&p.inArray("auto",[g,h])>-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c$.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c$.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=c_(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window);
src/server.js
literarymachine/crg-ui
import React from 'react' import { renderToString } from 'react-dom/server' import path from 'path' import express from 'express' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' import template from './views/index' import webpackConfig from '../webpack.config.babel' import Api from './api' import Init from './components/Init' import { getTitle } from './common' import Config, { apiConfig } from '../config' const server = express() server.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept") next() }) if (process.env.NODE_ENV === 'development') { const compiler = webpack(webpackConfig) server.use([ webpackDevMiddleware(compiler, { filename: webpackConfig.output.filename, hot: true, overlay: true, stats: { colors: true } }), webpackHotMiddleware(compiler, { log: console.log }) ]) } server.use(express.static(path.join(__dirname, '/../dist'))) server.get(/^(.*)$/, (req, res) => { const defaultLanguage = 'en' const supportedLanguages = [ 'en', 'de', 'es' ] const requestedLanguages = req.headers['accept-language'] ? req.headers['accept-language'].split(',').map(language => { return language.split(';')[0] }) : [defaultLanguage] const acceptedLanguages = requestedLanguages.filter(language => { return supportedLanguages.includes(language) }) if (!acceptedLanguages.includes(defaultLanguage)) { acceptedLanguages.push(defaultLanguage) } const api = new Api(apiConfig) api.load(req.url, response => { const initialState = { data: response.data, user: response.user, locales: acceptedLanguages, apiConfig } res.send(template({ body: renderToString(<Init {...initialState} emitter={{}} />), title: getTitle(initialState.data), initialState: JSON.stringify(initialState) })) }, req.get("authorization")) }) server.listen(Config.port, Config.host, function () { console.info(`crg-ui server listening on http://${Config.host}:${Config.port}`) })
Mr.Mining/MikeTheMiner/Santas_helpers/Sia_wallet/resources/app/plugins/Files/js/components/uploaddialog.js
patel344/Mr.Miner
import PropTypes from 'prop-types' import React from 'react' import fs from 'graceful-fs' const UploadDialog = ({source, path, actions}) => { const onUploadClick = () => { source.forEach((file) => { if (fs.statSync(file).isDirectory()) { actions.uploadFolder(path, file) } else { actions.uploadFile(path, file) } }) actions.hideUploadDialog() } const onCancelClick = () => actions.hideUploadDialog() return ( <div className="modal"> <div className="upload-dialog"> <h1> Confirm Upload </h1> <div>Would you like to upload {source.length} {source.length === 1 ? 'item' : 'items'}?</div> <div className="upload-dialog-buttons"> <button onClick={onUploadClick}>Upload</button> <button onClick={onCancelClick}>Cancel</button> </div> </div> </div> ) } UploadDialog.propTypes = { source: PropTypes.array.isRequired, path: PropTypes.string.isRequired, } export default UploadDialog
src/lib/components/form/Radio.js
lighter-cd/ezui_react_one
import React from 'react'; import injectSheet from 'react-jss'; import classNames from 'classnames'; const styles = theme => ({ radio: { appearance: 'none', position: 'relative', width: theme.radioSizeOuter, height: theme.radioSizeOuter, border: `${theme.radioBorder} solid ${theme.radioUncheckBorderColor}`, outline: 0, borderRadius: theme.radioBorderRadiusOuter, boxSizing: 'border-box', backgroundColor: theme.radioUncheckBgColor, '&:checked': { borderColor: theme.radioCheckBorderColor, backgroundColor: theme.radioCheckBgColor, '&:after': { content: '" "', position: 'absolute', top: theme.radioCenter, left: theme.radioCenter, width: theme.radioSize, height: theme.radioSize, borderRadius: theme.radioBorderRadius, backgroundColor: theme.radioColor, }, }, }, }); const Radio = (props) => { const { classes, className, sheet, theme, ...others } = props; const cls = classNames(classes.radio, { [className]: className, }); return ( <div> <input className={cls} type="radio" {...others} /> </div> ); }; export default injectSheet(styles)(Radio);
ajax/libs/babel-core/5.7.3/browser-polyfill.min.js
kiwi89/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;function drainQueue(){if(draining){return}draining=true;var currentQueue;var len=queue.length;while(len){currentQueue=queue;queue=[];var i=-1;while(++i<len){currentQueue[i]()}len=queue.length}draining=false}process.nextTick=function(fun){queue.push(fun);if(!draining){setTimeout(drainQueue,0)}};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],2:[function(require,module,exports){(function(global){"use strict";require("core-js/shim");require("regenerator/runtime");if(global._babelPolyfill){throw new Error("only one instance of babel/polyfill is allowed")}global._babelPolyfill=true}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"core-js/shim":91,"regenerator/runtime":92}],3:[function(require,module,exports){var $=require("./$");module.exports=function(IS_INCLUDES){return function($this,el,fromIndex){var O=$.toObject($this),length=$.toLength(O.length),index=$.toIndex(fromIndex,length),value;if(IS_INCLUDES&&el!=el)while(length>index){value=O[index++];if(value!=value)return true}else for(;length>index;index++)if(IS_INCLUDES||index in O){if(O[index]===el)return IS_INCLUDES||index}return!IS_INCLUDES&&-1}}},{"./$":24}],4:[function(require,module,exports){var $=require("./$"),ctx=require("./$.ctx");module.exports=function(TYPE){var IS_MAP=TYPE==1,IS_FILTER=TYPE==2,IS_SOME=TYPE==3,IS_EVERY=TYPE==4,IS_FIND_INDEX=TYPE==6,NO_HOLES=TYPE==5||IS_FIND_INDEX;return function($this,callbackfn,that){var O=Object($.assertDefined($this)),self=$.ES5Object(O),f=ctx(callbackfn,that,3),length=$.toLength(self.length),index=0,result=IS_MAP?Array(length):IS_FILTER?[]:undefined,val,res;for(;length>index;index++)if(NO_HOLES||index in self){val=self[index];res=f(val,index,O);if(TYPE){if(IS_MAP)result[index]=res;else if(res)switch(TYPE){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(IS_EVERY)return false}}return IS_FIND_INDEX?-1:IS_SOME||IS_EVERY?IS_EVERY:result}}},{"./$":24,"./$.ctx":12}],5:[function(require,module,exports){var $=require("./$");function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}assert.def=$.assertDefined;assert.fn=function(it){if(!$.isFunction(it))throw TypeError(it+" is not a function!");return it};assert.obj=function(it){if(!$.isObject(it))throw TypeError(it+" is not an object!");return it};assert.inst=function(it,Constructor,name){if(!(it instanceof Constructor))throw TypeError(name+": use the 'new' operator!");return it};module.exports=assert},{"./$":24}],6:[function(require,module,exports){var $=require("./$"),enumKeys=require("./$.enum-keys");module.exports=Object.assign||function assign(target,source){var T=Object($.assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=$.ES5Object(arguments[i++]),keys=enumKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T}},{"./$":24,"./$.enum-keys":15}],7:[function(require,module,exports){var $=require("./$"),TAG=require("./$.wks")("toStringTag"),toString={}.toString;function cof(it){return toString.call(it).slice(8,-1)}cof.classof=function(it){var O,T;return it==undefined?it===undefined?"Undefined":"Null":typeof(T=(O=Object(it))[TAG])=="string"?T:cof(O)};cof.set=function(it,tag,stat){if(it&&!$.has(it=stat?it:it.prototype,TAG))$.hide(it,TAG,tag)};module.exports=cof},{"./$":24,"./$.wks":42}],8:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),safe=require("./$.uid").safe,assert=require("./$.assert"),forOf=require("./$.for-of"),step=require("./$.iter").step,$has=$.has,set=$.set,isObject=$.isObject,hide=$.hide,isExtensible=Object.isExtensible||isObject,ID=safe("id"),O1=safe("O1"),LAST=safe("last"),FIRST=safe("first"),ITER=safe("iter"),SIZE=$.DESC?safe("size"):"size",id=0;function fastKey(it,create){if(!isObject(it))return typeof it=="symbol"?it:(typeof it=="string"?"S":"P")+it;if(!$has(it,ID)){if(!isExtensible(it))return"F";if(!create)return"E";hide(it,ID,++id)}return"O"+it[ID]}function getEntry(that,key){var index=fastKey(key),entry;if(index!=="F")return that[O1][index];for(entry=that[FIRST];entry;entry=entry.n){if(entry.k==key)return entry}}module.exports={getConstructor:function(wrapper,NAME,IS_MAP,ADDER){var C=wrapper(function(that,iterable){assert.inst(that,C,NAME);set(that,O1,$.create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);if(iterable!=undefined)forOf(iterable,IS_MAP,that[ADDER],that)});require("./$.mix")(C.prototype,{clear:function clear(){for(var that=this,data=that[O1],entry=that[FIRST];entry;entry=entry.n){entry.r=true;if(entry.p)entry.p=entry.p.n=undefined;delete data[entry.i]}that[FIRST]=that[LAST]=undefined;that[SIZE]=0},"delete":function(key){var that=this,entry=getEntry(that,key);if(entry){var next=entry.n,prev=entry.p;delete that[O1][entry.i];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}return!!entry},forEach:function forEach(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function has(key){return!!getEntry(this,key)}});if($.DESC)$.setDesc(C.prototype,"size",{get:function(){return assert.def(this[SIZE])}});return C},def:function(that,key,value){var entry=getEntry(that,key),prev,index;if(entry){entry.v=value}else{that[LAST]=entry={i:index=fastKey(key,true),k:key,v:value,p:prev=that[LAST],n:undefined,r:false};if(!that[FIRST])that[FIRST]=entry;if(prev)prev.n=entry;that[SIZE]++;if(index!=="F")that[O1][index]=entry}return that},getEntry:getEntry,setIter:function(C,NAME,IS_MAP){require("./$.iter-define")(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!iter.o||!(iter.l=entry=entry?entry.n:iter.o[FIRST])){iter.o=undefined;return step(1)}if(kind=="keys")return step(0,entry.k);if(kind=="values")return step(0,entry.v);return step(0,[entry.k,entry.v])},IS_MAP?"entries":"values",!IS_MAP,true)}}},{"./$":24,"./$.assert":5,"./$.ctx":12,"./$.for-of":16,"./$.iter":23,"./$.iter-define":21,"./$.mix":26,"./$.uid":40}],9:[function(require,module,exports){var $def=require("./$.def"),forOf=require("./$.for-of");module.exports=function(NAME){$def($def.P,NAME,{toJSON:function toJSON(){var arr=[];forOf(this,false,arr.push,arr);return arr}})}},{"./$.def":13,"./$.for-of":16}],10:[function(require,module,exports){"use strict";var $=require("./$"),safe=require("./$.uid").safe,assert=require("./$.assert"),forOf=require("./$.for-of"),$has=$.has,isObject=$.isObject,hide=$.hide,isExtensible=Object.isExtensible||isObject,id=0,ID=safe("id"),WEAK=safe("weak"),LEAK=safe("leak"),method=require("./$.array-methods"),find=method(5),findIndex=method(6);function findFrozen(store,key){return find(store.array,function(it){return it[0]===key})}function leakStore(that){return that[LEAK]||hide(that,LEAK,{array:[],get:function(key){var entry=findFrozen(this,key);if(entry)return entry[1]},has:function(key){return!!findFrozen(this,key)},set:function(key,value){var entry=findFrozen(this,key);if(entry)entry[1]=value;else this.array.push([key,value])},"delete":function(key){var index=findIndex(this.array,function(it){return it[0]===key});if(~index)this.array.splice(index,1);return!!~index}})[LEAK]}module.exports={getConstructor:function(wrapper,NAME,IS_MAP,ADDER){var C=wrapper(function(that,iterable){$.set(assert.inst(that,C,NAME),ID,id++);if(iterable!=undefined)forOf(iterable,IS_MAP,that[ADDER],that)});require("./$.mix")(C.prototype,{"delete":function(key){if(!isObject(key))return false;if(!isExtensible(key))return leakStore(this)["delete"](key);return $has(key,WEAK)&&$has(key[WEAK],this[ID])&&delete key[WEAK][this[ID]]},has:function has(key){if(!isObject(key))return false;if(!isExtensible(key))return leakStore(this).has(key);return $has(key,WEAK)&&$has(key[WEAK],this[ID])}});return C},def:function(that,key,value){if(!isExtensible(assert.obj(key))){leakStore(that).set(key,value)}else{$has(key,WEAK)||hide(key,WEAK,{});key[WEAK][that[ID]]=value}return that},leakStore:leakStore,WEAK:WEAK,ID:ID}},{"./$":24,"./$.array-methods":4,"./$.assert":5,"./$.for-of":16,"./$.mix":26,"./$.uid":40}],11:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),BUGGY=require("./$.iter").BUGGY,forOf=require("./$.for-of"),species=require("./$.species"),assertInstance=require("./$.assert").inst;module.exports=function(NAME,wrapper,methods,common,IS_MAP,IS_WEAK){var Base=$.g[NAME],C=Base,ADDER=IS_MAP?"set":"add",proto=C&&C.prototype,O={};function fixMethod(KEY){var fn=proto[KEY];require("./$.redef")(proto,KEY,KEY=="delete"?function(a){return fn.call(this,a===0?0:a)}:KEY=="has"?function has(a){return fn.call(this,a===0?0:a)}:KEY=="get"?function get(a){return fn.call(this,a===0?0:a)}:KEY=="add"?function add(a){fn.call(this,a===0?0:a);return this}:function set(a,b){fn.call(this,a===0?0:a,b);return this})}if(!$.isFunction(C)||!(IS_WEAK||!BUGGY&&proto.forEach&&proto.entries)){C=common.getConstructor(wrapper,NAME,IS_MAP,ADDER);require("./$.mix")(C.prototype,methods)}else{var inst=new C,chain=inst[ADDER](IS_WEAK?{}:-0,1),buggyZero;if(!require("./$.iter-detect")(function(iter){new C(iter)})){C=wrapper(function(target,iterable){assertInstance(target,C,NAME);var that=new Base;if(iterable!=undefined)forOf(iterable,IS_MAP,that[ADDER],that);return that});C.prototype=proto;proto.constructor=C}IS_WEAK||inst.forEach(function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixMethod("delete");fixMethod("has");IS_MAP&&fixMethod("get")}if(buggyZero||chain!==inst)fixMethod(ADDER)}require("./$.cof").set(C,NAME);O[NAME]=C;$def($def.G+$def.W+$def.F*(C!=Base),O);species(C);species($.core[NAME]);if(!IS_WEAK)common.setIter(C,NAME,IS_MAP);return C}},{"./$":24,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.for-of":16,"./$.iter":23,"./$.iter-detect":22,"./$.mix":26,"./$.redef":29,"./$.species":34}],12:[function(require,module,exports){var assertFunction=require("./$.assert").fn;module.exports=function(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}},{"./$.assert":5}],13:[function(require,module,exports){var $=require("./$"),global=$.g,core=$.core,isFunction=$.isFunction,$redef=require("./$.redef");function ctx(fn,that){return function(){return fn.apply(that,arguments)}}global.core=core;$def.F=1;$def.G=2;$def.S=4;$def.P=8;$def.B=16;$def.W=32;function $def(type,name,source){var key,own,out,exp,isGlobal=type&$def.G,isProto=type&$def.P,target=isGlobal?global:type&$def.S?global[name]:(global[name]||{}).prototype,exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&$def.F)&&target&&key in target;out=(own?target:source)[key];if(type&$def.B&&own)exp=ctx(out,global);else exp=isProto&&isFunction(out)?ctx(Function.call,out):out;if(target&&!own)$redef(target,key,out);if(exports[key]!=out)$.hide(exports,key,exp);if(isProto)(exports.prototype||(exports.prototype={}))[key]=out}}module.exports=$def},{"./$":24,"./$.redef":29}],14:[function(require,module,exports){var $=require("./$"),document=$.g.document,isObject=$.isObject,is=isObject(document)&&isObject(document.createElement);module.exports=function(it){return is?document.createElement(it):{}}},{"./$":24}],15:[function(require,module,exports){var $=require("./$");module.exports=function(it){var keys=$.getKeys(it),getDesc=$.getDesc,getSymbols=$.getSymbols;if(getSymbols)$.each.call(getSymbols(it),function(key){if(getDesc(it,key).enumerable)keys.push(key)});return keys}},{"./$":24}],16:[function(require,module,exports){var ctx=require("./$.ctx"),get=require("./$.iter").get,call=require("./$.iter-call");module.exports=function(iterable,entries,fn,that){var iterator=get(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done){if(call(iterator,f,step.value,entries)===false){return call.close(iterator)}}}},{"./$.ctx":12,"./$.iter":23,"./$.iter-call":20}],17:[function(require,module,exports){module.exports=function($){$.FW=true;$.path=$.g;return $}},{}],18:[function(require,module,exports){var $=require("./$"),toString={}.toString,getNames=$.getNames;var windowNames=typeof window=="object"&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];function getWindowNames(it){try{return getNames(it)}catch(e){return windowNames.slice()}}module.exports.get=function getOwnPropertyNames(it){if(windowNames&&toString.call(it)=="[object Window]")return getWindowNames(it);return getNames($.toObject(it))}},{"./$":24}],19:[function(require,module,exports){module.exports=function(fn,args,that){var un=that===undefined;switch(args.length){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}},{}],20:[function(require,module,exports){var assertObject=require("./$.assert").obj;function close(iterator){var ret=iterator["return"];if(ret!==undefined)assertObject(ret.call(iterator))}function call(iterator,fn,value,entries){try{return entries?fn(assertObject(value)[0],value[1]):fn(value)}catch(e){close(iterator);throw e}}call.close=close;module.exports=call},{"./$.assert":5}],21:[function(require,module,exports){var $def=require("./$.def"),$redef=require("./$.redef"),$=require("./$"),cof=require("./$.cof"),$iter=require("./$.iter"),SYMBOL_ITERATOR=require("./$.wks")("iterator"),FF_ITERATOR="@@iterator",KEYS="keys",VALUES="values",Iterators=$iter.Iterators;module.exports=function(Base,NAME,Constructor,next,DEFAULT,IS_SET,FORCE){$iter.create(Constructor,NAME,next);function createMethod(kind){function $$(that){return new Constructor(that,kind)}switch(kind){case KEYS:return function keys(){return $$(this)};case VALUES:return function values(){return $$(this)}}return function entries(){return $$(this)}}var TAG=NAME+" Iterator",proto=Base.prototype,_native=proto[SYMBOL_ITERATOR]||proto[FF_ITERATOR]||DEFAULT&&proto[DEFAULT],_default=_native||createMethod(DEFAULT),methods,key;if(_native){var IteratorPrototype=$.getProto(_default.call(new Base));cof.set(IteratorPrototype,TAG,true);if($.FW&&$.has(proto,FF_ITERATOR))$iter.set(IteratorPrototype,$.that)}if($.FW||FORCE)$iter.set(proto,_default);Iterators[NAME]=_default;Iterators[TAG]=$.that;if(DEFAULT){methods={keys:IS_SET?_default:createMethod(KEYS),values:DEFAULT==VALUES?_default:createMethod(VALUES),entries:DEFAULT!=VALUES?_default:createMethod("entries")};if(FORCE)for(key in methods){if(!(key in proto))$redef(proto,key,methods[key])}else $def($def.P+$def.F*$iter.BUGGY,NAME,methods)}}},{"./$":24,"./$.cof":7,"./$.def":13,"./$.iter":23,"./$.redef":29,"./$.wks":42}],22:[function(require,module,exports){var SYMBOL_ITERATOR=require("./$.wks")("iterator"),SAFE_CLOSING=false;try{var riter=[7][SYMBOL_ITERATOR]();riter["return"]=function(){SAFE_CLOSING=true};Array.from(riter,function(){throw 2})}catch(e){}module.exports=function(exec){if(!SAFE_CLOSING)return false;var safe=false;try{var arr=[7],iter=arr[SYMBOL_ITERATOR]();iter.next=function(){safe=true};arr[SYMBOL_ITERATOR]=function(){return iter};exec(arr)}catch(e){}return safe}},{"./$.wks":42}],23:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),classof=cof.classof,assert=require("./$.assert"),assertObject=assert.obj,SYMBOL_ITERATOR=require("./$.wks")("iterator"),FF_ITERATOR="@@iterator",Iterators=require("./$.shared")("iterators"),IteratorPrototype={};setIterator(IteratorPrototype,$.that);function setIterator(O,value){$.hide(O,SYMBOL_ITERATOR,value);if(FF_ITERATOR in[])$.hide(O,FF_ITERATOR,value)}module.exports={BUGGY:"keys"in[]&&!("next"in[].keys()),Iterators:Iterators,step:function(done,value){return{value:value,done:!!done}},is:function(it){var O=Object(it),Symbol=$.g.Symbol;return(Symbol&&Symbol.iterator||FF_ITERATOR)in O||SYMBOL_ITERATOR in O||$.has(Iterators,classof(O))},get:function(it){var Symbol=$.g.Symbol,getIter;if(it!=undefined){getIter=it[Symbol&&Symbol.iterator||FF_ITERATOR]||it[SYMBOL_ITERATOR]||Iterators[classof(it)]}assert($.isFunction(getIter),it," is not iterable!");return assertObject(getIter.call(it))},set:setIterator,create:function(Constructor,NAME,next,proto){Constructor.prototype=$.create(proto||IteratorPrototype,{next:$.desc(1,next)});cof.set(Constructor,NAME+" Iterator")}}},{"./$":24,"./$.assert":5,"./$.cof":7,"./$.shared":33,"./$.wks":42}],24:[function(require,module,exports){"use strict";var global=typeof self!="undefined"?self:Function("return this")(),core={},defineProperty=Object.defineProperty,hasOwnProperty={}.hasOwnProperty,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min;var DESC=!!function(){try{return defineProperty({},"a",{get:function(){return 2}}).a==2}catch(e){}}();var hide=createDefiner(1);function toInteger(it){return isNaN(it=+it)?0:(it>0?floor:ceil)(it)}function desc(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return $.setDesc(object,key,desc(bitmap,value))}:simpleSet}function isObject(it){return it!==null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}function assertDefined(it){if(it==undefined)throw TypeError("Can't call method on "+it);return it}var $=module.exports=require("./$.fw")({g:global,core:core,html:global.document&&document.documentElement,isObject:isObject,isFunction:isFunction,that:function(){return this},toInteger:toInteger,toLength:function(it){return it>0?min(toInteger(it),9007199254740991):0},toIndex:function(index,length){index=toInteger(index);return index<0?max(index+length,0):min(index,length)},has:function(it,key){return hasOwnProperty.call(it,key)},create:Object.create,getProto:Object.getPrototypeOf,DESC:DESC,desc:desc,getDesc:Object.getOwnPropertyDescriptor,setDesc:defineProperty,setDescs:Object.defineProperties,getKeys:Object.keys,getNames:Object.getOwnPropertyNames,getSymbols:Object.getOwnPropertySymbols,assertDefined:assertDefined,ES5Object:Object,toObject:function(it){return $.ES5Object(assertDefined(it))},hide:hide,def:createDefiner(0),set:global.Symbol?simpleSet:hide,each:[].forEach});if(typeof __e!="undefined")__e=core;if(typeof __g!="undefined")__g=global},{"./$.fw":17}],25:[function(require,module,exports){var $=require("./$");module.exports=function(object,el){var O=$.toObject(object),keys=$.getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}},{"./$":24}],26:[function(require,module,exports){var $redef=require("./$.redef");module.exports=function(target,src){for(var key in src)$redef(target,key,src[key]);return target}},{"./$.redef":29}],27:[function(require,module,exports){var $=require("./$"),assertObject=require("./$.assert").obj;module.exports=function ownKeys(it){assertObject(it);var keys=$.getNames(it),getSymbols=$.getSymbols;return getSymbols?keys.concat(getSymbols(it)):keys}},{"./$":24,"./$.assert":5}],28:[function(require,module,exports){"use strict";var $=require("./$"),invoke=require("./$.invoke"),assertFunction=require("./$.assert").fn;module.exports=function(){var fn=assertFunction(this),length=arguments.length,pargs=Array(length),i=0,_=$.path._,holder=false;while(length>i)if((pargs[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,j=0,k=0,args;if(!holder&&!_length)return invoke(fn,pargs,that);args=pargs.slice();if(holder)for(;length>j;j++)if(args[j]===_)args[j]=arguments[k++];while(_length>k)args.push(arguments[k++]);return invoke(fn,args,that)}}},{"./$":24,"./$.assert":5,"./$.invoke":19}],29:[function(require,module,exports){var $=require("./$"),tpl=String({}.hasOwnProperty),SRC=require("./$.uid").safe("src"),_toString=Function.toString;function $redef(O,key,val,safe){if($.isFunction(val)){var base=O[key];$.hide(val,SRC,base?String(base):tpl.replace(/hasOwnProperty/,String(key)));if(!("name"in val))val.name=key}if(O===$.g){O[key]=val}else{if(!safe)delete O[key];$.hide(O,key,val)}}$redef(Function.prototype,"toString",function toString(){return $.has(this,SRC)?this[SRC]:_toString.call(this)});$.core.inspectSource=function(it){return _toString.call(it)};module.exports=$redef},{"./$":24,"./$.uid":40}],30:[function(require,module,exports){"use strict";module.exports=function(regExp,replace,isStatic){var replacer=replace===Object(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}},{}],31:[function(require,module,exports){module.exports=Object.is||function is(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}},{}],32:[function(require,module,exports){var $=require("./$"),assert=require("./$.assert");function check(O,proto){assert.obj(O);assert(proto===null||$.isObject(proto),proto,": can't set as prototype!")}module.exports={set:Object.setPrototypeOf||("__proto__"in{}?function(buggy,set){try{set=require("./$.ctx")(Function.call,$.getDesc(Object.prototype,"__proto__").set,2);set({},[])}catch(e){buggy=true}return function setPrototypeOf(O,proto){check(O,proto);if(buggy)O.__proto__=proto;else set(O,proto);return O}}():undefined),check:check}},{"./$":24,"./$.assert":5,"./$.ctx":12}],33:[function(require,module,exports){var $=require("./$"),SHARED="__core-js_shared__",store=$.g[SHARED]||($.g[SHARED]={});module.exports=function(key){return store[key]||(store[key]={})}},{"./$":24}],34:[function(require,module,exports){var $=require("./$"),SPECIES=require("./$.wks")("species");module.exports=function(C){if($.DESC&&!(SPECIES in C))$.setDesc(C,SPECIES,{configurable:true,get:$.that})}},{"./$":24,"./$.wks":42}],35:[function(require,module,exports){var $=require("./$");module.exports=function(TO_STRING){return function(that,pos){var s=String($.assertDefined(that)),i=$.toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return TO_STRING?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?TO_STRING?s.charAt(i):a:TO_STRING?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}},{"./$":24}],36:[function(require,module,exports){var $=require("./$"),repeat=require("./$.string-repeat");module.exports=function(that,minLength,fillChar,left){var S=String($.assertDefined(that));if(minLength===undefined)return S;var intMinLength=$.toInteger(minLength);var fillLen=intMinLength-S.length;if(fillLen<0||fillLen===Infinity){throw new RangeError("Cannot satisfy string length "+minLength+" for string: "+S)}var sFillStr=fillChar===undefined?" ":String(fillChar);var sFillVal=repeat.call(sFillStr,Math.ceil(fillLen/sFillStr.length));if(sFillVal.length>fillLen)sFillVal=left?sFillVal.slice(sFillVal.length-fillLen):sFillVal.slice(0,fillLen);return left?sFillVal.concat(S):S.concat(sFillVal)}},{"./$":24,"./$.string-repeat":37}],37:[function(require,module,exports){"use strict";var $=require("./$");module.exports=function repeat(count){var str=String($.assertDefined(this)),res="",n=$.toInteger(count);if(n<0||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res}},{"./$":24}],38:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),invoke=require("./$.invoke"),cel=require("./$.dom-create"),global=$.g,isFunction=$.isFunction,html=$.html,process=global.process,setTask=global.setImmediate,clearTask=global.clearImmediate,MessageChannel=global.MessageChannel,counter=0,queue={},ONREADYSTATECHANGE="onreadystatechange",defer,channel,port;function run(){var id=+this;if($.has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run.call(event.data)}if(!isFunction(setTask)||!isFunction(clearTask)){setTask=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearTask=function(id){delete queue[id]};if(cof(process)=="process"){defer=function(id){process.nextTick(ctx(run,id,1))}}else if(global.addEventListener&&isFunction(global.postMessage)&&!global.importScripts){defer=function(id){global.postMessage(id,"*")};global.addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(ONREADYSTATECHANGE in cel("script")){defer=function(id){html.appendChild(cel("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run.call(id)}}}else{defer=function(id){setTimeout(ctx(run,id,1),0)}}}module.exports={set:setTask,clear:clearTask}},{"./$":24,"./$.cof":7,"./$.ctx":12,"./$.dom-create":14,"./$.invoke":19}],39:[function(require,module,exports){module.exports=function(exec){try{exec();return false}catch(e){return true}}},{}],40:[function(require,module,exports){var sid=0;function uid(key){return"Symbol(".concat(key===undefined?"":key,")_",(++sid+Math.random()).toString(36))}uid.safe=require("./$").g.Symbol||uid;module.exports=uid},{"./$":24}],41:[function(require,module,exports){var UNSCOPABLES=require("./$.wks")("unscopables");if(!(UNSCOPABLES in[]))require("./$").hide(Array.prototype,UNSCOPABLES,{});module.exports=function(key){[][UNSCOPABLES][key]=true}},{"./$":24,"./$.wks":42}],42:[function(require,module,exports){var global=require("./$").g,store=require("./$.shared")("wks");module.exports=function(name){return store[name]||(store[name]=global.Symbol&&global.Symbol[name]||require("./$.uid").safe("Symbol."+name))}},{"./$":24,"./$.shared":33,"./$.uid":40}],43:[function(require,module,exports){var $=require("./$"),cel=require("./$.dom-create"),cof=require("./$.cof"),$def=require("./$.def"),invoke=require("./$.invoke"),arrayMethod=require("./$.array-methods"),IE_PROTO=require("./$.uid").safe("__proto__"),assert=require("./$.assert"),assertObject=assert.obj,ObjectProto=Object.prototype,html=$.html,A=[],_slice=A.slice,_join=A.join,classof=cof.classof,has=$.has,defineProperty=$.setDesc,getOwnDescriptor=$.getDesc,defineProperties=$.setDescs,isFunction=$.isFunction,isObject=$.isObject,toObject=$.toObject,toLength=$.toLength,toIndex=$.toIndex,IE8_DOM_DEFINE=false,$indexOf=require("./$.array-includes")(false),$forEach=arrayMethod(0),$map=arrayMethod(1),$filter=arrayMethod(2),$some=arrayMethod(3),$every=arrayMethod(4);if(!$.DESC){try{IE8_DOM_DEFINE=defineProperty(cel("div"),"x",{get:function(){return 8}}).x==8}catch(e){}$.setDesc=function(O,P,Attributes){if(IE8_DOM_DEFINE)try{return defineProperty(O,P,Attributes)}catch(e){}if("get"in Attributes||"set"in Attributes)throw TypeError("Accessors not supported!");if("value"in Attributes)assertObject(O)[P]=Attributes.value;return O};$.getDesc=function(O,P){if(IE8_DOM_DEFINE)try{return getOwnDescriptor(O,P)}catch(e){}if(has(O,P))return $.desc(!ObjectProto.propertyIsEnumerable.call(O,P),O[P])};$.setDescs=defineProperties=function(O,Properties){assertObject(O);var keys=$.getKeys(Properties),length=keys.length,i=0,P;while(length>i)$.setDesc(O,P=keys[i++],Properties[P]);return O}}$def($def.S+$def.F*!$.DESC,"Object",{getOwnPropertyDescriptor:$.getDesc,defineProperty:$.setDesc,defineProperties:defineProperties});var keys1=("constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,"+"toLocaleString,toString,valueOf").split(","),keys2=keys1.concat("length","prototype"),keysLen1=keys1.length;var createDict=function(){var iframe=cel("iframe"),i=keysLen1,gt=">",iframeDocument;iframe.style.display="none";html.appendChild(iframe);iframe.src="javascript:";iframeDocument=iframe.contentWindow.document;iframeDocument.open();iframeDocument.write("<script>document.F=Object</script"+gt);iframeDocument.close();createDict=iframeDocument.F;while(i--)delete createDict.prototype[keys1[i]];return createDict()};function createGetKeys(names,length){return function(object){var O=toObject(object),i=0,result=[],key;for(key in O)if(key!=IE_PROTO)has(O,key)&&result.push(key);while(length>i)if(has(O,key=names[i++])){~$indexOf(result,key)||result.push(key)}return result}}function Empty(){}$def($def.S,"Object",{getPrototypeOf:$.getProto=$.getProto||function(O){O=Object(assert.def(O));if(has(O,IE_PROTO))return O[IE_PROTO];if(isFunction(O.constructor)&&O instanceof O.constructor){return O.constructor.prototype}return O instanceof Object?ObjectProto:null},getOwnPropertyNames:$.getNames=$.getNames||createGetKeys(keys2,keys2.length,true),create:$.create=$.create||function(O,Properties){var result;if(O!==null){Empty.prototype=assertObject(O);result=new Empty;Empty.prototype=null;result[IE_PROTO]=O}else result=createDict();return Properties===undefined?result:defineProperties(result,Properties)},keys:$.getKeys=$.getKeys||createGetKeys(keys1,keysLen1,false),seal:function seal(it){return it},freeze:function freeze(it){return it},preventExtensions:function preventExtensions(it){return it},isSealed:function isSealed(it){return!isObject(it)},isFrozen:function isFrozen(it){return!isObject(it)},isExtensible:function isExtensible(it){return isObject(it)}});$def($def.P,"Function",{bind:function(that){var fn=assert.fn(this),partArgs=_slice.call(arguments,1);function bound(){var args=partArgs.concat(_slice.call(arguments)),constr=this instanceof bound,ctx=constr?$.create(fn.prototype):that,result=invoke(fn,args,ctx);return constr?ctx:result}if(fn.prototype)bound.prototype=fn.prototype;return bound}});if(!(0 in Object("z")&&"z"[0]=="z")){$.ES5Object=function(it){return cof(it)=="String"?it.split(""):Object(it)}}var buggySlice=true;try{if(html)_slice.call(html);buggySlice=false}catch(e){}$def($def.P+$def.F*buggySlice,"Array",{slice:function slice(begin,end){var len=toLength(this.length),klass=cof(this);end=end===undefined?len:end;if(klass=="Array")return _slice.call(this,begin,end);var start=toIndex(begin,len),upTo=toIndex(end,len),size=toLength(upTo-start),cloned=Array(size),i=0;for(;i<size;i++)cloned[i]=klass=="String"?this.charAt(start+i):this[start+i];return cloned}});$def($def.P+$def.F*($.ES5Object!=Object),"Array",{join:function join(){return _join.apply($.ES5Object(this),arguments)}});$def($def.S,"Array",{isArray:function(arg){return cof(arg)=="Array"}});function createArrayReduce(isRight){return function(callbackfn,memo){assert.fn(callbackfn);var O=toObject(this),length=toLength(O.length),index=isRight?length-1:0,i=isRight?-1:1; if(arguments.length<2)for(;;){if(index in O){memo=O[index];index+=i;break}index+=i;assert(isRight?index>=0:length>index,"Reduce of empty array with no initial value")}for(;isRight?index>=0:length>index;index+=i)if(index in O){memo=callbackfn(memo,O[index],index,this)}return memo}}$def($def.P,"Array",{forEach:$.each=$.each||function forEach(callbackfn){return $forEach(this,callbackfn,arguments[1])},map:function map(callbackfn){return $map(this,callbackfn,arguments[1])},filter:function filter(callbackfn){return $filter(this,callbackfn,arguments[1])},some:function some(callbackfn){return $some(this,callbackfn,arguments[1])},every:function every(callbackfn){return $every(this,callbackfn,arguments[1])},reduce:createArrayReduce(false),reduceRight:createArrayReduce(true),indexOf:function indexOf(el){return $indexOf(this,el,arguments[1])},lastIndexOf:function(el,fromIndex){var O=toObject(this),length=toLength(O.length),index=length-1;if(arguments.length>1)index=Math.min(index,$.toInteger(fromIndex));if(index<0)index=toLength(length+index);for(;index>=0;index--)if(index in O)if(O[index]===el)return index;return-1}});$def($def.P,"String",{trim:require("./$.replacer")(/^\s*([\s\S]*\S)?\s*$/,"$1")});$def($def.S,"Date",{now:function(){return+new Date}});function lz(num){return num>9?num:"0"+num}var date=new Date(-5e13-1),brokenDate=!(date.toISOString&&date.toISOString()=="0385-07-25T07:06:39.999Z"&&require("./$.throws")(function(){new Date(NaN).toISOString()}));$def($def.P+$def.F*brokenDate,"Date",{toISOString:function(){if(!isFinite(this))throw RangeError("Invalid time value");var d=this,y=d.getUTCFullYear(),m=d.getUTCMilliseconds(),s=y<0?"-":y>9999?"+":"";return s+("00000"+Math.abs(y)).slice(s?-6:-4)+"-"+lz(d.getUTCMonth()+1)+"-"+lz(d.getUTCDate())+"T"+lz(d.getUTCHours())+":"+lz(d.getUTCMinutes())+":"+lz(d.getUTCSeconds())+"."+(m>99?m:"0"+lz(m))+"Z"}});if(classof(function(){return arguments}())=="Object")cof.classof=function(it){var tag=classof(it);return tag=="Object"&&isFunction(it.callee)?"Arguments":tag}},{"./$":24,"./$.array-includes":3,"./$.array-methods":4,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.dom-create":14,"./$.invoke":19,"./$.replacer":30,"./$.throws":39,"./$.uid":40}],44:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),toIndex=$.toIndex;$def($def.P,"Array",{copyWithin:function copyWithin(target,start){var O=Object($.assertDefined(this)),len=$.toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=Math.min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O}});require("./$.unscope")("copyWithin")},{"./$":24,"./$.def":13,"./$.unscope":41}],45:[function(require,module,exports){"use strict";var $=require("./$"),$def=require("./$.def"),toIndex=$.toIndex;$def($def.P,"Array",{fill:function fill(value){var O=Object($.assertDefined(this)),length=$.toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O}});require("./$.unscope")("fill")},{"./$":24,"./$.def":13,"./$.unscope":41}],46:[function(require,module,exports){"use strict";var KEY="findIndex",$def=require("./$.def"),forced=true,$find=require("./$.array-methods")(6);if(KEY in[])Array(1)[KEY](function(){forced=false});$def($def.P+$def.F*forced,"Array",{findIndex:function findIndex(callbackfn){return $find(this,callbackfn,arguments[1])}});require("./$.unscope")(KEY)},{"./$.array-methods":4,"./$.def":13,"./$.unscope":41}],47:[function(require,module,exports){"use strict";var KEY="find",$def=require("./$.def"),forced=true,$find=require("./$.array-methods")(5);if(KEY in[])Array(1)[KEY](function(){forced=false});$def($def.P+$def.F*forced,"Array",{find:function find(callbackfn){return $find(this,callbackfn,arguments[1])}});require("./$.unscope")(KEY)},{"./$.array-methods":4,"./$.def":13,"./$.unscope":41}],48:[function(require,module,exports){var $=require("./$"),ctx=require("./$.ctx"),$def=require("./$.def"),$iter=require("./$.iter"),call=require("./$.iter-call");$def($def.S+$def.F*!require("./$.iter-detect")(function(iter){Array.from(iter)}),"Array",{from:function from(arrayLike){var O=Object($.assertDefined(arrayLike)),mapfn=arguments[1],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,arguments[2],2):undefined,index=0,length,result,step,iterator;if($iter.is(O)){iterator=$iter.get(O);result=new(typeof this=="function"?this:Array);for(;!(step=iterator.next()).done;index++){result[index]=mapping?call(iterator,f,[step.value,index],true):step.value}}else{result=new(typeof this=="function"?this:Array)(length=$.toLength(O.length));for(;length>index;index++){result[index]=mapping?f(O[index],index):O[index]}}result.length=index;return result}})},{"./$":24,"./$.ctx":12,"./$.def":13,"./$.iter":23,"./$.iter-call":20,"./$.iter-detect":22}],49:[function(require,module,exports){var $=require("./$"),setUnscope=require("./$.unscope"),ITER=require("./$.uid").safe("iter"),$iter=require("./$.iter"),step=$iter.step,Iterators=$iter.Iterators;require("./$.iter-define")(Array,"Array",function(iterated,kind){$.set(this,ITER,{o:$.toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length){iter.o=undefined;return step(1)}if(kind=="keys")return step(0,index);if(kind=="values")return step(0,O[index]);return step(0,[index,O[index]])},"values");Iterators.Arguments=Iterators.Array;setUnscope("keys");setUnscope("values");setUnscope("entries")},{"./$":24,"./$.iter":23,"./$.iter-define":21,"./$.uid":40,"./$.unscope":41}],50:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Array",{of:function of(){var index=0,length=arguments.length,result=new(typeof this=="function"?this:Array)(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}})},{"./$.def":13}],51:[function(require,module,exports){require("./$.species")(Array)},{"./$.species":34}],52:[function(require,module,exports){var $=require("./$"),HAS_INSTANCE=require("./$.wks")("hasInstance"),FunctionProto=Function.prototype;if(!(HAS_INSTANCE in FunctionProto))$.setDesc(FunctionProto,HAS_INSTANCE,{value:function(O){if(!$.isFunction(this)||!$.isObject(O))return false;if(!$.isObject(this.prototype))return O instanceof this;while(O=$.getProto(O))if(this.prototype===O)return true;return false}})},{"./$":24,"./$.wks":42}],53:[function(require,module,exports){"use strict";var $=require("./$"),NAME="name",setDesc=$.setDesc,FunctionProto=Function.prototype;NAME in FunctionProto||$.FW&&$.DESC&&setDesc(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";$.has(this,NAME)||setDesc(this,NAME,$.desc(5,name));return name},set:function(value){$.has(this,NAME)||setDesc(this,NAME,$.desc(0,value))}})},{"./$":24}],54:[function(require,module,exports){"use strict";var strong=require("./$.collection-strong");require("./$.collection")("Map",function(get){return function Map(){return get(this,arguments[0])}},{get:function get(key){var entry=strong.getEntry(this,key);return entry&&entry.v},set:function set(key,value){return strong.def(this,key===0?0:key,value)}},strong,true)},{"./$.collection":11,"./$.collection-strong":8}],55:[function(require,module,exports){var Infinity=1/0,$def=require("./$.def"),E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,ceil=Math.ceil,floor=Math.floor,EPSILON=pow(2,-52),EPSILON32=pow(2,-23),MAX32=pow(2,127)*(2-EPSILON32),MIN32=pow(2,-126);function roundTiesToEven(n){return n+1/EPSILON-1/EPSILON}function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1}function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$def($def.S,"Math",{acosh:function acosh(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function atanh(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function cbrt(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function clz32(x){return(x>>>=0)?31-floor(log(x+.5)*Math.LOG2E):32},cosh:function cosh(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function fround(x){var $abs=abs(x),$sign=sign(x),a,result;if($abs<MIN32)return $sign*roundTiesToEven($abs/MIN32/EPSILON32)*MIN32*EPSILON32;a=(1+EPSILON32/EPSILON)*$abs;result=a-(a-$abs);if(result>MAX32||result!=result)return $sign*Infinity;return $sign*result},hypot:function hypot(value1,value2){var sum=0,i=0,len=arguments.length,larg=0,arg,div;while(i<len){arg=abs(arguments[i++]);if(larg<arg){div=larg/arg;sum=sum*div*div+1;larg=arg}else if(arg>0){div=arg/larg;sum+=div*div}else sum+=arg}return larg===Infinity?Infinity:larg*sqrt(sum)},imul:function imul(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function log1p(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function log10(x){return log(x)/Math.LN10},log2:function log2(x){return log(x)/Math.LN2},sign:sign,sinh:function sinh(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function tanh(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:function trunc(it){return(it>0?floor:ceil)(it)}})},{"./$.def":13}],56:[function(require,module,exports){"use strict";var $=require("./$"),isObject=$.isObject,isFunction=$.isFunction,NUMBER="Number",$Number=$.g[NUMBER],Base=$Number,proto=$Number.prototype;function toPrimitive(it){var fn,val;if(isFunction(fn=it.valueOf)&&!isObject(val=fn.call(it)))return val;if(isFunction(fn=it.toString)&&!isObject(val=fn.call(it)))return val;throw TypeError("Can't convert object to number")}function toNumber(it){if(isObject(it))it=toPrimitive(it);if(typeof it=="string"&&it.length>2&&it.charCodeAt(0)==48){var binary=false;switch(it.charCodeAt(1)){case 66:case 98:binary=true;case 79:case 111:return parseInt(it.slice(2),binary?2:8)}}return+it}if($.FW&&!($Number("0o1")&&$Number("0b1"))){$Number=function Number(it){return this instanceof $Number?new Base(toNumber(it)):toNumber(it)};$.each.call($.DESC?$.getNames(Base):("MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,"+"EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,"+"MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger").split(","),function(key){if($.has(Base,key)&&!$.has($Number,key)){$.setDesc($Number,key,$.getDesc(Base,key))}});$Number.prototype=proto;proto.constructor=$Number;require("./$.redef")($.g,NUMBER,$Number)}},{"./$":24,"./$.redef":29}],57:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),abs=Math.abs,floor=Math.floor,_isFinite=$.g.isFinite,MAX_SAFE_INTEGER=9007199254740991;function isInteger(it){return!$.isObject(it)&&_isFinite(it)&&floor(it)===it}$def($def.S,"Number",{EPSILON:Math.pow(2,-52),isFinite:function isFinite(it){return typeof it=="number"&&_isFinite(it)},isInteger:isInteger,isNaN:function isNaN(number){return number!=number},isSafeInteger:function isSafeInteger(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt})},{"./$":24,"./$.def":13}],58:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{assign:require("./$.assign")})},{"./$.assign":6,"./$.def":13}],59:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{is:require("./$.same")})},{"./$.def":13,"./$.same":31}],60:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"Object",{setPrototypeOf:require("./$.set-proto").set})},{"./$.def":13,"./$.set-proto":32}],61:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),isObject=$.isObject,toObject=$.toObject;$.each.call(("freeze,seal,preventExtensions,isFrozen,isSealed,isExtensible,"+"getOwnPropertyDescriptor,getPrototypeOf,keys,getOwnPropertyNames").split(","),function(KEY,ID){var fn=($.core.Object||{})[KEY]||Object[KEY],forced=0,method={};method[KEY]=ID==0?function freeze(it){return isObject(it)?fn(it):it}:ID==1?function seal(it){return isObject(it)?fn(it):it}:ID==2?function preventExtensions(it){return isObject(it)?fn(it):it}:ID==3?function isFrozen(it){return isObject(it)?fn(it):true}:ID==4?function isSealed(it){return isObject(it)?fn(it):true}:ID==5?function isExtensible(it){return isObject(it)?fn(it):false}:ID==6?function getOwnPropertyDescriptor(it,key){return fn(toObject(it),key)}:ID==7?function getPrototypeOf(it){return fn(Object($.assertDefined(it)))}:ID==8?function keys(it){return fn(toObject(it))}:require("./$.get-names").get;try{fn("z")}catch(e){forced=1}$def($def.S+$def.F*forced,"Object",method)})},{"./$":24,"./$.def":13,"./$.get-names":18}],62:[function(require,module,exports){"use strict";var cof=require("./$.cof"),tmp={};tmp[require("./$.wks")("toStringTag")]="z";if(require("./$").FW&&cof(tmp)!="z"){require("./$.redef")(Object.prototype,"toString",function toString(){return"[object "+cof.classof(this)+"]"},true)}},{"./$":24,"./$.cof":7,"./$.redef":29,"./$.wks":42}],63:[function(require,module,exports){"use strict";var $=require("./$"),ctx=require("./$.ctx"),cof=require("./$.cof"),$def=require("./$.def"),assert=require("./$.assert"),forOf=require("./$.for-of"),setProto=require("./$.set-proto").set,same=require("./$.same"),species=require("./$.species"),SPECIES=require("./$.wks")("species"),RECORD=require("./$.uid").safe("record"),PROMISE="Promise",global=$.g,process=global.process,isNode=cof(process)=="process",asap=process&&process.nextTick||require("./$.task").set,P=global[PROMISE],isFunction=$.isFunction,isObject=$.isObject,assertFunction=assert.fn,assertObject=assert.obj,Wrapper;function testResolve(sub){var test=new P(function(){});if(sub)test.constructor=Object;return P.resolve(test)===test}var useNative=function(){var works=false;function P2(x){var self=new P(x);setProto(self,P2.prototype);return self}try{works=isFunction(P)&&isFunction(P.resolve)&&testResolve();setProto(P2,P);P2.prototype=$.create(P.prototype,{constructor:{value:P2}});if(!(P2.resolve(5).then(function(){})instanceof P2)){works=false}if(works&&$.DESC){var thenableThenGotten=false;P.resolve($.setDesc({},"then",{get:function(){thenableThenGotten=true}}));works=thenableThenGotten}}catch(e){works=false}return works}();function isPromise(it){return isObject(it)&&(useNative?cof.classof(it)=="Promise":RECORD in it)}function sameConstructor(a,b){if(!$.FW&&a===P&&b===Wrapper)return true;return same(a,b)}function getConstructor(C){var S=assertObject(C)[SPECIES];return S!=undefined?S:C}function isThenable(it){var then;if(isObject(it))then=it.then;return isFunction(then)?then:false}function notify(record){var chain=record.c;if(chain.length)asap.call(global,function(){var value=record.v,ok=record.s==1,i=0;function run(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){if(!ok)record.h=true;ret=cb===true?value:cb(value);if(ret===react.P){react.rej(TypeError("Promise-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(value)}catch(err){react.rej(err)}}while(chain.length>i)run(chain[i++]);chain.length=0})}function isUnhandled(promise){var record=promise[RECORD],chain=record.a||record.c,i=0,react;if(record.h)return false;while(chain.length>i){react=chain[i++];if(react.fail||!isUnhandled(react.P))return false}return true}function $reject(value){var record=this,promise;if(record.d)return;record.d=true;record=record.r||record;record.v=value;record.s=2;record.a=record.c.slice();setTimeout(function(){asap.call(global,function(){if(isUnhandled(promise=record.p)){if(isNode){process.emit("unhandledRejection",value,promise)}else if(global.console&&console.error){console.error("Unhandled promise rejection",value)}}record.a=undefined})},1);notify(record)}function $resolve(value){var record=this,then;if(record.d)return;record.d=true;record=record.r||record;try{if(then=isThenable(value)){asap.call(global,function(){var wrapper={r:record,d:false};try{then.call(value,ctx($resolve,wrapper,1),ctx($reject,wrapper,1))}catch(e){$reject.call(wrapper,e)}})}else{record.v=value;record.s=1;notify(record)}}catch(e){$reject.call({r:record,d:false},e)}}if(!useNative){P=function Promise(executor){assertFunction(executor);var record={p:assert.inst(this,P,PROMISE),c:[],a:undefined,s:0,d:false,v:undefined,h:false};$.hide(this,RECORD,record);try{executor(ctx($resolve,record,1),ctx($reject,record,1))}catch(err){$reject.call(record,err)}};require("./$.mix")(P.prototype,{then:function then(onFulfilled,onRejected){var S=assertObject(assertObject(this).constructor)[SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false};var promise=react.P=new(S!=undefined?S:P)(function(res,rej){react.res=assertFunction(res);react.rej=assertFunction(rej)});var record=this[RECORD];record.c.push(react);if(record.a)record.a.push(react);if(record.s)notify(record);return promise},"catch":function(onRejected){return this.then(undefined,onRejected)}})}$def($def.G+$def.W+$def.F*!useNative,{Promise:P});cof.set(P,PROMISE);species(P);species(Wrapper=$.core[PROMISE]);$def($def.S+$def.F*!useNative,PROMISE,{reject:function reject(r){return new(getConstructor(this))(function(res,rej){rej(r)})}});$def($def.S+$def.F*(!useNative||testResolve(true)),PROMISE,{resolve:function resolve(x){return isPromise(x)&&sameConstructor(x.constructor,this)?x:new this(function(res){res(x)})}});$def($def.S+$def.F*!(useNative&&require("./$.iter-detect")(function(iter){P.all(iter)["catch"](function(){})})),PROMISE,{all:function all(iterable){var C=getConstructor(this),values=[];return new C(function(res,rej){forOf(iterable,false,values.push,values);var remaining=values.length,results=Array(remaining);if(remaining)$.each.call(values,function(promise,index){C.resolve(promise).then(function(value){results[index]=value;--remaining||res(results)},rej)});else res(results)})},race:function race(iterable){var C=getConstructor(this);return new C(function(res,rej){forOf(iterable,false,function(promise){C.resolve(promise).then(res,rej)})})}})},{"./$":24,"./$.assert":5,"./$.cof":7,"./$.ctx":12,"./$.def":13,"./$.for-of":16,"./$.iter-detect":22,"./$.mix":26,"./$.same":31,"./$.set-proto":32,"./$.species":34,"./$.task":38,"./$.uid":40,"./$.wks":42}],64:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),setProto=require("./$.set-proto"),$iter=require("./$.iter"),ITERATOR=require("./$.wks")("iterator"),ITER=require("./$.uid").safe("iter"),step=$iter.step,assert=require("./$.assert"),isObject=$.isObject,getProto=$.getProto,$Reflect=$.g.Reflect,_apply=Function.apply,assertObject=assert.obj,_isExtensible=Object.isExtensible||isObject,_preventExtensions=Object.preventExtensions,buggyEnumerate=!($Reflect&&$Reflect.enumerate&&ITERATOR in $Reflect.enumerate({}));function Enumerate(iterated){$.set(this,ITER,{o:iterated,k:undefined,i:0})}$iter.create(Enumerate,"Object",function(){var iter=this[ITER],keys=iter.k,key;if(keys==undefined){iter.k=keys=[];for(key in iter.o)keys.push(key)}do{if(iter.i>=keys.length)return step(1)}while(!((key=keys[iter.i++])in iter.o));return step(0,key)});var reflect={apply:function apply(target,thisArgument,argumentsList){return _apply.call(target,thisArgument,argumentsList)},construct:function construct(target,argumentsList){var proto=assert.fn(arguments.length<3?target:arguments[2]).prototype,instance=$.create(isObject(proto)?proto:Object.prototype),result=_apply.call(target,instance,argumentsList);return isObject(result)?result:instance},defineProperty:function defineProperty(target,propertyKey,attributes){assertObject(target);try{$.setDesc(target,propertyKey,attributes);return true}catch(e){return false}},deleteProperty:function deleteProperty(target,propertyKey){var desc=$.getDesc(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},get:function get(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=$.getDesc(assertObject(target),propertyKey),proto;if(desc)return $.has(desc,"value")?desc.value:desc.get===undefined?undefined:desc.get.call(receiver);return isObject(proto=getProto(target))?get(proto,propertyKey,receiver):undefined},getOwnPropertyDescriptor:function getOwnPropertyDescriptor(target,propertyKey){return $.getDesc(assertObject(target),propertyKey)},getPrototypeOf:function getPrototypeOf(target){return getProto(assertObject(target))},has:function has(target,propertyKey){return propertyKey in target},isExtensible:function isExtensible(target){return _isExtensible(assertObject(target))},ownKeys:require("./$.own-keys"),preventExtensions:function preventExtensions(target){assertObject(target);try{if(_preventExtensions)_preventExtensions(target);return true}catch(e){return false}},set:function set(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],ownDesc=$.getDesc(assertObject(target),propertyKey),existingDescriptor,proto;if(!ownDesc){if(isObject(proto=getProto(target))){return set(proto,propertyKey,V,receiver)}ownDesc=$.desc(0)}if($.has(ownDesc,"value")){if(ownDesc.writable===false||!isObject(receiver))return false;existingDescriptor=$.getDesc(receiver,propertyKey)||$.desc(0);existingDescriptor.value=V;$.setDesc(receiver,propertyKey,existingDescriptor);return true}return ownDesc.set===undefined?false:(ownDesc.set.call(receiver,V),true)}};if(setProto)reflect.setPrototypeOf=function setPrototypeOf(target,proto){setProto.check(target,proto);try{setProto.set(target,proto);return true}catch(e){return false}};$def($def.G,{Reflect:{}});$def($def.S+$def.F*buggyEnumerate,"Reflect",{enumerate:function enumerate(target){return new Enumerate(assertObject(target))}});$def($def.S,"Reflect",reflect)},{"./$":24,"./$.assert":5,"./$.def":13,"./$.iter":23,"./$.own-keys":27,"./$.set-proto":32,"./$.uid":40,"./$.wks":42}],65:[function(require,module,exports){var $=require("./$"),cof=require("./$.cof"),$RegExp=$.g.RegExp,Base=$RegExp,proto=$RegExp.prototype,re=/a/g,CORRECT_NEW=new $RegExp(re)!==re,ALLOWS_RE_WITH_FLAGS=function(){try{return $RegExp(re,"i")=="/a/i"}catch(e){}}();if($.FW&&$.DESC){if(!CORRECT_NEW||!ALLOWS_RE_WITH_FLAGS){$RegExp=function RegExp(pattern,flags){var patternIsRegExp=cof(pattern)=="RegExp",flagsIsUndefined=flags===undefined;if(!(this instanceof $RegExp)&&patternIsRegExp&&flagsIsUndefined)return pattern;return CORRECT_NEW?new Base(patternIsRegExp&&!flagsIsUndefined?pattern.source:pattern,flags):new Base(patternIsRegExp?pattern.source:pattern,patternIsRegExp&&flagsIsUndefined?pattern.flags:flags)};$.each.call($.getNames(Base),function(key){key in $RegExp||$.setDesc($RegExp,key,{configurable:true,get:function(){return Base[key]},set:function(it){Base[key]=it}})});proto.constructor=$RegExp;$RegExp.prototype=proto;require("./$.redef")($.g,"RegExp",$RegExp)}if(/./g.flags!="g")$.setDesc(proto,"flags",{configurable:true,get:require("./$.replacer")(/^.*\/(\w*)$/,"$1")})}require("./$.species")($RegExp)},{"./$":24,"./$.cof":7,"./$.redef":29,"./$.replacer":30,"./$.species":34}],66:[function(require,module,exports){"use strict";var strong=require("./$.collection-strong");require("./$.collection")("Set",function(get){return function Set(){return get(this,arguments[0])}},{add:function add(value){return strong.def(this,value=value===0?0:value,value)}},strong)},{"./$.collection":11,"./$.collection-strong":8}],67:[function(require,module,exports){"use strict";var $def=require("./$.def"),$at=require("./$.string-at")(false);$def($def.P,"String",{codePointAt:function codePointAt(pos){return $at(this,pos)}})},{"./$.def":13,"./$.string-at":35}],68:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def"),toLength=$.toLength;$def($def.P+$def.F*!require("./$.throws")(function(){"q".endsWith(/./)}),"String",{endsWith:function endsWith(searchString){if(cof(searchString)=="RegExp")throw TypeError();var that=String($.assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:Math.min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString}})},{"./$":24,"./$.cof":7,"./$.def":13,"./$.throws":39}],69:[function(require,module,exports){var $def=require("./$.def"),toIndex=require("./$").toIndex,fromCharCode=String.fromCharCode,$fromCodePoint=String.fromCodePoint;$def($def.S+$def.F*(!!$fromCodePoint&&$fromCodePoint.length!=1),"String",{fromCodePoint:function fromCodePoint(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fromCharCode(code):fromCharCode(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")}})},{"./$":24,"./$.def":13}],70:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def");$def($def.P,"String",{includes:function includes(searchString){if(cof(searchString)=="RegExp")throw TypeError();return!!~String($.assertDefined(this)).indexOf(searchString,arguments[1])}})},{"./$":24,"./$.cof":7,"./$.def":13}],71:[function(require,module,exports){var set=require("./$").set,$at=require("./$.string-at")(true),ITER=require("./$.uid").safe("iter"),$iter=require("./$.iter"),step=$iter.step;require("./$.iter-define")(String,"String",function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return step(1);point=$at(O,index);iter.i+=point.length;return step(0,point)})},{"./$":24,"./$.iter":23,"./$.iter-define":21,"./$.string-at":35,"./$.uid":40}],72:[function(require,module,exports){var $=require("./$"),$def=require("./$.def");$def($def.S,"String",{raw:function raw(callSite){var tpl=$.toObject(callSite.raw),len=$.toLength(tpl.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(tpl[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}})},{"./$":24,"./$.def":13}],73:[function(require,module,exports){var $def=require("./$.def");$def($def.P,"String",{repeat:require("./$.string-repeat")})},{"./$.def":13,"./$.string-repeat":37}],74:[function(require,module,exports){"use strict";var $=require("./$"),cof=require("./$.cof"),$def=require("./$.def");$def($def.P+$def.F*!require("./$.throws")(function(){"q".startsWith(/./)}),"String",{startsWith:function startsWith(searchString){if(cof(searchString)=="RegExp")throw TypeError();var that=String($.assertDefined(this)),index=$.toLength(Math.min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}})},{"./$":24,"./$.cof":7,"./$.def":13,"./$.throws":39}],75:[function(require,module,exports){"use strict";var $=require("./$"),setTag=require("./$.cof").set,uid=require("./$.uid"),shared=require("./$.shared"),$def=require("./$.def"),$redef=require("./$.redef"),keyOf=require("./$.keyof"),enumKeys=require("./$.enum-keys"),assertObject=require("./$.assert").obj,ObjectProto=Object.prototype,DESC=$.DESC,has=$.has,$create=$.create,getDesc=$.getDesc,setDesc=$.setDesc,desc=$.desc,$names=require("./$.get-names"),getNames=$names.get,toObject=$.toObject,$Symbol=$.g.Symbol,setter=false,TAG=uid("tag"),HIDDEN=uid("hidden"),_propertyIsEnumerable={}.propertyIsEnumerable,SymbolRegistry=shared("symbol-registry"),AllSymbols=shared("symbols"),useNative=$.isFunction($Symbol);var setSymbolDesc=DESC?function(){try{return $create(setDesc({},HIDDEN,{get:function(){return setDesc(this,HIDDEN,{value:false})[HIDDEN]}}))[HIDDEN]||setDesc}catch(e){return function(it,key,D){var protoDesc=getDesc(ObjectProto,key);if(protoDesc)delete ObjectProto[key];setDesc(it,key,D);if(protoDesc&&it!==ObjectProto)setDesc(ObjectProto,key,protoDesc)}}}():setDesc;function wrap(tag){var sym=AllSymbols[tag]=$.set($create($Symbol.prototype),TAG,tag);DESC&&setter&&setSymbolDesc(ObjectProto,tag,{configurable:true,set:function(value){if(has(this,HIDDEN)&&has(this[HIDDEN],tag))this[HIDDEN][tag]=false;setSymbolDesc(this,tag,desc(1,value))}});return sym}function defineProperty(it,key,D){if(D&&has(AllSymbols,key)){if(!D.enumerable){if(!has(it,HIDDEN))setDesc(it,HIDDEN,desc(1,{}));it[HIDDEN][key]=true}else{if(has(it,HIDDEN)&&it[HIDDEN][key])it[HIDDEN][key]=false;D=$create(D,{enumerable:desc(0,false)})}return setSymbolDesc(it,key,D)}return setDesc(it,key,D)}function defineProperties(it,P){assertObject(it);var keys=enumKeys(P=toObject(P)),i=0,l=keys.length,key;while(l>i)defineProperty(it,key=keys[i++],P[key]);return it}function create(it,P){return P===undefined?$create(it):defineProperties($create(it),P)}function propertyIsEnumerable(key){var E=_propertyIsEnumerable.call(this,key);return E||!has(this,key)||!has(AllSymbols,key)||has(this,HIDDEN)&&this[HIDDEN][key]?E:true}function getOwnPropertyDescriptor(it,key){var D=getDesc(it=toObject(it),key);if(D&&has(AllSymbols,key)&&!(has(it,HIDDEN)&&it[HIDDEN][key]))D.enumerable=true;return D}function getOwnPropertyNames(it){var names=getNames(toObject(it)),result=[],i=0,key;while(names.length>i)if(!has(AllSymbols,key=names[i++])&&key!=HIDDEN)result.push(key);return result}function getOwnPropertySymbols(it){var names=getNames(toObject(it)),result=[],i=0,key;while(names.length>i)if(has(AllSymbols,key=names[i++]))result.push(AllSymbols[key]);return result}if(!useNative){$Symbol=function Symbol(){if(this instanceof $Symbol)throw TypeError("Symbol is not a constructor");return wrap(uid(arguments[0]))};$redef($Symbol.prototype,"toString",function(){return this[TAG]});$.create=create;$.setDesc=defineProperty;$.getDesc=getOwnPropertyDescriptor;$.setDescs=defineProperties;$.getNames=$names.get=getOwnPropertyNames;$.getSymbols=getOwnPropertySymbols;if($.DESC&&$.FW)$redef(ObjectProto,"propertyIsEnumerable",propertyIsEnumerable,true)}var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=$Symbol(key)},keyFor:function keyFor(key){return keyOf(SymbolRegistry,key)},useSetter:function(){setter=true},useSimple:function(){setter=false}};$.each.call(("hasInstance,isConcatSpreadable,iterator,match,replace,search,"+"species,split,toPrimitive,toStringTag,unscopables").split(","),function(it){var sym=require("./$.wks")(it);symbolStatics[it]=useNative?sym:wrap(sym)});setter=true;$def($def.G+$def.W,{Symbol:$Symbol});$def($def.S,"Symbol",symbolStatics);$def($def.S+$def.F*!useNative,"Object",{create:create,defineProperty:defineProperty,defineProperties:defineProperties,getOwnPropertyDescriptor:getOwnPropertyDescriptor,getOwnPropertyNames:getOwnPropertyNames,getOwnPropertySymbols:getOwnPropertySymbols});setTag($Symbol,"Symbol");setTag(Math,"Math",true);setTag($.g.JSON,"JSON",true)},{"./$":24,"./$.assert":5,"./$.cof":7,"./$.def":13,"./$.enum-keys":15,"./$.get-names":18,"./$.keyof":25,"./$.redef":29,"./$.shared":33,"./$.uid":40,"./$.wks":42}],76:[function(require,module,exports){"use strict";var $=require("./$"),weak=require("./$.collection-weak"),leakStore=weak.leakStore,ID=weak.ID,WEAK=weak.WEAK,has=$.has,isObject=$.isObject,isExtensible=Object.isExtensible||isObject,tmp={};var $WeakMap=require("./$.collection")("WeakMap",function(get){return function WeakMap(){return get(this,arguments[0])}},{get:function get(key){if(isObject(key)){if(!isExtensible(key))return leakStore(this).get(key);if(has(key,WEAK))return key[WEAK][this[ID]]}},set:function set(key,value){return weak.def(this,key,value)}},weak,true,true);if((new $WeakMap).set((Object.freeze||Object)(tmp),7).get(tmp)!=7){$.each.call(["delete","has","get","set"],function(key){var proto=$WeakMap.prototype,method=proto[key];require("./$.redef")(proto,key,function(a,b){if(isObject(a)&&!isExtensible(a)){var result=leakStore(this)[key](a,b); return key=="set"?this:result}return method.call(this,a,b)})})}},{"./$":24,"./$.collection":11,"./$.collection-weak":10,"./$.redef":29}],77:[function(require,module,exports){"use strict";var weak=require("./$.collection-weak");require("./$.collection")("WeakSet",function(get){return function WeakSet(){return get(this,arguments[0])}},{add:function add(value){return weak.def(this,value,true)}},weak,false,true)},{"./$.collection":11,"./$.collection-weak":10}],78:[function(require,module,exports){"use strict";var $def=require("./$.def"),$includes=require("./$.array-includes")(true);$def($def.P,"Array",{includes:function includes(el){return $includes(this,el,arguments[1])}});require("./$.unscope")("includes")},{"./$.array-includes":3,"./$.def":13,"./$.unscope":41}],79:[function(require,module,exports){require("./$.collection-to-json")("Map")},{"./$.collection-to-json":9}],80:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),ownKeys=require("./$.own-keys");$def($def.S,"Object",{getOwnPropertyDescriptors:function getOwnPropertyDescriptors(object){var O=$.toObject(object),result={};$.each.call(ownKeys(O),function(key){$.setDesc(result,key,$.desc(0,$.getDesc(O,key)))});return result}})},{"./$":24,"./$.def":13,"./$.own-keys":27}],81:[function(require,module,exports){var $=require("./$"),$def=require("./$.def");function createObjectToArray(isEntries){return function(object){var O=$.toObject(object),keys=$.getKeys(O),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$def($def.S,"Object",{values:createObjectToArray(false),entries:createObjectToArray(true)})},{"./$":24,"./$.def":13}],82:[function(require,module,exports){var $def=require("./$.def");$def($def.S,"RegExp",{escape:require("./$.replacer")(/[\\^$*+?.()|[\]{}]/g,"\\$&",true)})},{"./$.def":13,"./$.replacer":30}],83:[function(require,module,exports){require("./$.collection-to-json")("Set")},{"./$.collection-to-json":9}],84:[function(require,module,exports){"use strict";var $def=require("./$.def"),$at=require("./$.string-at")(true);$def($def.P,"String",{at:function at(pos){return $at(this,pos)}})},{"./$.def":13,"./$.string-at":35}],85:[function(require,module,exports){"use strict";var $def=require("./$.def"),$pad=require("./$.string-pad");$def($def.P,"String",{lpad:function lpad(n){return $pad(this,n,arguments[1],true)}})},{"./$.def":13,"./$.string-pad":36}],86:[function(require,module,exports){"use strict";var $def=require("./$.def"),$pad=require("./$.string-pad");$def($def.P,"String",{rpad:function rpad(n){return $pad(this,n,arguments[1],false)}})},{"./$.def":13,"./$.string-pad":36}],87:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),$Array=$.core.Array||Array,statics={};function setStatics(keys,length){$.each.call(keys.split(","),function(key){if(length==undefined&&key in $Array)statics[key]=$Array[key];else if(key in[])statics[key]=require("./$.ctx")(Function.call,[][key],length)})}setStatics("pop,reverse,shift,keys,values,entries",1);setStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$def($def.S,"Array",statics)},{"./$":24,"./$.ctx":12,"./$.def":13}],88:[function(require,module,exports){require("./es6.array.iterator");var $=require("./$"),Iterators=require("./$.iter").Iterators,ITERATOR=require("./$.wks")("iterator"),ArrayValues=Iterators.Array,NL=$.g.NodeList,HTC=$.g.HTMLCollection,NLProto=NL&&NL.prototype,HTCProto=HTC&&HTC.prototype;if($.FW){if(NL&&!(ITERATOR in NLProto))$.hide(NLProto,ITERATOR,ArrayValues);if(HTC&&!(ITERATOR in HTCProto))$.hide(HTCProto,ITERATOR,ArrayValues)}Iterators.NodeList=Iterators.HTMLCollection=ArrayValues},{"./$":24,"./$.iter":23,"./$.wks":42,"./es6.array.iterator":49}],89:[function(require,module,exports){var $def=require("./$.def"),$task=require("./$.task");$def($def.G+$def.B,{setImmediate:$task.set,clearImmediate:$task.clear})},{"./$.def":13,"./$.task":38}],90:[function(require,module,exports){var $=require("./$"),$def=require("./$.def"),invoke=require("./$.invoke"),partial=require("./$.partial"),navigator=$.g.navigator,MSIE=!!navigator&&/MSIE .\./.test(navigator.userAgent);function wrap(set){return MSIE?function(fn,time){return set(invoke(partial,[].slice.call(arguments,2),$.isFunction(fn)?fn:Function(fn)),time)}:set}$def($def.G+$def.B+$def.F*MSIE,{setTimeout:wrap($.g.setTimeout),setInterval:wrap($.g.setInterval)})},{"./$":24,"./$.def":13,"./$.invoke":19,"./$.partial":28}],91:[function(require,module,exports){require("./modules/es5");require("./modules/es6.symbol");require("./modules/es6.object.assign");require("./modules/es6.object.is");require("./modules/es6.object.set-prototype-of");require("./modules/es6.object.to-string");require("./modules/es6.object.statics-accept-primitives");require("./modules/es6.function.name");require("./modules/es6.function.has-instance");require("./modules/es6.number.constructor");require("./modules/es6.number.statics");require("./modules/es6.math");require("./modules/es6.string.from-code-point");require("./modules/es6.string.raw");require("./modules/es6.string.iterator");require("./modules/es6.string.code-point-at");require("./modules/es6.string.ends-with");require("./modules/es6.string.includes");require("./modules/es6.string.repeat");require("./modules/es6.string.starts-with");require("./modules/es6.array.from");require("./modules/es6.array.of");require("./modules/es6.array.iterator");require("./modules/es6.array.species");require("./modules/es6.array.copy-within");require("./modules/es6.array.fill");require("./modules/es6.array.find");require("./modules/es6.array.find-index");require("./modules/es6.regexp");require("./modules/es6.promise");require("./modules/es6.map");require("./modules/es6.set");require("./modules/es6.weak-map");require("./modules/es6.weak-set");require("./modules/es6.reflect");require("./modules/es7.array.includes");require("./modules/es7.string.at");require("./modules/es7.string.lpad");require("./modules/es7.string.rpad");require("./modules/es7.regexp.escape");require("./modules/es7.object.get-own-property-descriptors");require("./modules/es7.object.to-array");require("./modules/es7.map.to-json");require("./modules/es7.set.to-json");require("./modules/js.array.statics");require("./modules/web.timers");require("./modules/web.immediate");require("./modules/web.dom.iterable");module.exports=require("./modules/$").core},{"./modules/$":24,"./modules/es5":43,"./modules/es6.array.copy-within":44,"./modules/es6.array.fill":45,"./modules/es6.array.find":47,"./modules/es6.array.find-index":46,"./modules/es6.array.from":48,"./modules/es6.array.iterator":49,"./modules/es6.array.of":50,"./modules/es6.array.species":51,"./modules/es6.function.has-instance":52,"./modules/es6.function.name":53,"./modules/es6.map":54,"./modules/es6.math":55,"./modules/es6.number.constructor":56,"./modules/es6.number.statics":57,"./modules/es6.object.assign":58,"./modules/es6.object.is":59,"./modules/es6.object.set-prototype-of":60,"./modules/es6.object.statics-accept-primitives":61,"./modules/es6.object.to-string":62,"./modules/es6.promise":63,"./modules/es6.reflect":64,"./modules/es6.regexp":65,"./modules/es6.set":66,"./modules/es6.string.code-point-at":67,"./modules/es6.string.ends-with":68,"./modules/es6.string.from-code-point":69,"./modules/es6.string.includes":70,"./modules/es6.string.iterator":71,"./modules/es6.string.raw":72,"./modules/es6.string.repeat":73,"./modules/es6.string.starts-with":74,"./modules/es6.symbol":75,"./modules/es6.weak-map":76,"./modules/es6.weak-set":77,"./modules/es7.array.includes":78,"./modules/es7.map.to-json":79,"./modules/es7.object.get-own-property-descriptors":80,"./modules/es7.object.to-array":81,"./modules/es7.regexp.escape":82,"./modules/es7.set.to-json":83,"./modules/es7.string.at":84,"./modules/es7.string.lpad":85,"./modules/es7.string.rpad":86,"./modules/js.array.statics":87,"./modules/web.dom.iterable":88,"./modules/web.immediate":89,"./modules/web.timers":90}],92:[function(require,module,exports){(function(process,global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryLocsList){var generator=Object.create((outerFn||Generator).prototype);generator._invoke=makeInvokeMethod(innerFn,self||null,new Context(tryLocsList||[]));return generator}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function Generator(){}function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";function defineIteratorMethods(prototype){["next","throw","return"].forEach(function(method){prototype[method]=function(arg){return this._invoke(method,arg)}})}runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.awrap=function(arg){return new AwaitArgument(arg)};function AwaitArgument(arg){this.arg=arg}function AsyncIterator(generator){function invoke(method,arg){var result=generator[method](arg);var value=result.value;return value instanceof AwaitArgument?Promise.resolve(value.arg).then(invokeNext,invokeThrow):Promise.resolve(value).then(function(unwrapped){result.value=unwrapped;return result})}if(typeof process==="object"&&process.domain){invoke=process.domain.bind(invoke)}var invokeNext=invoke.bind(generator,"next");var invokeThrow=invoke.bind(generator,"throw");var invokeReturn=invoke.bind(generator,"return");var previousPromise;function enqueue(method,arg){var enqueueResult=previousPromise?previousPromise.then(function(){return invoke(method,arg)}):new Promise(function(resolve){resolve(invoke(method,arg))});previousPromise=enqueueResult["catch"](function(ignored){});return enqueueResult}this._invoke=enqueue}defineIteratorMethods(AsyncIterator.prototype);runtime.async=function(innerFn,outerFn,self,tryLocsList){var iter=new AsyncIterator(wrap(innerFn,outerFn,self,tryLocsList));return runtime.isGeneratorFunction(outerFn)?iter:iter.next().then(function(result){return result.done?result.value:iter.next()})};function makeInvokeMethod(innerFn,self,context){var state=GenStateSuspendedStart;return function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){if(method==="throw"){throw arg}return doneResult()}while(true){var delegate=context.delegate;if(delegate){if(method==="return"||method==="throw"&&delegate.iterator[method]===undefined){context.delegate=null;var returnMethod=delegate.iterator["return"];if(returnMethod){var record=tryCatch(returnMethod,delegate.iterator,arg);if(record.type==="throw"){method="throw";arg=record.arg;continue}}if(method==="return"){continue}}var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedYield){context.sent=arg}else{context.sent=undefined}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;method="throw";arg=record.arg}}}}defineIteratorMethods(Gp);Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(locs){var entry={tryLoc:locs[0]};if(1 in locs){entry.catchLoc=locs[1]}if(2 in locs){entry.finallyLoc=locs[2];entry.afterLoc=locs[3]}this.tryEntries.push(entry)}function resetTryEntry(entry){var record=entry.completion||{};record.type="normal";delete record.arg;entry.completion=record}function Context(tryLocsList){this.tryEntries=[{tryLoc:"root"}];tryLocsList.forEach(pushTryEntry,this);this.reset(true)}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(skipTempReset){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);if(!skipTempReset){for(var name in this){if(name.charAt(0)==="t"&&hasOwn.call(this,name)&&!isNaN(+name.slice(1))){this[name]=undefined}}}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},abrupt:function(type,arg){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev<entry.finallyLoc){var finallyEntry=entry;break}}if(finallyEntry&&(type==="break"||type==="continue")&&finallyEntry.tryLoc<=arg&&arg<=finallyEntry.finallyLoc){finallyEntry=null}var record=finallyEntry?finallyEntry.completion:{};record.type=type;record.arg=arg;if(finallyEntry){this.next=finallyEntry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record,afterLoc){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}else if(record.type==="normal"&&afterLoc){this.next=afterLoc}},finish:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc){this.complete(entry.completion,entry.afterLoc);resetTryEntry(entry);return ContinueSentinel}}},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:typeof self==="object"?self:this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:1}]},{},[2]);
stories/Modal.stories.js
react-materialize/react-materialize
import React from 'react'; import { storiesOf } from '@storybook/react'; import Button from '../src/Button'; import Modal from '../src/Modal'; const stories = storiesOf('Javascript/Modal', module); stories.addParameters({ info: { text: `Use a modal for dialog boxes, confirmation messages, or other content that can be called up.` } }); stories.add('Default', () => ( <Modal header="Modal Header" trigger={<Button>MODAL</Button>}> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </p> </Modal> )); stories.add('Bottom Sheet', () => ( <Modal header="Modal Header" bottomSheet trigger={<Button>MODAL BUTTOM SHEET STYLE</Button>} > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </Modal> )); stories.add('Fixed Footer', () => ( <Modal header="Modal Header" fixedFooter trigger={<Button>MODAL WITH FIXED FOOTER</Button>} > Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum </Modal> )); stories.add('No Trigger', () => ( <div> <Button href="#modal1" className="modal-trigger"> {' '} Show Modal{' '} </Button> <Modal id="modal1" header="Modal Header"> Lorem ipsum dolor sit amet </Modal> </div> ));
client/src/components/MailList-Form/MailList-Form.js
DillGromble/TNABT-org
import React, { Component } from 'react'; // import { findDOMNode } from 'react-dom'; import axios from 'axios'; import ReactTooltip from 'react-tooltip'; import './mail-list.css'; export default class MailListForm extends Component { constructor(props) { super(props); this.state = { name: '', email: '', submitted: false, open: false }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.hideTooltip = this.hideTooltip.bind(this); this.toggleForm = this.toggleForm.bind(this); } handleSubmit(event) { event.preventDefault(); if (!this.state.name) return ReactTooltip.show(this.refs.name); if (!this.state.email) return ReactTooltip.show(this.refs.email); return axios.post('/api/mailer/mailinglist', this.state) .then(res => { this.setState({ name: '', email: '', submitted: true }); this.props.finishForm(); }) .catch(err => console.error(err)); } handleChange(event) { this.setState({ [event.target.name]: event.target.value }); } hideTooltip () { setTimeout(ReactTooltip.hide, 3000); } toggleForm() { this.setState({ open: !this.state.open }); } link() { return ( <a onClick={this.toggleForm} className="link" > Click Here to Register </a> ) } render() { if (!this.state.open) { return this.link(); } if (this.state.submitted) { return <h3 className="mail_list_thanks">Thank you!</h3>; } return ( <form onSubmit={this.handleSubmit} className="mail_list_form"> <ReactTooltip effect="solid" event="manual" afterShow={this.hideTooltip} /> <div className="mail_list_input_group"> <div className="mail_list_input"> <br /> <input type="text" data-tip="Name is required" onChange={this.handleChange} value={this.state.name} name="name" ref="name" placeholder="Name" /> </div> <div className="mail_list_input"> <br /> <input type="email" data-tip="E-mail is required" onChange={this.handleChange} value={this.state.email} name="email" ref="email" placeholder="E-mail" /> </div> </div> <div className="mail_list_btn_group"> <button type="submit" className="btn btn-ghost mail_list_submit"> Submit </button> <button type="button" className="btn btn-full mail_list_submit" onClick={this.toggleForm}> Cancel </button> </div> </form> ) } }
app/containers/Auth/controllers.js
balintsoos/app.rezsi.io
import React from 'react'; import Auth from 'containers/Auth'; export function AuthComponent(Component, controller) { return (props) => ( <Auth controller={controller} {...props}> <Component {...props} /> </Auth> ); } export function isLoggedInGroupLeader(Component) { return AuthComponent(Component, (isAuthenticated, user, redirect) => { if (isAuthenticated && user.role === 'LEADER') { return; } redirect('/login'); }); } export function isLoggedInGroupMember(Component) { return AuthComponent(Component, (isAuthenticated, user, redirect) => { if (isAuthenticated && user.role === 'MEMBER') { return; } redirect('/login'); }); } export function isNotLoggedIn(Component) { return AuthComponent(Component, (isAuthenticated, user, redirect) => { if (!isAuthenticated) { return; } if (user.role === 'LEADER') { return redirect('/groups'); // eslint-disable-line consistent-return } if (user.role === 'MEMBER') { return redirect('/user'); // eslint-disable-line consistent-return } }); }
src/svg-icons/editor/format-line-spacing.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatLineSpacing = (props) => ( <SvgIcon {...props}> <path d="M6 7h2.5L5 3.5 1.5 7H4v10H1.5L5 20.5 8.5 17H6V7zm4-2v2h12V5H10zm0 14h12v-2H10v2zm0-6h12v-2H10v2z"/> </SvgIcon> ); EditorFormatLineSpacing = pure(EditorFormatLineSpacing); EditorFormatLineSpacing.displayName = 'EditorFormatLineSpacing'; EditorFormatLineSpacing.muiName = 'SvgIcon'; export default EditorFormatLineSpacing;
src/mui/form/FormTab.js
RestUI/rest-ui
import React from 'react'; import FormField from './FormField'; const FormTab = ({ label, icon, children, ...rest }) => <span> {React.Children.map(children, input => input && ( <div key={input.props.source} style={input.props.style}> <FormField input={input} {...rest} /> </div> ))} </span>; export default FormTab;
src/components/tabbar/tabbar.js
vinej/react-portal
import React, { Component } from 'react'; import { observer } from "mobx-react";; import { Link } from 'react-router'; import { tabbarStore } from '../../stores/tabbar_store'; import { dispatch } from '../../helpers/dispatcher'; import { tabbarClose, tabbarSelect } from '../../actions/tabbar_actions'; @observer class TabBarItem extends Component { constructor() { super() this.handleOnClick = this.handleOnClick.bind(this) this.handleOnClose = this.handleOnClose.bind(this) } handleOnClick(event) { if (event.target.value == null) { return } dispatch(tabbarSelect(this.props.componentId)) } handleOnClose() { dispatch(tabbarClose(this.props.componentId)) } renderClose(visible){ if (visible === true ){ return ( <sup><span style={{ 'marginLeft' : '5px' }} /><a className='fa fa-close fa-sm' onClick={ this.handleOnClose } style={{ 'color': 'red'}}></a></sup> ) } } render() { return ( <li onClick={ this.handleOnClick } key={this.props.componentId} value={this.props.componentId} > {this.props.title} { this.renderClose(this.props.visible) } </li> ) } } @observer class TabBar extends Component { render() { const stores = tabbarStore.getStores() const count = stores.length - 1 return ( <div className='rp-tabbar-content'> <ul className="rp-tabbar"> { stores.map( (store, idx) => <TabBarItem key={store.componentId} componentId={store.componentId} title={store.title} visible={ store.display === 'block'} /> ) } </ul> </div> ) } } export default TabBar;
examples/todomvc/containers/App.js
joshblack/redux
import React, { Component } from 'react'; import TodoApp from './TodoApp'; import { createRedux } from 'redux'; import { Provider } from 'redux/react'; import * as stores from '../stores'; const redux = createRedux(stores); export default class App extends Component { render() { return ( <Provider redux={redux}> {() => <TodoApp />} </Provider> ); } }
app/components/main/MainHeaderCapture.js
sheldhur/Vector
// @flow import { remote } from 'electron'; import { message, Button, Input, Modal, Icon } from 'antd'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import moment from 'moment'; import domToImage from 'dom-to-image'; import * as fs from 'fs'; const { dialog, BrowserWindow } = remote; const currentWindow = remote.getCurrentWindow(); class MainHeaderCapture extends Component { size = 'small'; handlerSaveImage = (e) => { dialog.showSaveDialog(currentWindow, { title: 'Select path for image', defaultPath: this.props.currentTime ? `mainView ${moment(this.props.currentTime).format('YYYY-MM-DD HH-mm-ss')}.png` : 'mainView.png', properties: ['openFile', 'createDirectory'], buttonLabel: 'Save image', filters: [ { name: 'PNG', extensions: ['png'] }, ], }, (filePath) => { if (filePath && filePath.length) { const chart = document.querySelector('#mainView'); chart.classList.add('screencapture'); domToImage.toPng(chart).then((dataUrl) => { chart.classList.remove('screencapture'); fs.writeFile(filePath, dataUrl.replace(/^data:image\/png;base64,/, ''), 'base64', (error) => { if (error) { message.error(error.message, 6); throw error; } else { message.success(`${filePath} was saved`, 3); } }); }); } }); }; render = () => ( <Input.Group size={this.props.size} compact> <Button icon="picture" size={this.props.size} onClick={(e) => this.handlerSaveImage()} /> </Input.Group> ) } function mapStateToProps(state) { return { currentTime: state.ui.chartCurrentTime ? new Date(state.ui.chartCurrentTime) : null, }; } function mapDispatchToProps(dispatch) { return {}; } export default connect(mapStateToProps, mapDispatchToProps)(MainHeaderCapture);
app/javascript/mastodon/features/compose/components/upload_button.js
mimumemo/mastodon
import React from 'react'; import IconButton from '../../../components/icon_button'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePropTypes from 'react-immutable-proptypes'; const messages = defineMessages({ upload: { id: 'upload_button.label', defaultMessage: 'Add media (JPEG, PNG, GIF, WebM, MP4, MOV)' }, }); const makeMapStateToProps = () => { const mapStateToProps = state => ({ acceptContentTypes: state.getIn(['media_attachments', 'accept_content_types']), }); return mapStateToProps; }; const iconStyle = { height: null, lineHeight: '27px', }; export default @connect(makeMapStateToProps) @injectIntl class UploadButton extends ImmutablePureComponent { static propTypes = { disabled: PropTypes.bool, onSelectFile: PropTypes.func.isRequired, style: PropTypes.object, resetFileKey: PropTypes.number, acceptContentTypes: ImmutablePropTypes.listOf(PropTypes.string).isRequired, intl: PropTypes.object.isRequired, }; handleChange = (e) => { if (e.target.files.length > 0) { this.props.onSelectFile(e.target.files); } } handleClick = () => { this.fileElement.click(); } setRef = (c) => { this.fileElement = c; } render () { const { intl, resetFileKey, disabled, acceptContentTypes } = this.props; return ( <div className='compose-form__upload-button'> <IconButton icon='camera' title={intl.formatMessage(messages.upload)} disabled={disabled} onClick={this.handleClick} className='compose-form__upload-button-icon' size={18} inverted style={iconStyle} /> <label> <span style={{ display: 'none' }}>{intl.formatMessage(messages.upload)}</span> <input key={resetFileKey} ref={this.setRef} type='file' multiple={false} accept={acceptContentTypes.toArray().join(',')} onChange={this.handleChange} disabled={disabled} style={{ display: 'none' }} /> </label> </div> ); } }
src/containers/Asians/_components/PublishedBreakRound/Ballots/LargeBallots/Instance/BallotInstance/TeamDisplay.js
westoncolemanl/tabbr-web
import React from 'react' import ListSubheader from 'material-ui/List/ListSubheader' import SpeakerDisplay from './SpeakerDisplay' import Total from './Total' export default ({ government, breakRoom, firstSpeaker, secondSpeaker, whipSpeaker, replySpeaker, govTotal, oppTotal }) => <div className={'w-100'} > <ListSubheader disableSticky > {government ? 'Government' : 'Opposition'} </ListSubheader> <SpeakerDisplay speaker={government ? breakRoom.pm : breakRoom.lo} speakerScore={firstSpeaker} /> <SpeakerDisplay speaker={government ? breakRoom.dpm : breakRoom.dlo} speakerScore={secondSpeaker} /> <SpeakerDisplay speaker={government ? breakRoom.gw : breakRoom.ow} speakerScore={whipSpeaker} /> <SpeakerDisplay speaker={government ? breakRoom.gr : breakRoom.or} speakerScore={replySpeaker} /> <Total total={government ? govTotal : oppTotal} winner={government ? govTotal > oppTotal : govTotal < oppTotal} /> </div>
src/components/mock/FrontPage.js
tituomin/council-compass
import React from 'react'; import classNames from 'classnames'; import {Link} from 'react-router-dom'; export default function FrontPage({nextVote}) { let caseLink = null; if (nextVote) { caseLink = <Link to={`/motion/${nextVote}`} className="f4 b link dim br-pill ph3 pv3 dib white bg-purple mt3 mt4-ns" href="#0">Aloitetaan äänestäminen!</Link>; } return (<div> <article className="center mw7 hidden ba b--light-gray mv4"> <div className="pa3 bg-white"> <h1 className="f3 f2-ns tc ttu tracked">Partisipaattori</h1> <hr className="mw3 bb bw1 b--black-10" /> <h2 className="f4 f3-ns gray tc">Tarkastele ja kerro mielipiteesi Helsingin kaupunginvaltuuston tehdyistä päätöksistä.</h2> <p className="lh-copy tc"> Partisipaattorin avulla voit tarkastella Helsingin kaupunginvaltuustossa käsiteltyjä asioita ja verrata äänestystuloksia omiin mielipiteisiisi. Pääset äänestämään polttavista kysymyksistä itse, ja jokaisen vastauksen jälkeen näet, mitkä puolueet äänestivät eniten kantasi mukaisesti. Lopulta saat näkyviin yhteenvedon kaikista äänestyksistä. </p> <p className="lh-copy tc"> Palvelu on <a href="https://github.com/tituomin/council-compass">avointa lähdekoodia</a> ja se toteutettiin 5.5.2017 <a href="https://www.sitra.fi/tapahtumat/demokratiahack/">Demokratiahack-tapahtuman</a> yhteydessä. </p> <p className="tc"> { caseLink } </p> </div> </article> </div>); }
src/components/Html.js
jonirrings/react-stack
/** * react-stack react-stack * * Copyright © 2016. JonirRings. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* eslint-disable react/no-danger */ import React from 'react'; import PropTypes from 'prop-types'; import { analytics } from '../config'; function Html({ title, description, style, scripts, data, children }) { return ( <html className="no-js" lang="en"> <head> <meta charSet="utf-8" /> <meta httpEquiv="x-ua-compatible" content="ie=edge" /> <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="apple-touch-icon" href="apple-touch-icon.png" /> <link href="//cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" /> <link href="//fonts.jonirrings.com/css?family=Josefin+Sans|Nixie+One|Noto+Sans|Open+Sans|Poiret+One|Rajdhani|Rokkitt|Titillium+Web" rel="stylesheet" /> {style && <style id="css" dangerouslySetInnerHTML={{ __html: style }} />} </head> <body> <div id="root" dangerouslySetInnerHTML={{ __html: children }} /> { data && <script id="preloadData" type="application/json" dangerouslySetInnerHTML={{ __html: JSON.stringify(data) }} /> } {scripts && scripts.map(script => <script key={script} src={script} />)} {analytics.google.trackingId && <script dangerouslySetInnerHTML={{ __html: 'window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;' + `ga('create','${analytics.google.trackingId}','auto');ga('send','pageview')` }} /> } {analytics.google.trackingId && <script src="https://www.google-analytics.com/analytics.js" async defer /> } </body> </html> ); } Html.propTypes = { title: PropTypes.string.isRequired, description: PropTypes.string.isRequired, style: PropTypes.string.isRequired, scripts: PropTypes.arrayOf(PropTypes.string).isRequired, data: PropTypes.oneOfType([ PropTypes.string, PropTypes.array, ]).isRequired, children: PropTypes.string.isRequired, }; export default Html;
app/containers/Mobile/index.js
CityOfZion/neon-wallet
// @flow import { compose } from 'recompose' import { connect } from 'react-redux' import withThemeData from '../../hocs/withThemeData' import Mobile from './Mobile' import { showModal } from '../../modules/modal' import { MODAL_TYPES } from '../../core/constants' import withAuthData from '../../hocs/withAuthData' const mapDispatchToProps = dispatch => ({ showQrForExportModal: props => dispatch(showModal(MODAL_TYPES.SHOW_QR_FOR_EXPORT, props)), }) export default compose( connect( null, mapDispatchToProps, ), withAuthData(), withThemeData(), )(Mobile)
packages/material-ui-icons/src/PrintRounded.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19 8H5c-1.66 0-3 1.34-3 3v4c0 1.1.9 2 2 2h2v2c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2v-2h2c1.1 0 2-.9 2-2v-4c0-1.66-1.34-3-3-3zm-4 11H9c-.55 0-1-.45-1-1v-4h8v4c0 .55-.45 1-1 1zm4-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-2-9H7c-.55 0-1 .45-1 1v2c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1z" /></React.Fragment> , 'PrintRounded');
demo/qiniudemo/qiniudemo/ueditor/third-party/highcharts/highcharts.src.js
binlyzhuo/travelling
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v3.0.6 (2013-10-04) * * (c) 2009-2013 Torstein Hønsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ (function () { // encapsulated variables var UNDEFINED, doc = document, win = window, math = Math, mathRound = math.round, mathFloor = math.floor, mathCeil = math.ceil, mathMax = math.max, mathMin = math.min, mathAbs = math.abs, mathCos = math.cos, mathSin = math.sin, mathPI = math.PI, deg2rad = mathPI * 2 / 360, // some variables userAgent = navigator.userAgent, isOpera = win.opera, isIE = /msie/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext, Renderer, hasTouch = doc.documentElement.ontouchstart !== UNDEFINED, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function globalAnimation, pathAnim, timeUnits, noop = function () {}, charts = [], PRODUCT = 'Highcharts', VERSION = '3.0.6', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', /* * Empirical lowest possible opacities for TRACKER_FILL * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable //TRACKER_FILL = 'rgba(192,192,192,0.5)', NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', MILLISECOND = 'millisecond', SECOND = 'second', MINUTE = 'minute', HOUR = 'hour', DAY = 'day', WEEK = 'week', MONTH = 'month', YEAR = 'year', // constants for attributes LINEAR_GRADIENT = 'linearGradient', STOPS = 'stops', STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used makeTime, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}; // The Highcharts namespace win.Highcharts = win.Highcharts ? error(16, true) : {}; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ function extend(a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; } /** * Deep merge two or more objects and return a third object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, len = arguments.length, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // For each argument, extend the return for (i = 0; i < len; i++) { ret = doCopy(ret, arguments[i]); } return ret; } /** * Take an array and turn into a hash with even number arguments as keys and odd numbers as * values. Allows creating constants for commonly used style properties, attributes etc. * Avoid it in performance critical situations like looping */ function hash() { var i = 0, args = arguments, length = args.length, obj = {}; for (; i < length; i++) { obj[args[i++]] = args[i]; } return obj; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. Like MooTools' $.defined. * @param {Object} obj */ function defined(obj) { return obj !== UNDEFINED && obj !== null; } /** * Set or get an attribute or an object of attributes. Can't use jQuery attr because * it attempts to set expando properties on the SVG element, which is not allowed. * * @param {Object} elem The DOM element to receive the attribute(s) * @param {String|Object} prop The property or an abject of key-value pairs * @param {String} value The value if a single property is set */ function attr(elem, prop, value) { var key, setAttribute = 'setAttribute', ret; // if the prop is a string if (isString(prop)) { // set the value if (defined(value)) { elem[setAttribute](prop, value); // get the value } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo... ret = elem.getAttribute(prop); } // else if prop is defined, it is a hash of key/value pairs } else if (defined(prop) && isObject(prop)) { for (key in prop) { elem[setAttribute](key, prop[key]); } } return ret; } /** * Check if an element is an array, and if not, make it into an array. Like * MooTools' $.splat. */ function splat(obj) { return isArray(obj) ? obj : [obj]; } /** * Return the first value that is defined. Like MooTools' $.pick. */ function pick() { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (typeof arg !== 'undefined' && arg !== null) { return arg; } } } /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isIE) { if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () {}; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} decPoint The decimal point, defaults to the one given in the lang options * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options */ function numberFormat(number, decimals, decPoint, thousandsSep) { var lang = defaultOptions.lang, // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/ n = +number || 0, c = decimals === -1 ? (n.toString().split('.')[1] || '').length : // preserve decimals (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals), d = decPoint === undefined ? lang.decimalPoint : decPoint, t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep, s = n < 0 ? "-" : "", i = String(pInt(n = mathAbs(n).toFixed(c))), j = i.length > 3 ? i.length % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""); } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // Create an array of the remaining length +1 and join it with 0's return new Array((length || 2) + 1 - String(number).length).join(0) + number; } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ function wrap(obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return 'Invalid date'; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; val = numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, options) { var normalized, i; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (options && options.allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { interval = multiples[i]; if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) { break; } } // multiply back to the correct magnitude interval *= magnitude; return interval; } /** * Get a normalized tick interval for dates. Returns a configuration object with * unit range (interval), count and name. Used to prepare data for getTimeTicks. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs * of segments in stock charts, the normalizing logic was extracted in order to * prevent it for running over again for each segment having the same interval. * #662, #697. */ function normalizeTimeTickInterval(tickInterval, unitsOption) { var units = unitsOption || [[ MILLISECOND, // unit name [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples ], [ SECOND, [1, 2, 5, 10, 15, 30] ], [ MINUTE, [1, 2, 5, 10, 15, 30] ], [ HOUR, [1, 2, 3, 4, 6, 8, 12] ], [ DAY, [1, 2] ], [ WEEK, [1, 2] ], [ MONTH, [1, 2, 3, 4, 6] ], [ YEAR, null ]], unit = units[units.length - 1], // default unit is years interval = timeUnits[unit[0]], multiples = unit[1], count, i; // loop through the units to find the one that best fits the tickInterval for (i = 0; i < units.length; i++) { unit = units[i]; interval = timeUnits[unit[0]]; multiples = unit[1]; if (units[i + 1]) { // lessThan is in the middle between the highest multiple and the next unit. var lessThan = (interval * multiples[multiples.length - 1] + timeUnits[units[i + 1][0]]) / 2; // break and keep the current unit if (tickInterval <= lessThan) { break; } } } // prevent 2.5 years intervals, though 25, 250 etc. are allowed if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) { multiples = [1, 2, 5]; } // get the count count = normalizeTickInterval( tickInterval / interval, multiples, unit[0] === YEAR ? getMagnitude(tickInterval / interval) : 1 // #1913 ); return { unitRange: interval, count: count, unitName: unit[0] }; } /** * Set the tick positions to a time unit that makes sense, for example * on the first of each month or on every Monday. Return an array * with the time positions. Used in datetime axes as well as for grouping * data on a datetime axis. * * @param {Object} normalizedInterval The interval in axis values (ms) and the count * @param {Number} min The minimum in axis values * @param {Number} max The maximum in axis values * @param {Number} startOfWeek */ function getTimeTicks(normalizedInterval, min, max, startOfWeek) { var tickPositions = [], i, higherRanks = {}, useUTC = defaultOptions.global.useUTC, minYear, // used in months and years as a basis for Date.UTC() minDate = new Date(min), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 if (interval >= timeUnits[SECOND]) { // second minDate.setMilliseconds(0); minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 : count * mathFloor(minDate.getSeconds() / count)); } if (interval >= timeUnits[MINUTE]) { // minute minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 : count * mathFloor(minDate[getMinutes]() / count)); } if (interval >= timeUnits[HOUR]) { // hour minDate[setHours](interval >= timeUnits[DAY] ? 0 : count * mathFloor(minDate[getHours]() / count)); } if (interval >= timeUnits[DAY]) { // day minDate[setDate](interval >= timeUnits[MONTH] ? 1 : count * mathFloor(minDate[getDate]() / count)); } if (interval >= timeUnits[MONTH]) { // month minDate[setMonth](interval >= timeUnits[YEAR] ? 0 : count * mathFloor(minDate[getMonth]() / count)); minYear = minDate[getFullYear](); } if (interval >= timeUnits[YEAR]) { // year minYear -= minYear % count; minDate[setFullYear](minYear); } // week is a special case that runs outside the hierarchy if (interval === timeUnits[WEEK]) { // get start of current week, independent of count minDate[setDate](minDate[getDate]() - minDate[getDay]() + pick(startOfWeek, 1)); } // get tick positions i = 1; minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), timezoneOffset = useUTC ? 0 : (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950 // iterate and add tick positions at appropriate values while (time < max) { tickPositions.push(time); // if the interval is years, use Date.UTC to increase years if (interval === timeUnits[YEAR]) { time = makeTime(minYear + i * count, 0); // if the interval is months, use Date.UTC to increase months } else if (interval === timeUnits[MONTH]) { time = makeTime(minYear, minMonth + i * count); // if we're using global time, the interval is not fixed as it jumps // one hour at the DST crossover } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) { time = makeTime(minYear, minMonth, minDateDate + i * count * (interval === timeUnits[DAY] ? 1 : 7)); // else, the interval is fixed and we use simple addition } else { time += interval * count; } i++; } // push the last time tickPositions.push(time); // mark new days if the time is dividible by day (#1649, #1760) each(grep(tickPositions, function (time) { return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset; }), function (time) { higherRanks[time] = DAY; }); } // record information on the chosen unit - for dynamic label formatter tickPositions.info = extend(normalizedInterval, { higherRanks: higherRanks, totalRange: interval * count }); return tickPositions; } /** * Helper class that contains variuos counters that are local to the chart. */ function ChartCounters() { this.color = 0; this.symbol = 0; } ChartCounters.prototype = { /** * Wraps the color counter if it reaches the specified length. */ wrapColor: function (length) { if (this.color >= length) { this.color = 0; } }, /** * Wraps the symbol counter if it reaches the specified length. */ wrapSymbol: function (length) { if (this.symbol >= length) { this.symbol = 0; } } }; /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].ss_i = i; // stable sort index } arr.sort(function (a, b) { sortValue = sortFunction(a, b); return sortValue === 0 ? a.ss_i - b.ss_i : sortValue; }); // Remove index from items for (i = 0; i < length; i++) { delete arr[i].ss_i; // stable sort index } } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMin(data) { var i = data.length, min = data[0]; while (i--) { if (data[i] < min) { min = data[i]; } } return min; } /** * Non-recursive method to find the lowest member of an array. Math.min raises a maximum * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This * method is slightly slower, but safe. */ function arrayMax(data) { var i = data.length, max = data[0]; while (i--) { if (data[i] > max) { max = data[i]; } } return max; } /** * Utility method that destroys any SVGElement or VMLElement that are properties on the given object. * It loops all properties and invokes destroy if there is a destroy method. The property is * then delete'ed. * @param {Object} The object to destroy properties on * @param {Object} Exception, do not destroy this property, only delete it. */ function destroyObjectProperties(obj, except) { var n; for (n in obj) { // If the object is non-null and destroy is defined if (obj[n] && obj[n] !== except && obj[n].destroy) { // Invoke the destroy obj[n].destroy(); } // Delete the property from the object. delete obj[n]; } } /** * Discard an element by moving it to the bin and delete * @param {Object} The HTML node to discard */ function discardElement(element) { // create a garbage bin element, not part of the DOM if (!garbageBin) { garbageBin = createElement(DIV); } // move the node and empty bin if (element) { garbageBin.appendChild(element); } garbageBin.innerHTML = ''; } /** * Provide error messages for debugging, with links to online explanation */ function error(code, stop) { var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code; if (stop) { throw msg; } else if (win.console) { console.log(msg); } } /** * Fix JS round off float errors * @param {Number} num */ function correctFloat(num) { return parseFloat( num.toPrecision(14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ /*jslint white: true*/ timeUnits = hash( MILLISECOND, 1, SECOND, 1000, MINUTE, 60000, HOUR, 3600000, DAY, 24 * 3600000, WEEK, 7 * 24 * 3600000, MONTH, 31 * 24 * 3600000, YEAR, 31556952000 ); /*jslint white: false*/ /** * Path interpolation algorithm used across adapters */ pathAnim = { /** * Prepare start and end values so that the path can be animated one to one */ init: function (elem, fromD, toD) { fromD = fromD || ''; var shift = elem.shift, bezier = fromD.indexOf('C') > -1, numParams = bezier ? 7 : 3, endLength, slice, i, start = fromD.split(' '), end = [].concat(toD), // copy startBaseLine, endBaseLine, sixify = function (arr) { // in splines make move points have six parameters like bezier curves i = arr.length; while (i--) { if (arr[i] === M) { arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]); } } }; if (bezier) { sixify(start); sixify(end); } // pull out the base lines before padding if (elem.isArea) { startBaseLine = start.splice(start.length - 6, 6); endBaseLine = end.splice(end.length - 6, 6); } // if shifting points, prepend a dummy point to the end path if (shift <= end.length / numParams && start.length === end.length) { while (shift--) { end = [].concat(end).splice(0, numParams).concat(end); } } elem.shift = 0; // reset for following animations // copy and append last point until the length matches the end length if (start.length) { endLength = end.length; while (start.length < endLength) { //bezier && sixify(start); slice = [].concat(start).splice(start.length - numParams, numParams); if (bezier) { // disable first control point slice[numParams - 6] = slice[numParams - 2]; slice[numParams - 5] = slice[numParams - 1]; } start = start.concat(slice); } } if (startBaseLine) { // append the base lines for areas start = start.concat(startBaseLine); end = end.concat(endBaseLine); } return [start, end]; }, /** * Interpolate each value of the path and return the array */ step: function (start, end, pos, complete) { var ret = [], i = start.length, startVal; if (pos === 1) { // land on the final path without adjustment points appended in the ends ret = complete; } else if (i === end.length && pos < 1) { while (i--) { startVal = parseFloat(start[i]); ret[i] = isNaN(startVal) ? // a letter instruction like M or L start[i] : pos * (parseFloat(end[i] - startVal)) + startVal; } } else { // if animation is finished or length not matching, land on right value ret = end; } return ret; } }; (function ($) { /** * The default HighchartsAdapter for jQuery */ win.HighchartsAdapter = win.HighchartsAdapter || ($ && { /** * Initialize the adapter by applying some extensions to jQuery */ init: function (pathAnim) { // extend the animate function to allow SVG animations var Fx = $.fx, Step = Fx.step, dSetter, Tween = $.Tween, propHooks = Tween && Tween.propHooks, opacityHook = $.cssHooks.opacity; /*jslint unparam: true*//* allow unused param x in this function */ $.extend($.easing, { easeOutQuad: function (x, t, b, c, d) { return -c * (t /= d) * (t - 2) + b; } }); /*jslint unparam: false*/ // extend some methods to check for elem.attr, which means it is a Highcharts SVG object $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) { var obj = Step, base, elem; // Handle different parent objects if (fn === 'cur') { obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype } else if (fn === '_default' && Tween) { // jQuery 1.8 model obj = propHooks[fn]; fn = 'set'; } // Overwrite the method base = obj[fn]; if (base) { // step.width and step.height don't exist in jQuery < 1.7 // create the extended function replacement obj[fn] = function (fx) { // Fx.prototype.cur does not use fx argument fx = i ? fx : this; // Don't run animations on textual properties like align (#1821) if (fx.prop === 'align') { return; } // shortcut elem = fx.elem; // Fx.prototype.cur returns the current value. The other ones are setters // and returning a value has no effect. return elem.attr ? // is SVG element wrapper elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method base.apply(this, arguments); // use jQuery's built-in method }; } }); // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+ wrap(opacityHook, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) dSetter = function (fx) { var elem = fx.elem, ends; // Normally start and end should be set in state == 0, but sometimes, // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped // in these cases if (!fx.started) { ends = pathAnim.init(elem, elem.d, elem.toD); fx.start = ends[0]; fx.end = ends[1]; fx.started = true; } // interpolate each value of the path elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD)); }; // jQuery 1.8 style if (Tween) { propHooks.d = { set: dSetter }; // pre 1.8 } else { // animate paths Step.d = dSetter; } /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ this.each = Array.prototype.forEach ? function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } : function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; /** * Register Highcharts as a plugin in the respective framework */ $.fn.highcharts = function () { var constr = 'Chart', // default constructor args = arguments, options, ret, chart; if (isString(args[0])) { constr = args[0]; args = Array.prototype.slice.call(args, 1); } options = args[0]; // Create the chart if (options !== UNDEFINED) { /*jslint unused:false*/ options.chart = options.chart || {}; options.chart.renderTo = this[0]; chart = new Highcharts[constr](options, args[1]); ret = this; /*jslint unused:true*/ } // When called without parameters or with the return argument, get a predefined chart if (options === UNDEFINED) { ret = charts[attr(this[0], 'data-highcharts-chart')]; } return ret; }; }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: $.getScript, /** * Return the index of an item in an array, or -1 if not found */ inArray: $.inArray, /** * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method. * @param {Object} elem The HTML element * @param {String} method Which method to run on the wrapped element */ adapterRun: function (elem, method) { return $(elem)[method](); }, /** * Filter an array */ grep: $.grep, /** * Map an array * @param {Array} arr * @param {Function} fn */ map: function (arr, fn) { //return jQuery.map(arr, fn); var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the position of an element relative to the top left of the page */ offset: function (el) { return $(el).offset(); }, /** * Add an event listener * @param {Object} el A HTML element or custom object * @param {String} event The event type * @param {Function} fn The event handler */ addEvent: function (el, event, fn) { $(el).bind(event, fn); }, /** * Remove event added with addEvent * @param {Object} el The object * @param {String} eventType The event type. Leave blank to remove all events. * @param {Function} handler The function to remove */ removeEvent: function (el, eventType, handler) { // workaround for jQuery issue with unbinding custom events: // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2 var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent'; if (doc[func] && el && !el[func]) { el[func] = function () {}; } $(el).unbind(eventType, handler); }, /** * Fire an event on a custom object * @param {Object} el * @param {String} type * @param {Object} eventArguments * @param {Function} defaultFunction */ fireEvent: function (el, type, eventArguments, defaultFunction) { var event = $.Event(type), detachedType = 'detached' + type, defaultPrevented; // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts // never uses these properties, Chrome includes them in the default click event and // raises the warning when they are copied over in the extend statement below. // // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid // testing if they are there (warning in chrome) the only option is to test if running IE. if (!isIE && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; } extend(event, eventArguments); // Prevent jQuery from triggering the object method that is named the // same as the event. For example, if the event is 'select', jQuery // attempts calling el.select and it goes into a loop. if (el[type]) { el[detachedType] = el[type]; el[type] = null; } // Wrap preventDefault and stopPropagation in try/catch blocks in // order to prevent JS errors when cancelling events on non-DOM // objects. #615. /*jslint unparam: true*/ $.each(['preventDefault', 'stopPropagation'], function (i, fn) { var base = event[fn]; event[fn] = function () { try { base.call(event); } catch (e) { if (fn === 'preventDefault') { defaultPrevented = true; } } }; }); /*jslint unparam: false*/ // trigger it $(el).trigger(event); // attach the method if (el[detachedType]) { el[type] = el[detachedType]; el[detachedType] = null; } if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) { defaultFunction(event); } }, /** * Extension method needed for MooTools */ washMouseEvent: function (e) { var ret = e.originalEvent || e; // computed by jQuery, needed by IE8 if (ret.pageX === UNDEFINED) { // #1236 ret.pageX = e.pageX; ret.pageY = e.pageY; } return ret; }, /** * Animate a HTML element or SVG element wrapper * @param {Object} el * @param {Object} params * @param {Object} options jQuery-like animation options: duration, easing, callback */ animate: function (el, params, options) { var $el = $(el); if (!el.style) { el.style = {}; // #1881 } if (params.d) { el.toD = params.d; // keep the array form for paths, used in $.fx.step.d params.d = 1; // because in jQuery, animating to an array has a different meaning } $el.stop(); if (params.opacity !== UNDEFINED && el.attr) { params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161) } $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { $(el).stop(); } }); }(win.jQuery)); // check for a custom HighchartsAdapter defined prior to this file var globalAdapter = win.HighchartsAdapter, adapter = globalAdapter || {}; // Initialize the adapter if (globalAdapter) { globalAdapter.init.call(globalAdapter, pathAnim); } // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object // and all the utility functions will be null. In that case they are populated by the // default adapters below. var adapterRun = adapter.adapterRun, getScript = adapter.getScript, inArray = adapter.inArray, each = adapter.each, grep = adapter.grep, offset = adapter.offset, map = adapter.map, addEvent = adapter.addEvent, removeEvent = adapter.removeEvent, fireEvent = adapter.fireEvent, washMouseEvent = adapter.washMouseEvent, animate = adapter.animate, stop = adapter.stop; /* **************************************************************************** * Handle the options * *****************************************************************************/ var defaultLabelOptions = { enabled: true, // rotation: 0, // align: 'center', x: 0, y: 15, /*formatter: function () { return this.value; },*/ style: { color: '#666', cursor: 'default', fontSize: '11px', lineHeight: '14px' } }; defaultOptions = { colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ',' }, global: { useUTC: true, canvasToolsURL: 'http://code.highcharts.com/3.0.6/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/3.0.6/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 5, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, style: { fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#274b6d',//#3E576F', fontSize: '16px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#4d759e' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, lineWidth: 2, //shadow: false, // stacking: null, marker: { enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true //radius: base + 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: merge(defaultLabelOptions, { align: 'center', enabled: false, formatter: function () { return this.y === null ? '' : numberFormat(this.y, -1); }, verticalAlign: 'bottom', // above singular point y: 0 // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, // padding: 3, // shadow: false }), cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, showInLegend: true, states: { // states for the entire series hover: { //enabled: false, //lineWidth: base + 1, marker: { // lineWidth: base + 1, // radius: base + 1 } }, select: { marker: {} } }, stickyTracking: true //tooltip: { //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} // turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, borderWidth: 1, borderColor: '#909090', borderRadius: 5, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 10, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { cursor: 'pointer', color: '#274b6d', fontSize: '12px' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '1em' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(255, 255, 255, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>', shadow: true, //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // Series defaults var defaultPlotOptions = defaultOptions.plotOptions, defaultSeriesOptions = defaultPlotOptions.line; // set the default time methods setTimeMethods(); /** * Set the time methods globally based on the useUTC option. Time method can be either * local time or UTC (default). */ function setTimeMethods() { var useUTC = defaultOptions.global.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) { return new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Pull out axis options and apply them to the respective default axis options /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis); defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis); options.xAxis = options.yAxis = UNDEFINED;*/ // Merge in the default options defaultOptions = merge(defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Merely exposing defaultOptions for outside modules * isn't enough because the setOptions method creates a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var Color = function (input) { // declare variables var rgba = [], result, stops; /** * Parse the input color to rgba array * @param {String} input */ function init(input) { // Gradients if (input && input.stops) { stops = map(input.stops, function (stop) { return Color(stop[1]); }); // Solid colors } else { // rgba result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1]; } } } } } /** * Return the color a specified format * @param {String} format */ function get(format) { var ret; if (stops) { ret = merge(input); ret.stops = [].concat(ret.stops); each(stops, function (stop, i) { ret.stops[i] = [ret.stops[i][0], stop.get(format)]; }); // it's NaN if gradient colors on a column chart } else if (rgba && !isNaN(rgba[0])) { if (format === 'rgb') { ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')'; } else if (format === 'a') { ret = rgba[3]; } else { ret = 'rgba(' + rgba.join(',') + ')'; } } else { ret = input; } return ret; } /** * Brighten the color * @param {Number} alpha */ function brighten(alpha) { if (stops) { each(stops, function (stop) { stop.brighten(alpha); }); } else if (isNumber(alpha) && alpha !== 0) { var i; for (i = 0; i < 3; i++) { rgba[i] += pInt(alpha * 255); if (rgba[i] < 0) { rgba[i] = 0; } if (rgba[i] > 255) { rgba[i] = 255; } } } return this; } /** * Set the color's opacity to a given alpha value * @param {Number} alpha */ function setOpacity(alpha) { rgba[3] = alpha; return this; } // initialize: parse the input init(input); // public methods return { get: get, brighten: brighten, rgba: rgba, setOpacity: setOpacity }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; /** * A collection of attribute setters. These methods, if defined, are called right before a certain * attribute is set on an element wrapper. Returning false prevents the default attribute * setter to run. Returning a value causes the default setter to set that value. Used in * Renderer.label. */ wrapper.attrSetters = {}; }, /** * Default base for animation */ opacity: 1, /** * Animate a given attribute * @param {Object} params * @param {Number} options The same options as in jQuery animation * @param {Function} complete Function to perform at the end of animation */ animate: function (params, options, complete) { var animOptions = pick(options, globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions); if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params); if (complete) { complete(); } } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val) { var wrapper = this, key, value, result, i, child, element = wrapper.element, nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text" renderer = wrapper.renderer, skipAttr, titleNode, attrSetters = wrapper.attrSetters, shadows = wrapper.shadows, hasSetSymbolSize, doTransform, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (isString(hash)) { key = hash; if (nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } else if (key === 'strokeWidth') { key = 'stroke-width'; } ret = attr(element, key) || wrapper[key] || 0; if (key !== 'd' && key !== 'visibility' && key !== 'fill') { // 'd' is string in animation step ret = parseFloat(ret); } // setter } else { for (key in hash) { skipAttr = false; // reset value = hash[key]; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false) { if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // paths if (key === 'd') { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } //wrapper.d = value; // shortcut for animations // update child tspans x values } else if (key === 'x' && nodeName === 'text') { for (i = 0; i < element.childNodes.length; i++) { child = element.childNodes[i]; // if the x values are equal, the tspan represents a linebreak if (attr(child, 'x') === attr(element, 'x')) { //child.setAttribute('x', value); attr(child, 'x', value); } } } else if (wrapper.rotation && (key === 'x' || key === 'y')) { doTransform = true; // apply gradients } else if (key === 'fill') { value = renderer.color(value, element, key); // circle x and y } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) { key = { x: 'cx', y: 'cy' }[key] || key; // rectangle border radius } else if (nodeName === 'rect' && key === 'r') { attr(element, { rx: value, ry: value }); skipAttr = true; // translation and text rotation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' || key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') { doTransform = true; skipAttr = true; // apply opacity as subnode (required by legacy WebKit and Batik) } else if (key === 'stroke') { value = renderer.color(value, element, key); // emulate VML's dashstyle implementation } else if (key === 'dashstyle') { key = 'stroke-dasharray'; value = value && value.toLowerCase(); if (value === 'solid') { value = NONE; } else if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * pick(hash['stroke-width'], wrapper['stroke-width']); } value = value.join(','); } // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2 // is unable to cast them. Test again with final IE9. } else if (key === 'width') { value = pInt(value); // Text alignment } else if (key === 'align') { key = 'text-anchor'; value = { left: 'start', center: 'middle', right: 'end' }[value]; // Title requires a subnode, #431 } else if (key === 'title') { titleNode = element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); element.appendChild(titleNode); } titleNode.textContent = value; } // jQuery animate changes case if (key === 'strokeWidth') { key = 'stroke-width'; } // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke- // width is 0. #1369 if (key === 'stroke-width' || key === 'stroke') { wrapper[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (wrapper.stroke && wrapper['stroke-width']) { attr(element, 'stroke', wrapper.stroke); attr(element, 'stroke-width', wrapper['stroke-width']); wrapper.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) { element.removeAttribute('stroke'); wrapper.hasStroke = false; } skipAttr = true; } // symbols if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } // let the shadow follow the main element if (shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { i = shadows.length; while (i--) { attr( shadows[i], key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : value ); } } // validate heights if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) { value = 0; } // Record for animation and quick access without polling the DOM wrapper[key] = value; if (key === 'text') { // Delete bBox memo when the text changes if (value !== wrapper.textStr) { delete wrapper.bBox; } wrapper.textStr = value; if (wrapper.added) { renderer.buildText(wrapper); } } else if (!skipAttr) { attr(element, key, value); } } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (doTransform) { wrapper.updateTransform(); } } return ret; }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (strokeWidth, x, y, width, height) { var wrapper = this, key, attribs = {}, values = {}, normalizer; strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges values.x = mathFloor(x || wrapper.x || 0) + normalizer; values.y = mathFloor(y || wrapper.y || 0) + normalizer; values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer); values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer); values.strokeWidth = strokeWidth; for (key in values) { if (wrapper[key] !== values[key]) { // only set attribute if changed wrapper[key] = attribs[key] = values[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { /*jslint unparam: true*//* allow unused param a in the regexp function below */ var elemWrapper = this, elem = elemWrapper.element, textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text', n, serializedCss = '', hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Merge the new styles with the old ones styles = extend( elemWrapper.styles, styles ); // store object elemWrapper.styles = styles; // Don't handle line wrap on canvas if (useCanVG && textWidth) { delete styles.width; } // serialize and set style attribute if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute if (textWidth) { delete styles.width; } css(elemWrapper.element, styles); } else { for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { this.element.radialReference = coordinates; return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element, bBox = wrapper.bBox; // faking getBBox in exported SVG in legacy IE if (!bBox) { // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } bBox = wrapper.bBox = { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; } return bBox; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], nonLeft = align && align !== 'left', shadows = wrapper.shadows; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, height, rotation = wrapper.rotation, baseline, radians = 0, costheta = 1, sintheta = 0, quad, textWidth = pInt(wrapper.textWidth), xCorr = wrapper.xCorr || 0, yCorr = wrapper.yCorr || 0, currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed if (defined(rotation)) { radians = rotation * deg2rad; // deg to rad costheta = mathCos(radians); sintheta = mathSin(radians); wrapper.setSpanRotation(rotation, sintheta, costheta); } width = pick(wrapper.elemWidth, elem.offsetWidth); height = pick(wrapper.elemHeight, elem.offsetHeight); // update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: 'normal' }); width = textWidth; } // correct x and y baseline = renderer.fontMetrics(elem.style.fontSize).b; xCorr = costheta < 0 && -width; yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(elem, { textAlign: align }); } // record correction wrapper.xCorr = xCorr; wrapper.yCorr = yCorr; } // apply position with correction css(elem, { left: (x + xCorr) + PX, top: (y + yCorr) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { height = elem.offsetHeight; // assigned to height for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation) { var rotationStyle = {}, cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; css(this.element, rotationStyle); }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')'); } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { attr(wrapper.element, 'transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function () { var wrapper = this, bBox = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad; if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669) if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } wrapper.bBox = bBox; } return bBox; }, /** * Show the element */ show: function () { return this.attr({ visibility: VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.hide(); } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, parentWrapper = parent || renderer, parentNode = parentWrapper.element || renderer.box, childNodes = parentNode.childNodes, element = this.element, zIndex = attr(element, 'zIndex'), otherElement, otherZIndex, i, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // mark the container as having z indexed children if (zIndex) { parentWrapper.handleZ = true; zIndex = pInt(zIndex); } // insert according to this and other elements' zIndex if (parentWrapper.handleZ) { // this element or any of its siblings has a z index for (i = 0; i < childNodes.length; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // insert before the first element with a higher zIndex pInt(otherZIndex) > zIndex || // if no zIndex given, insert before the first element with a zIndex (!defined(zIndex) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; break; } } } // default: append at the end if (!inserted) { parentNode.appendChild(element); } // mark as added this.added = true; // fire an event for internal hooks fireEvent(this, 'add'); return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && element.parentNode, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960). while (parentToClean && parentToClean.childNodes.length === 0) { grandParent = parentToClean.parentNode; wrapper.safeRemoveChild(parentToClean); parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, forExport) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? loc.href .replace(/#.*?$/, '') // remove the hash .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes .replace(/ /g, '%20') : // replace spaces (needed for Safari only) ''; // Add description desc = this.createElement('desc').add(); desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION)); renderer.defs = this.createElement('defs').add(); renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, lines = pick(wrapper.textStr, '').toString() .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g), childNodes = textNode.childNodes, styleRegex = /style="([^"]+)"/, hrefRegex = /href="(http[^"]+)"/, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = textStyles && textStyles.width && pInt(textStyles.width), textLineHeight = textStyles && textStyles.lineHeight, i = childNodes.length; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } if (width && !wrapper.added) { this.box.appendChild(textNode); // attach it to the DOM to read offset width } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = (span.replace(/<(.|\n)*?>/g, '') || ' ') .replace(/&lt;/g, '<') .replace(/&gt;/g, '>'); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left attributes.x = parentX; } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', textLineHeight || renderer.fontMetrics( /px$/.test(tspan.style.fontSize) ? tspan.style.fontSize : textStyles.fontSize ).h, // Safari 6.0.2 - too optimized for its own good (#1539) // TODO: revisit this with future versions of Safari isWebKit && tspan.offsetHeight ); } // Append it textNode.appendChild(tspan); spanNo++; // check width and apply soft breaks if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 tooLong, actualWidth, clipHeight = wrapper._clipHeight, rest = [], dy = pInt(textLineHeight || 16), softLineNo = 1, bBox; while (words.length || rest.length) { delete wrapper.bBox; // delete cache bBox = wrapper.getBBox(); actualWidth = bBox.width; tooLong = actualWidth > width; if (!tooLong || words.length === 1) { // new line needed words = rest; rest = []; if (words.length) { softLineNo++; if (clipHeight && softLineNo * dy > clipHeight) { words = ['...']; wrapper.attr('title', wrapper.textStr); } else { tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } } } } }); }); }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState) { var label = this.label(text, x, y, null, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, STYLE = 'style', verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState[STYLE]; delete normalState[STYLE]; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState[STYLE]; delete hoverState[STYLE]; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState[STYLE]; delete pressedState[STYLE]; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState[STYLE]; delete disabledState[STYLE]; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function () { if (curState !== 3) { callback.call(label); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }; return this.createElement('circle').attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect').attr({ rx: r, ry: r, fill: NONE }); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var obj, // get the symbol definition function symbolFn = this.symbols[symbol], // check if there's a path defined for this symbol path = symbolFn && symbolFn( mathRound(x), mathRound(y), width, height, options ), imageElement, imageRegex = /^url\((.*?)\)$/, imageSrc, imageSize, centerImage; if (path) { obj = this.path(path); // expando properties for use in animate and attr extend(obj, { symbolName: symbol, x: x, y: y, width: width, height: height }); if (options) { extend(obj, options); } // image symbols } else if (imageRegex.test(symbol)) { // On image load, set the size and position centerImage = function (img, size) { if (img.element) { // it may be destroyed in the meantime (#1390) img.attr({ width: size[0], height: size[1] }); if (!img.alignByTranslate) { // #185 img.translate( mathRound((width - size[0]) / 2), // #1378 mathRound((height - size[1]) / 2) ); } } }; imageSrc = symbol.match(imageRegex)[1]; imageSize = symbolSizes[imageSrc]; // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. // obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); }, src: imageSrc }); } } return obj; }, /** * An extendable collection of functions for defining symbol paths. */ symbols: { 'circle': function (x, y, w, h) { var cpw = 0.166 * w; return [ M, x + w / 2, y, 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h, 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y, 'Z' ]; }, 'square': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h, x, y + h, 'Z' ]; }, 'triangle-down': function (x, y, w, h) { return [ M, x, y, L, x + w, y, x + w / 2, y + h, 'Z' ]; }, 'diamond': function (x, y, w, h) { return [ M, x + w / 2, y, L, x + w, y + h / 2, x + w / 2, y + h, x, y + h / 2, 'Z' ]; }, 'arc': function (x, y, w, h, options) { var start = options.start, radius = options.r || w || h, end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561) innerRadius = options.innerR, open = options.open, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), longArc = options.end - start < mathPI ? 0 : 1; return [ M, x + radius * cosStart, y + radius * sinStart, 'A', // arcTo radius, // x radius radius, // y radius 0, // slanting longArc, // long or short arc 1, // clockwise x + radius * cosEnd, y + radius * sinEnd, open ? M : L, x + innerRadius * cosEnd, y + innerRadius * sinEnd, 'A', // arcTo innerRadius, // x radius innerRadius, // y radius 0, // slanting longArc, // long or short arc 0, // clockwise x + innerRadius * cosStart, y + innerRadius * sinStart, open ? '' : 'Z' // close ]; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; return wrapper; }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object. Prior to Highstock, an array was used to define * a linear gradient with pixel positions relative to the SVG. In newer versions * we change the coordinates to apply relative to the shape, using coordinates * 0-1 within the shape. To preserve backwards compatibility, linearGradient * in this definition is an object of x1, y1, x2 and y2. * * @param {Object} color The color or config object */ color: function (color, elem, prop) { var renderer = this, colorObject, regexRgba = /^rgba/, gradName, gradAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color && color.linearGradient) { gradName = 'linearGradient'; } else if (color && color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { gradAttr = merge(gradAttr, { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2], gradientUnits: 'userSpaceOnUse' }); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].id; } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Return the reference to the gradient object return 'url(' + renderer.url + '#' + id + ')'; // Webkit and Batik can't show rgba. } else if (regexRgba.test(color)) { colorObject = Color(color); attr(elem, prop + '-opacity', colorObject.get('a')); return colorObject.get('rgb'); } else { // Remove the opacity attribute added above. Does not throw if the attribute is not there. elem.removeAttribute(prop + '-opacity'); return color; } }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, defaultChartStyle = defaultOptions.chart.style, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper; if (useHTML && !renderer.forExport) { return renderer.html(str, x, y); } x = mathRound(pick(x, 0)); y = mathRound(pick(y, 0)); wrapper = renderer.createElement('text') .attr({ x: x, y: y, text: str }) .css({ fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } wrapper.x = x; wrapper.y = y; return wrapper; }, /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var defaultChartStyle = defaultOptions.chart.style, wrapper = this.createElement('span'), attrSetters = wrapper.attrSetters, element = wrapper.element, renderer = wrapper.renderer; // Text setter attrSetters.text = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = value; return false; }; // Various setters which rely on update transform attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); return false; }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, whiteSpace: 'nowrap', fontFamily: defaultChartStyle.fontFamily, fontSize: defaultChartStyle.fontSize }); // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle; // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, { className: attr(parentGroup.element, 'class') }, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup.attrSetters, { translateX: function (value) { htmlGroupStyle.left = value + PX; }, translateY: function (value) { htmlGroupStyle.top = value + PX; }, visibility: function (value, key) { htmlGroupStyle[key] = value; } }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize) { fontSize = pInt(fontSize || 11); // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2), baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, attrSetters = wrapper.attrSetters, needsBox; /** * This function runs after the label is added to the DOM (when the bounding box is * available), and after the text of the label is updated to detect the new bounding * box and reflect it in the border box. */ function updateBoxSize() { var boxX, boxY, style = text.element.style; bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.getBBox(); wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding); boxY = baseline ? -baselineOffset : 0; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(merge({ width: wrapper.width, height: wrapper.height }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ function updateTextPadding() { var styles = wrapper.styles, textAlign = styles && styles.textAlign, x = paddingLeft + padding * (1 - alignFactor), y; // determin y based on the baseline y = baseline ? 0 : baselineOffset; // compensate for alignment if (defined(width) && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr({ x: x, y: y }); } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } function getSizeAfterAdd() { text.add(wrapper); wrapper.attr({ text: str, // alignment is available now x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ addEvent(wrapper, 'add', getSizeAfterAdd); /* * Add specific attribute setters. */ // only change local variables attrSetters.width = function (value) { width = value; return false; }; attrSetters.height = function (value) { height = value; return false; }; attrSetters.padding = function (value) { if (defined(value) && value !== padding) { padding = value; updateTextPadding(); } return false; }; attrSetters.paddingLeft = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } return false; }; // change local variable and set attribue as well attrSetters.align = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; return false; // prevent setting text-anchor on the group }; // apply these to the box and the text alike attrSetters.text = function (value, key) { text.attr(key, value); updateBoxSize(); updateTextPadding(); return false; }; // apply these to the box but not to the text attrSetters[STROKE_WIDTH] = function (value, key) { needsBox = true; crispAdjust = value % 2 / 2; boxAttr(key, value); return false; }; attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) { if (key === 'fill') { needsBox = true; } boxAttr(key, value); return false; }; attrSetters.anchorX = function (value, key) { anchorX = value; boxAttr(key, value + crispAdjust - wrapperX); return false; }; attrSetters.anchorY = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); return false; }; // rename attributes attrSetters.x = function (value) { wrapper.x = value; // for animation getter value -= alignFactor * ((width || bBox.width) + padding); wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); return false; }; attrSetters.y = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); return false; }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { removeEvent(wrapper, 'add', getSizeAfterAdd); // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ Highcharts.VMLElement = VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; wrapper.attrSetters = {}; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks fireEvent(wrapper, 'add'); return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function (rotation, sintheta, costheta) { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://highcharts.com/tests/?file=text-rotation css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = [], clockwise; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract 1 from the end X // position. #760, #1371. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { clockwise = value[i] === 'wa' ? 1 : -1; // #1642 if (path[i + 5] === path[i + 7]) { path[i + 7] -= clockwise; } // Start and end Y (#1410) if (path[i + 6] === path[i + 8]) { path[i + 8] -= clockwise; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Get or set attributes */ attr: function (hash, val) { var wrapper = this, key, value, i, result, element = wrapper.element || {}, elemStyle = element.style, nodeName = element.nodeName, renderer = wrapper.renderer, symbolName = wrapper.symbolName, hasSetSymbolSize, shadows = wrapper.shadows, skipAttr, attrSetters = wrapper.attrSetters, ret = wrapper; // single key-value pair if (isString(hash) && defined(val)) { key = hash; hash = {}; hash[key] = val; } // used as a getter, val is undefined if (isString(hash)) { key = hash; if (key === 'strokeWidth' || key === 'stroke-width') { ret = wrapper.strokeweight; } else { ret = wrapper[key]; } // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; // check for a specific attribute setter result = attrSetters[key] && attrSetters[key].call(wrapper, value, key); if (result !== false && value !== null) { // #620 if (result !== UNDEFINED) { value = result; // the attribute setter has returned a new value to set } // prepare paths // symbols if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) { // if one of the symbol size affecting parameters are changed, // check all the others only once for each call to an element's // .attr() method if (!hasSetSymbolSize) { wrapper.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } else if (key === 'd') { value = value || []; wrapper.d = value.join(' '); // used in getter for animation element.path = value = wrapper.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } skipAttr = true; // handle visibility } else if (key === 'visibility') { // let the shadow follow the main element if (shadows) { i = shadows.length; while (i--) { shadows[i].style[key] = value; } } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { elemStyle[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } elemStyle[key] = value; skipAttr = true; // directly mapped to css } else if (key === 'zIndex') { if (value) { elemStyle[key] = value; } skipAttr = true; // x, y, width, height } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) { wrapper[key] = value; // used in getter if (key === 'x' || key === 'y') { key = { x: 'left', y: 'top' }[key]; } else { value = mathMax(0, value); // don't set width or height below zero (#311) } // clipping rectangle special if (wrapper.updateClipping) { wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' wrapper.updateClipping(); } else { // normal elemStyle[key] = value; } skipAttr = true; // class name } else if (key === 'class' && nodeName === 'DIV') { // IE8 Standards mode has problems retrieving the className element.className = value; // stroke } else if (key === 'stroke') { value = renderer.color(value, element, key); key = 'strokecolor'; // stroke width } else if (key === 'stroke-width' || key === 'strokeWidth') { element.stroked = value ? true : false; key = 'strokeweight'; wrapper[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } // dashStyle } else if (key === 'dashstyle') { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; wrapper.dashstyle = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ skipAttr = true; // fill } else if (key === 'fill') { if (nodeName === 'SPAN') { // text color elemStyle.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE ? true : false; value = renderer.color(value, element, key, wrapper); key = 'fillcolor'; } // opacity: don't bother - animation is too slow and filters introduce artifacts } else if (key === 'opacity') { /*css(element, { opacity: value });*/ skipAttr = true; // rotation on VML elements } else if (nodeName === 'shape' && key === 'rotation') { wrapper[key] = element.style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; element.style.top = mathRound(mathCos(value * deg2rad)) + PX; // translation for animation } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') { wrapper[key] = value; wrapper.updateTransform(); skipAttr = true; // text for rotated and non-rotated elements } else if (key === 'text') { this.bBox = null; element.innerHTML = value; skipAttr = true; } if (!skipAttr) { if (docMode8) { // IE8 setAttribute bug element[key] = value; } else { attr(element, key, value); } } } } } return ret; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; } }; VMLElement = extendClass(SVGElement, VMLElement); /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height) { var renderer = this, boxWrapper, box; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV); box = boxWrapper.element; box.style.position = RELATIVE; // for freeform drawing using renderer directly container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153) (doc.styleSheets.length ? doc.styleSheets[0] : doc.createStyleSheet()).cssText += 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { member.css(clipRect.getCSS(member)); }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right addEvent(wrapper, 'add', applyRadialGradient); } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>']; createElement(this.prepVML(markup), null, null, elem); ret = colorObject.get('rgb'); } else { var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node if (propNodes.length) { propNodes[0].opacity = 1; propNodes[0].type = 'solid'; } ret = color; } return ret; }, /** * Take a VML string and prepare it for either IE8 or IE6/IE7. * @param {Array} markup A string array of the VML markup to prepare */ prepVML: function (markup) { var vmlStyle = 'display:inline-block;behavior:url(#default#VML);', isIE8 = this.isIE8; markup = markup.join(''); if (isIE8) { // add xmlns and style inline markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />'); if (markup.indexOf('style="') === -1) { markup = markup.replace('/>', ' style="' + vmlStyle + '" />'); } else { markup = markup.replace('style="', 'style="' + vmlStyle); } } else { // add namespace markup = markup.replace('<', '<hcv:'); } return markup; }, /** * Create rotated and aligned text * @param {String} str * @param {Number} x * @param {Number} y */ text: SVGRenderer.prototype.html, /** * Create and return a path element * @param {Array} path */ path: function (path) { var attr = { // subpixel precision down to 0.1 (width and height = 1px) coordsize: '10 10' }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } // create the shape return this.createElement('shape').attr(attr); }, /** * Create and return a circle element. In VML circles are implemented as * shapes, which is faster than v:oval * @param {Number} x * @param {Number} y * @param {Number} r */ circle: function (x, y, r) { var circle = this.symbol('circle'); if (isObject(x)) { r = x.r; y = x.y; x = x.x; } circle.isCircle = true; // Causes x and y to mean center (#1682) circle.r = r; return circle.attr({ x: x, y: y }); }, /** * Create a group using an outer div and an inner v:group to allow rotating * and flipping. A simple v:group would have problems with positioning * child HTML elements and CSS clip. * * @param {String} name The name of the group */ g: function (name) { var wrapper, attribs; // set the class name if (name) { attribs = { 'className': PREFIX + name, 'class': PREFIX + name }; } // the div to hold HTML and clipping wrapper = this.createElement(DIV).attr(attribs); return wrapper; }, /** * VML override to create a regular HTML image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var obj = this.createElement('img') .attr({ src: src }); if (arguments.length > 1) { obj.attr({ x: x, y: y, width: width, height: height }); } return obj; }, /** * VML uses a shape for rect to overcome bugs and rotation problems */ rect: function (x, y, width, height, r, strokeWidth) { var wrapper = this.symbol('rect'); wrapper.r = isObject(x) ? x.r : r; //return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))); return wrapper.attr( isObject(x) ? x : // do not crispify when an object is passed in (as in column charts) wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)) ); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var parentStyle = parentNode.style; css(element, { flip: 'x', left: pInt(parentStyle.width) - 1, top: pInt(parentStyle.height) - 1, rotation: -90 }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape * * @param {Number} left Left position * @param {Number} top Top position * @param {Number} r Border radius * @param {Object} options Width and height */ rect: function (left, top, width, height, options) { var right = left + width, bottom = top + height, ret, r; // No radius, return the more lightweight square if (!defined(options) || !options.r) { ret = SVGRenderer.prototype.symbols.square.apply(0, arguments); // Has radius add arcs for the corners } else { r = mathMin(options.r, width, height); ret = [ M, left + r, top, L, right - r, top, 'wa', right - 2 * r, top, right, top + 2 * r, right - r, top, right, top + r, L, right, bottom - r, 'wa', right - 2 * r, bottom - 2 * r, right, bottom, right, bottom - r, right - r, bottom, L, left + r, bottom, 'wa', left, bottom - 2 * r, left + 2 * r, bottom, left + r, bottom, left, bottom - r, L, left, top + r, 'wa', left, top, left + 2 * r, top + 2 * r, left, top + r, left + r, top, 'x', 'e' ]; } return ret; } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, horiz = axis.horiz, categories = axis.categories, names = axis.series[0] && axis.series[0].names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, width = (horiz && categories && !labelOptions.step && !labelOptions.staggerLines && !labelOptions.rotation && chart.plotWidth / tickPositions.length) || (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931 isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], css, attr, value = categories ? pick(categories[pos], names && names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; css = extend(css, labelOptions.style); // first call if (!defined(label)) { attr = { align: axis.labelAlign }; if (isNumber(labelOptions.rotation)) { attr.rotation = labelOptions.rotation; } if (width && labelOptions.ellipsis) { attr._clipHeight = axis.len / tickPositions.length; } tick.label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) .attr(attr) // without position absolute, IE export sometimes is wrong .css(css) .add(axis.labelGroup) : null; // update } else if (label) { label.attr({ text: str }) .css(css); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { var label = this.label, axis = this.axis; return label ? ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] : 0; }, /** * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision * detection with overflow logic. */ getLabelSides: function () { var bBox = this.labelBBox, // assume getLabelSize has run at this point axis = this.axis, options = axis.options, labelOptions = options.labels, width = bBox.width, leftSide = width * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] - labelOptions.x; return [-leftSide, width - leftSide]; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (index, xy) { var show = true, axis = this.axis, chart = axis.chart, isFirst = this.isFirst, isLast = this.isLast, x = xy.x, reversed = axis.reversed, tickPositions = axis.tickPositions; if (isFirst || isLast) { var sides = this.getLabelSides(), leftSide = sides[0], rightSide = sides[1], plotLeft = chart.plotLeft, plotRight = plotLeft + axis.len, neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]], neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1]; if ((isFirst && !reversed) || (isLast && reversed)) { // Is the label spilling out to the left of the plot area? if (x + leftSide < plotLeft) { // Align it to plot left x = plotLeft - leftSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + rightSide > neighbourEdge) { show = false; } } } else { // Is the label spilling out to the right of the plot area? if (x + rightSide > plotRight) { // Align it to plot right x = plotRight - rightSide; // Hide it if it now overlaps the neighbour label if (neighbour && x + leftSide < neighbourEdge) { show = false; } } } // Set the modified x position of the label xy.x = x; } return show; }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b, rotation = labelOptions.rotation; x = x + labelOptions.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + labelOptions.y - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for rotation (#1764) if (rotation && axis.side === 2) { y -= baseline - baseline * mathCos(rotation * deg2rad); } // Vertically centered if (!defined(labelOptions.y) && !rotation) { // #1951 y += baseline - label.getBBox().height / 2; } // Correct for staggered labels if (staggerLines) { y += (index / (step || 1) % staggerLines) * (axis.labelOffset / staggerLines); } return { x: x, y: y }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = options[tickPrefix + 'Width'] || 0, tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1, // #1480, #1687 staggerLines = axis.staggerLines; this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) { show = false; } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ function PlotLineOrBand(axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } } PlotLineOrBand.prototype = { /** * Render the plot line or plot band. If it is already existing, * move it. */ render: function () { var plotLine = this, axis = plotLine.axis, horiz = axis.horiz, halfPointRange = (axis.pointRange || 0) / 2, options = plotLine.options, optionsLabel = options.label, label = plotLine.label, width = options.width, to = options.to, from = options.from, isBand = defined(from) && defined(to), value = options.value, dashStyle = options.dashStyle, svgElem = plotLine.svgElem, path = [], addEvent, eventType, xs, ys, x, y, color = options.color, zIndex = options.zIndex, events = options.events, attribs, renderer = axis.chart.renderer; // logarithmic conversion if (axis.isLog) { from = log2lin(from); to = log2lin(to); value = log2lin(value); } // plot line if (width) { path = axis.getPlotLinePath(value, width); attribs = { stroke: color, 'stroke-width': width }; if (dashStyle) { attribs.dashstyle = dashStyle; } } else if (isBand) { // plot band // keep within plot area from = mathMax(from, axis.min - halfPointRange); to = mathMin(to, axis.max + halfPointRange); path = axis.getPlotBandPath(from, to, options); attribs = { fill: color }; if (options.borderWidth) { attribs.stroke = options.borderColor; attribs['stroke-width'] = options.borderWidth; } } else { return; } // zIndex if (defined(zIndex)) { attribs.zIndex = zIndex; } // common for lines and bands if (svgElem) { if (path) { svgElem.animate({ d: path }, null, svgElem.onGetPath); } else { svgElem.hide(); svgElem.onGetPath = function () { svgElem.show(); }; } } else if (path && path.length) { plotLine.svgElem = svgElem = renderer.path(path) .attr(attribs).add(); // events if (events) { addEvent = function (eventType) { svgElem.on(eventType, function (e) { events[eventType].apply(plotLine, [e]); }); }; for (eventType in events) { addEvent(eventType); } } } // the plot band/line label if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) { // apply defaults optionsLabel = merge({ align: horiz && isBand && 'center', x: horiz ? !isBand && 4 : 10, verticalAlign : !horiz && isBand && 'middle', y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4, rotation: horiz && !isBand && 90 }, optionsLabel); // add the SVG element if (!label) { plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr({ align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation, zIndex: zIndex }) .css(optionsLabel.style) .add(); } // get the bounding box and align the label xs = [path[1], path[4], pick(path[6], path[1])]; ys = [path[2], path[5], pick(path[7], path[2])]; x = arrayMin(xs); y = arrayMin(ys); label.align(optionsLabel, false, { x: x, y: y, width: arrayMax(xs) - x, height: arrayMax(ys) - y }); label.show(); } else if (label) { // move out of sight label.hide(); } // chainable return plotLine; }, /** * Remove the plot line or band */ destroy: function () { // remove it from the lookup erase(this.axis.plotLinesAndBands, this); delete this.axis; destroyObjectProperties(this); } }; /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption, stacking) { var inverted = axis.chart.inverted; this.axis = axis; // Tells if the stack is negative this.isNegative = isNegative; // Save the options to be able to style the label this.options = options; // Save the x value to be able to position the label later this.x = x; // Initialize total value this.total = null; // This will keep each points' extremes stored by series.index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; this.percent = stacking === 'percent'; // The align options and text align varies on whether the stack is negative and // if the chart is inverted or not. // First test the user supplied value, then use the dynamic. this.alignOptions = { align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'), verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')), y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)), x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0) }; this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center'); } StackItem.prototype = { destroy: function () { destroyObjectProperties(this, this.axis); }, /** * Renders the stack total label and adds it to the stack label group. */ render: function (group) { var options = this.options, formatOption = options.format, str = formatOption ? format(formatOption, this) : options.formatter.call(this); // format the text in the label // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden if (this.label) { this.label.attr({text: str, visibility: HIDDEN}); // Create new label } else { this.label = this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries .css(options.style) // apply style .attr({ align: this.textAlign, // fix the text-anchor rotation: options.rotation, // rotation visibility: HIDDEN // hidden until setOffset is called }) .add(group); // add to the labels-group } }, /** * Sets the offset that the stack has from the x value and repositions the label. */ setOffset: function (xOffset, xWidth) { var stackItem = this, axis = stackItem.axis, chart = axis.chart, inverted = chart.inverted, neg = this.isNegative, // special treatment is needed for negative stacks y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates yZero = axis.translate(0), // stack origin h = mathAbs(y - yZero), // stack height x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position plotHeight = chart.plotHeight, stackBox = { // this is the box for the complete stack x: inverted ? (neg ? y : y - h) : x, y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y), width: inverted ? h : xWidth, height: inverted ? xWidth : h }, label = this.label, alignAttr; if (label) { label.align(this.alignOptions, null, stackBox); // align the label to the box // Set visibility (#678) alignAttr = label.alignAttr; label.attr({ visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }); } } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ function Axis() { this.init.apply(this, arguments); } Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#C0C0C0', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: defaultLabelOptions, // { step: null }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 5, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#4d759e', //font: defaultFont.replace('normal', 'bold') fontWeight: 'bold' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return numberFormat(this.total, -1); }, style: defaultLabelOptions.style } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -8, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 8, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { x: 0, y: 14 // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for left axes */ defaultTopAxisOptions: { labels: { x: 0, y: -5 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.xOrY = isXAxis ? 'x' : 'y'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series //axis.ignoreMaxPadding = UNDEFINED; axis.chart = chart; axis.reversed = options.reversed; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0; // Major ticks axis.ticks = {}; // Minor ticks axis.minorTicks = {}; //axis.tickAmount = UNDEFINED; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; // Dictionary for stacks max values axis.stackExtremes = {}; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() chart.axes.push(axis); chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053) userOptions ) ); }, /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = this.userMin = this.userMax = UNDEFINED; // #1611, #2306 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.xOrY + 'Axis'; // xAxis or yAxis // Remove associated series each(this.series, function (series) { series.remove(false); }); // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && numericSymbols[i] !== null) { ret = numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (value >= 1000) { // add thousands separators ret = numberFormat(value, 0); } else { // small numbers ret = numberFormat(value, -1); } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // reset dataMin and dataMax in case we're redrawing axis.dataMin = axis.dataMax = null; // reset cached stacking extremes axis.stackExtremes = {}; axis.buildStacks(); // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { if (axis.dataMin >= threshold) { axis.dataMin = threshold; axis.ignoreMinPadding = true; } else if (axis.dataMax < threshold) { axis.dataMax = threshold; axis.ignoreMaxPadding = true; } } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this, axisLength = axis.len, sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axisLength; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * axisLength; } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (postTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (postTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, translatedValue = axis.translate(value, null, null, old), cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB; x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; if (x1 < axisLeft || x1 > axisLeft + axis.width) { skip = true; } } else { x1 = axisLeft; x2 = cWidth - axis.right; if (y1 < axisTop || y1 > axisTop + axis.height) { skip = true; } } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0); }, /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to), path = this.getPlotLinePath(from); if (path && toPath) { path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Set the tick positions of a logarithmic axis */ getLogTickPositions: function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max)) { // #1670 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, len; if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( getTimeTicks( normalizeTimeTickInterval(minorTickInterval), axis.min, axis.max, options.startOfWeek ) ); if (minorTickPositions[0] < axis.min) { minorTickPositions.shift(); } } else { for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) { minorTickPositions.push(pos); } } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { var minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, transA = axis.transA; // adjust translation for padding if (axis.isXAxis) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = series.pointRange, pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; if (seriesPointRange > range) { // #1446 seriesPointRange = 0; } pointRange = mathMax(pointRange, seriesPointRange); // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); // Set the closestPointRange if (!series.noSharedTooltip && defined(seriesClosestPointRange)) { closestPointRange = defined(closestPointRange) ? mathMin(closestPointRange, seriesClosestPointRange) : seriesClosestPointRange; } }); } // Record minPointOffset and pointRangePadding ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853 axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection; axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection; // pointRange means the width reserved for each point, like in a column chart axis.pointRange = mathMin(pointRange, range); // closestPointRange means the closest distance between points. In columns // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange // is some other value axis.closestPointRange = closestPointRange; } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickPositions: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, tickPositioner = axis.options.tickPositioner, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickIntervalOption = options.minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, tickPositions, keepTwoTicksOnly, categories = axis.categories; // linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } } else { // initial min and max from the extreme data values axis.min = pick(axis.userMin, options.min, axis.dataMin); axis.max = pick(axis.userMax, options.max, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934 axis.max = correctFloat(log2lin(axis.max)); } // handle zoomed range if (axis.range) { axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618 axis.userMax = axis.max; if (secondPass) { axis.range = null; // don't use it when running setExtremes } } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) { axis.min -= length * minPadding; } if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) { axis.max += length * maxPadding; } } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); // For squished axes, set only two ticks if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial) { keepTwoTicksOnly = true; axis.tickInterval /= 4; // tick extremes closer to the real values } } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) if (axis.pointRange) { axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval); } // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) { axis.tickInterval = minTickIntervalOption; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog) { // linear if (!tickIntervalOption) { axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options); } } // get minorTickInterval axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ? axis.tickInterval / 5 : options.minorTickInterval; // find the tick positions axis.tickPositions = tickPositions = options.tickPositions ? [].concat(options.tickPositions) : // Work on a copy (#1565) (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max])); if (!tickPositions) { // Too many ticks if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) { error(19, true); } if (isDatetimeAxis) { tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)( normalizeTimeTickInterval(axis.tickInterval, options.units), axis.min, axis.max, options.startOfWeek, axis.ordinalPositions, axis.closestPointRange, true ); } else if (isLog) { tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max); } else { tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max); } if (keepTwoTicksOnly) { tickPositions.splice(1, tickPositions.length - 2); } axis.tickPositions = tickPositions; } if (!isLinked) { // reset min/max or remove extremes based on start/end on tick var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = axis.minPointOffset || 0, singlePad; if (options.startOnTick) { axis.min = roundedMin; } else if (axis.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (options.endOnTick) { axis.max = roundedMax; } else if (axis.max + minPointOffset < roundedMax) { tickPositions.pop(); } // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (tickPositions.length === 1) { singlePad = 0.001; // The lowest possible number to avoid extra padding on columns axis.min -= singlePad; axis.max += singlePad; } } }, /** * Set the max ticks of either the x and y axis collection */ setMaxTicks: function () { var chart = this.chart, maxTicks = chart.maxTicks || {}, tickPositions = this.tickPositions, key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-'); if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) { maxTicks[key] = tickPositions.length; } chart.maxTicks = maxTicks; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var axis = this, chart = axis.chart, key = axis._maxTicksKey, tickPositions = axis.tickPositions, maxTicks = chart.maxTicks; if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale var oldTickAmount = axis.tickAmount, calculatedTickAmount = tickPositions.length, tickAmount; // set the axis-level tickAmount to use below axis.tickAmount = tickAmount = maxTicks[key]; if (calculatedTickAmount < tickAmount) { while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + axis.tickInterval )); } axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1); axis.max = tickPositions[tickPositions.length - 1]; } if (defined(oldTickAmount) && tickAmount !== oldTickAmount) { axis.isDirty = true; } } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, stacks = axis.stacks, type, i, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { // reset stacks if (!axis.isXAxis) { for (type in stacks) { delete stacks[type]; } } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickPositions(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (!axis.isXAxis) { if (axis.oldStacks) { stacks = axis.stacks = axis.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } // Set the maximum tick amount axis.setMaxTicks(); }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; // Mark for running afterSetExtremes axis.isDirtyExtremes = true; // redraw if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { // Prevent pinch zooming out of range. Check for defined is for #1946. if (!this.allowZoomOutside) { if (defined(this.dataMin) && newMin <= this.dataMin) { newMin = UNDEFINED; } if (defined(this.dataMax) && newMax >= this.dataMax) { newMax = UNDEFINED; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width, height, top, left; // Expose basic values to use in Series object and navigator this.left = left = pick(options.left, chart.plotLeft + offsetLeft); this.top = top = pick(options.top, chart.plotTop); this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight); this.height = height = pick(options.height, chart.plotHeight); this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog; var realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; if (realMin > threshold || threshold === null) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, addPlotBand: function (options) { this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { this.addPlotBandOrLine(options, 'plotLines'); }, /** * Add a plot band or plot line after render time * * @param options {Object} The plotBand or plotLine configuration object */ addPlotBandOrLine: function (options, coll) { var obj = new PlotLineOrBand(this, options).render(), userOptions = this.userOptions; if (obj) { // #2189 // Add it to the user options for exporting and Axis.update if (coll) { userOptions[coll] = userOptions[coll] || []; userOptions[coll].push(options); } this.plotLinesAndBands.push(obj); } return obj; }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, directionFactor = [-1, 1, 1, -1][side], n, i, autoStaggerLines = 1, maxStaggerLines = pick(labelOptions.maxStaggerLines, 5), sortedPositions, lastRight, overlap, pos, bBox, x, w, lineNo; // For reuse in Axis.render axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions)); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .add(); } if (hasData || axis.isLinked) { // Set the explicit or automatic label alignment axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation)); each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); // Handle automatic stagger lines if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) { sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions; while (autoStaggerLines < maxStaggerLines) { lastRight = []; overlap = false; for (i = 0; i < sortedPositions.length; i++) { pos = sortedPositions[i]; bBox = ticks[pos].label && ticks[pos].label.getBBox(); w = bBox ? bBox.width : 0; lineNo = i % autoStaggerLines; if (w) { x = axis.translate(pos); // don't handle log if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) { overlap = true; } lastRight[lineNo] = x + w; } } if (overlap) { autoStaggerLines++; } else { break; } } if (autoStaggerLines > 1) { axis.staggerLines = autoStaggerLines; } } each(tickPositions, function (pos) { // left side must be align: right and right side must have align: left for labels if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) { // get the highest offset labelOffset = mathMax( ticks[pos].getLabelSize(), labelOffset ); } }); if (axis.staggerLines) { labelOffset *= axis.staggerLines; axis.labelOffset = labelOffset; } } else { // doesn't have data for (n in ticks) { ticks[n].destroy(); delete ticks[n]; } } if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) { if (!axis.axisTitle) { axis.axisTitle = renderer.text( axisTitleOptions.text, 0, 0, axisTitleOptions.useHTML ) .attr({ zIndex: 7, rotation: axisTitleOptions.rotation || 0, align: axisTitleOptions.textAlign || { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align] }) .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10); titleOffsetOption = axisTitleOptions.offset; } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.axisTitleMargin = pick(titleOffsetOption, labelOffset + titleMargin + (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x']) ); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset ); clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis : offAxis + (opposite ? this.width : 0) + offset + (axisTitleOptions.x || 0), // x y: horiz ? offAxis - (opposite ? this.height : 0) + offset : alongAxis + (axisTitleOptions.y || 0) // y }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, stacks = axis.stacks, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), hasData = axis.hasData, showAxis = axis.showAxis, from, to; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (hasData || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) { // Reorganize the indices i = (i === tickPositions.length - 1) ? 0 : i + 1; // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true); } ticks[pos].render(i, false, 1); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && axis.min === 0) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { if (i % 2 === 0 && pos < axis.max) { if (!alternateBands[pos]) { alternateBands[pos] = new PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max; alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them if (coll === alternateBands || !chart.hasRendered || !delay) { destroyInactiveItems(); } else if (delay) { setTimeout(destroyInactiveItems, delay); } }); // Static items. As the axis group is cleared on subsequent calls // to render, these items are added outside the group. // axis line if (lineWidth) { linePath = axis.getLinePath(lineWidth); if (!axis.axisLine) { axis.axisLine = renderer.path(linePath) .attr({ stroke: options.lineColor, 'stroke-width': lineWidth, zIndex: 7 }) .add(axis.axisGroup); } else { axis.axisLine.animate({ d: linePath }); } // show or hide the line depending on options.showEmpty axis.axisLine[showAxis ? 'show' : 'hide'](); } if (axisTitle && showAxis) { axisTitle[axisTitle.isNew ? 'attr' : 'animate']( axis.getTitlePosition() ); axisTitle.isNew = false; } // Stacked totals: if (stackLabelOptions && stackLabelOptions.enabled) { var stackKey, oneStack, stackCategory, stackTotalGroup = axis.stackTotalGroup; // Create a separate group for the stack total labels if (!stackTotalGroup) { axis.stackTotalGroup = stackTotalGroup = renderer.g('stack-labels') .attr({ visibility: VISIBLE, zIndex: 6 }) .add(); } // plotLeft/Top will change when y axis gets wider so we need to translate the // stackTotalGroup at every render call. See bug #506 and #516 stackTotalGroup.translate(chart.plotLeft, chart.plotTop); // Render each stack total for (stackKey in stacks) { oneStack = stacks[stackKey]; for (stackCategory in oneStack) { oneStack[stackCategory].render(stackTotalGroup); } } } // End stacked totals axis.isDirty = false; }, /** * Remove a plot band or plot line from the chart by id * @param {Object} id */ removePlotBandOrLine: function (id) { var plotLinesAndBands = this.plotLinesAndBands, options = this.options, userOptions = this.userOptions, i = plotLinesAndBands.length; while (i--) { if (plotLinesAndBands[i].id === id) { plotLinesAndBands[i].destroy(); } } each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) { i = arr.length; while (i--) { if (arr[i].id === id) { erase(arr, arr[i]); } } }); }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { var axis = this, chart = axis.chart, pointer = chart.pointer; // hide tooltip and hover states if (pointer.reset) { pointer.reset(true); } // render the axis axis.render(); // move plot lines and bands each(axis.plotLinesAndBands, function (plotLine) { plotLine.render(); }); // mark associated series as dirty and ready for redraw each(axis.series, function (series) { series.isDirty = true; }); }, /** * Build the stacks from top down */ buildStacks: function () { var series = this.series, i = series.length; if (!this.isXAxis) { while (i--) { series[i].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); } }; // end Axis /** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ function Tooltip() { this.init.apply(this, arguments); } Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -999 }); // #2301 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.destroy(); } }); // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden; // get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY }); // move to the intermediate value tooltip.label.attr(now); // run on next tick of the mouse tracker if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) { // never allow two timeouts clearTimeout(this.tooltipTimeout); // set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function () { var tooltip = this, hoverPoints; clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766) if (!this.isHidden) { hoverPoints = this.chart.hoverPoints; this.hideTimer = setTimeout(function () { tooltip.label.fadeOut(); tooltip.isHidden = true; }, pick(this.options.hideDelay, 500)); // hide previous hoverPoints and set new if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } this.chart.hoverPoints = null; } }, /** * Hide the crosshairs */ hideCrosshairs: function () { each(this.crosshairs, function (crosshair) { if (crosshair) { crosshair.hide(); } }); }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotX = 0, plotY = 0, yAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; plotX += point.plotX; plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { // Set up the variables var chart = this.chart, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, distance = pick(this.options.distance, 12), pointX = point.plotX, pointY = point.plotY, x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance), y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip alignedRight; // It is too far to the left, adjust it if (x < 7) { x = plotLeft + mathMax(pointX, 0) + distance; } // Test to see if the tooltip is too far to the right, // if it is, move it back to be inside and then up to not cover the point. if ((x + boxWidth) > (plotLeft + plotWidth)) { x -= (x + boxWidth) - (plotLeft + plotWidth); y = pointY - boxHeight + plotTop - distance; alignedRight = true; } // If it is now above the plot area, align it to the top of the plot area if (y < plotTop + 5) { y = plotTop + 5; // If the tooltip is still covering the point, move it below instead if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) { y = pointY + plotTop + distance; // below } } // Now if the tooltip is below the chart, move it up. It's better to cover the // point than to disappear outside the chart. #834. if (y + boxHeight > plotTop + plotHeight) { y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below } return {x: x, y: y}; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), series = items[0].series, s; // build the header s = [series.tooltipHeaderFormatter(items[0])]; // build the values each(items, function (item) { series = item.series; s.push((series.tooltipFormatter && series.tooltipFormatter(item)) || item.point.tooltipFormatter(series.tooltipOptions.pointFormat)); }); // footer s.push(tooltip.options.footerFormat || ''); return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, crosshairsOptions = options.crosshairs, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y }); this.isHidden = false; } // crosshairs if (crosshairsOptions) { crosshairsOptions = splat(crosshairsOptions); // [x, y] var path, i = crosshairsOptions.length, attribs, axis, val, series; while (i--) { series = point.series; axis = series[i ? 'yAxis' : 'xAxis']; if (crosshairsOptions[i] && axis) { val = i ? pick(point.stackY, point.y) : point.x; // #814 if (axis.isLog) { // #1671 val = log2lin(val); } if (i === 1 && series.modifyValue) { // #1205, #2316 val = series.modifyValue(val); } path = axis.getPlotLinePath( val, 1 ); if (tooltip.crosshairs[i]) { tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE }); } else { attribs = { 'stroke-width': crosshairsOptions[i].width || 1, stroke: crosshairsOptions[i].color || '#C0C0C0', zIndex: crosshairsOptions[i].zIndex || 2 }; if (crosshairsOptions[i].dashStyle) { attribs.dashstyle = crosshairsOptions[i].dashStyle; } tooltip.crosshairs[i] = chart.renderer.path(path) .attr(attribs) .add(); } } } } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y), point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); } }; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ function Pointer(chart, options) { this.init(chart, options); } Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || win.event; if (!e.target) { e.target = e.srcElement; } // Framework specific normalizing (#1165) e = washMouseEvent(e); // iOS ePos = e.touches ? e.touches.item(0) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * Return the index in the tooltipPoints array, corresponding to pixel position in * the plot area. */ getIndex: function (e) { var chart = this.chart; return chart.inverted ? chart.plotHeight + chart.plotTop - e.chartY : e.chartX - chart.plotLeft; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, point, points, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, j, distance = chart.chartWidth, index = pointer.getIndex(e), anchor; // shared tooltip if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) { points = []; // loop over all series and find the ones with points closest to the mouse i = series.length; for (j = 0; j < i; j++) { if (series[j].visible && series[j].options.enableMouseTracking !== false && !series[j].noSharedTooltip && series[j].tooltipPoints.length) { point = series[j].tooltipPoints[index]; if (point && point.series) { // not a dummy point, #1544 point._dist = mathAbs(index - point.clientX); distance = mathMin(distance, point._dist); points.push(point); } } } // remove furthest points i = points.length; while (i--) { if (points[i]._dist > distance) { points.splice(i, 1); } } // refresh the tooltip if necessary if (points.length && (points[0].clientX !== pointer.hoverX)) { tooltip.refresh(points, e); pointer.hoverX = points[0].clientX; } } // separate tooltip and general mouse events if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker // get the point point = hoverSeries.tooltipPoints[index]; // a new point is hovered, refresh the tooltip if (point && point !== hoverPoint) { // trigger the events point.onMouseOver(e); } } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(); tooltip.hideCrosshairs(); } pointer.hoverX = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // TODO: implement clipping for inverted charts clip[xy] = clipXY - plotLeftTop; clip[wh] = selectionWH; } scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY; transformScale = inverted ? 1 / scale : scale; selectionMarker[wh] = selectionWH; selectionMarker[xy] = selectionXY; transform[scaleKey] = scale; transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start)); }, /** * Handle touch events with two touches */ pinch: function (e) { var self = this, chart = self.chart, pinchDown = self.pinchDown, followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, zoomHor = self.zoomHor || self.pinchHor, zoomVert = self.zoomVert || self.pinchVert, hasZoom = zoomHor || zoomVert, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || chart.runChartClick), clip = {}; // On touch devices, only proceed to trigger click if a handler is defined if ((hasZoom || followTouchMove) && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(axis.dataMin), max = axis.toPixels(axis.dataMax), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop }, chart.plotBox); } if (zoomHor) { self.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (zoomVert) { self.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } } }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY; // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) { if (!this.selectionMarker) { this.selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (this.selectionMarker && zoomHor) { size = chartX - mouseDownX; this.selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (this.selectionMarker && zoomVert) { size = chartY - mouseDownY; this.selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !this.selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.x, selectionTop = selectionBox.y, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled) { var horiz = axis.horiz, selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)), selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height)); if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859 selectionData[axis.xOrY + 'Axis'].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes, max: mathMax(selectionMin, selectionMax) }); runZoom = true; } } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { this.drop(e); }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition, hoverSeries = chart.hoverSeries; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { this.reset(); this.chartPosition = null; // also reset the chart position, used in #149 fix }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; // normalize e = this.normalize(e); // #295 e.returnValue = false; if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries; if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) { series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop, inverted = chart.inverted, chartPosition, plotX, plotY; e = this.normalize(e); e.cancelBubble = true; // IE specific if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { chartPosition = this.chartPosition; plotX = hoverPoint.plotX; plotY = hoverPoint.plotY; // add page position info extend(hoverPoint, { pageX: chartPosition.left + plotLeft + (inverted ? chart.plotWidth - plotY : plotX), pageY: chartPosition.top + plotTop + (inverted ? chart.plotHeight - plotX : plotY) }); // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, onContainerTouchStart: function (e) { var chart = this.chart; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { // Prevent the click pseudo event from firing unless it is set in the options /*if (!chart.runChartClick) { e.preventDefault(); }*/ // Run mouse events and display tooltip etc this.runPointActions(e); this.pinch(e); } else { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchMove: function (e) { if (e.touches.length === 1 || e.touches.length === 2) { this.pinch(e); } }, onDocumentTouchEnd: function (e) { this.drop(e); }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container, events; this._events = events = [ [container, 'onmousedown', 'onContainerMouseDown'], [container, 'onmousemove', 'onContainerMouseMove'], [container, 'onclick', 'onContainerClick'], [container, 'mouseleave', 'onContainerMouseLeave'], [doc, 'mousemove', 'onDocumentMouseMove'], [doc, 'mouseup', 'onDocumentMouseUp'] ]; if (hasTouch) { events.push( [container, 'ontouchstart', 'onContainerTouchStart'], [container, 'ontouchmove', 'onContainerTouchMove'], [doc, 'touchend', 'onDocumentTouchEnd'] ); } each(events, function (eventConfig) { // First, create the callback function that in turn calls the method on Pointer pointer['_' + eventConfig[2]] = function (e) { pointer[eventConfig[2]](e); }; // Now attach the function, either as a direct property or through addEvent if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]]; } else { addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var pointer = this; // Release all DOM events each(pointer._events, function (eventConfig) { if (eventConfig[1].indexOf('on') === 0) { eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE } else { removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]); } }); delete pointer._events; // memory and CPU leak clearInterval(pointer.tooltipTimeout); } }; /** * The overview of the chart's series */ function Legend(chart, options) { this.init(chart, options); } Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding = pick(options.padding, 8), itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding; legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.lastLineHeight = 0; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? item.color : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { stroke: symbolColor, fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox; if (item.legendGroup) { item.legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; if (alignAttr) { translateY = alignAttr.translateY; each(this.allItems, function (item) { var checkbox = item.checkbox, top; if (checkbox) { top = (translateY + checkbox.y + (scrollOffset || 0) + 3); css(checkbox, { left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = options.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 8) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series || item, itemOptions = series.options, showCheckbox = itemOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item), ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? li : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); li.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { li.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { item.setVisible(); }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (itemOptions && showCheckbox) { item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, options.itemCheckboxStyle, chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item, 'checkboxClick', { checked: target.checked }, function () { item.select(); } ); }); } } // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.legendItemWidth = options.itemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = bBox.height; // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = []; each(chart.series, function (serie) { var seriesOptions = serie.options; if (!seriesOptions.showInLegend || defined(seriesOptions.linkedTo)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( serie.legendItems || (seriesOptions.legendType === 'point' ? serie.data : serie) ); }); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items each(allItems, function (item) { legend.renderItem(item); }); // Draw the border legendWidth = options.width || legend.offsetWidth; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); if (legendBorderWidth || legendBackgroundColor) { legendWidth += padding; legendHeight += padding; if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp(null, null, null, legendWidth, legendHeight) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, pageCount, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle if (legendHeight > spaceHeight && !options.useHTML) { this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight; this.pageCount = pageCount = mathCeil(legendHeight / clipHeight); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, 0, 9999, 0); legend.contentGroup.clip(clipRect); } clipRect.attr({ height: clipHeight }); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipRect.attr({ height: chart.chartHeight }); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pageCount = this.pageCount, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + this.pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1; this.scrollGroup.animate({ translateY: scrollOffset }); pager.attr({ text: currentPage + '/' + pageCount }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview. // TODO: When IE11 is released, check again for this bug, and remove the fix // or make a better one. if (/Trident.*?11\.0/.test(userAgent)) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this; setTimeout(function () { proceed.call(legend, item); }); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ function Chart() { this.init.apply(this, arguments); } Chart.prototype = { /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = 0; chart.counters = new ChartCounters(); chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, axis; /*jslint unused: false*/ axis = new Axis(this, merge(options, { index: this[key].length, isX: isX })); /*jslint unused: true*/ // Push the new axis options to the chart options chartOptions[key] = splat(chartOptions[key] || {}); chartOptions[key].push(options); if (pick(redraw, true)) { this.redraw(animation); } }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Adjust all axes tick amounts */ adjustTickAmounts: function () { if (this.options.chart.alignTicks !== false) { each(this.axes, function (axis) { axis.adjustTickAmount(); }); } this.maxTicks = null; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed? seriesLength = series.length, i = seriesLength, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = []; setAnimation(animation, chart); if (isHiddenChart) { chart.cloneRenderTo(); } // Adjust title layout (reflow multiline text) chart.layOutTitles(); // link stacked series while (i--) { serie = series[i]; if (serie.options.stacking) { hasStackedSeries = true; if (serie.isDirty) { hasDirtyStacks = true; break; } } } if (hasDirtyStacks) { // mark others as dirty i = seriesLength; while (i--) { serie = series[i]; if (serie.options.stacking) { serie.isDirty = true; } } } // handle updated data in the series each(series, function (serie) { if (serie.isDirty) { // prepare the data so axis can read it if (serie.options.legendType === 'point') { redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (chart.hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } chart.adjustTickAmounts(); chart.getMargins(); // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set if (axis.isDirtyExtremes) { // #821 axis.isDirtyExtremes = false; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer && pointer.reset) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw if (isHiddenChart) { chart.cloneRenderTo(true); } // Fire callbacks that are put on hold until after the redraw each(afterRedraw, function (callback) { callback.call(); }); }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv; var loadingOptions = options.loading; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '', left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; }, /** * Get an axis, series or point object by id. * @param id {String} The id as given in the configuration options */ get: function (id) { var chart = this, axes = chart.axes, series = chart.series; var i, j, points; // search axes for (i = 0; i < axes.length; i++) { if (axes[i].options.id === id) { return axes[i]; } } // search series for (i = 0; i < series.length; i++) { if (series[i].options.id === id) { return series[i]; } } // search points for (i = 0; i < series.length; i++) { points = series[i].points || []; for (j = 0; j < points.length; j++) { if (points[j].id === id) { return points[j]; } } } return null; }, /** * Create the Axis instances based on the config options */ getAxes: function () { var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray, axis; // make sure the options are arrays and add some members each(xAxisOptions, function (axis, i) { axis.index = i; axis.isX = true; }); each(yAxisOptions, function (axis, i) { axis.index = i; }); // concatenate all axis options into one array optionsArray = xAxisOptions.concat(yAxisOptions); each(optionsArray, function (axisOptions) { axis = new Axis(chart, axisOptions); }); chart.adjustTickAmounts(); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Generate stacks for each series and calculate stacks total values */ getStacks: function () { var chart = this; // reset stacks for each yAxis each(chart.yAxis, function (axis) { if (axis.stacks && axis.hasVisibleSeries) { axis.oldStacks = axis.stacks; } }); each(chart.series, function (series) { if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) { series.stackKey = series.type + pick(series.options.stack, ''); } }); }, /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover) .attr({ align: btnOptions.position.align, title: lang.resetZoomTitle }) .add() .align(btnOptions.position, false, alignTo); }, /** * Zoom out to 1:1 */ zoomOut: function () { var chart = this; fireEvent(chart, 'selection', { resetSelection: true }, function () { chart.zoom(); }); }, /** * Zoom into a given portion of the chart given by axis coordinates * @param {Object} event */ zoom: function (event) { var chart = this, hasZoomed, pointer = chart.pointer, displayButton = false, resetZoomButton; // If zoom is called with no arguments, reset the axes if (!event || event.resetSelection) { each(chart.axes, function (axis) { hasZoomed = axis.zoom(); }); } else { // else, zoom in on all axes each(event.xAxis.concat(event.yAxis), function (axisData) { var axis = axisData.axis, isXAxis = axis.isXAxis; // don't zoom more than minRange if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) { hasZoomed = axis.zoom(axisData.min, axisData.max); if (axis.displayBtn) { displayButton = true; } } }); } // Show or hide the Reset zoom button resetZoomButton = chart.resetZoomButton; if (displayButton && !resetZoomButton) { chart.showResetZoom(); } else if (!displayButton && isObject(resetZoomButton)) { chart.resetZoomButton = resetZoomButton.destroy(); } // Redraw if (hasZoomed) { chart.redraw( pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation ); } }, /** * Pan the chart by dragging the mouse across the pane. This function is called * on mouse move, and the distance to pan is computed from chartX compared to * the first chartX position in the dragging operation. */ pan: function (e, panning) { var chart = this, hoverPoints = chart.hoverPoints, doRedraw; // remove active points for shared tooltip if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps var mousePos = e[isX ? 'chartX' : 'chartY'], axis = chart[isX ? 'xAxis' : 'yAxis'][0], startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'], halfPointRange = (axis.pointRange || 0) / 2, extremes = axis.getExtremes(), newMin = axis.toValue(startPos - mousePos, true) + halfPointRange, newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange; if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function () { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: 15 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; // Adjust for browser consistency + backwards compat after #776 fix if (titleOffset >= 18 && titleOffset <= 25) { titleOffset = 15; } } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } this.titleOffset = titleOffset; // used in getMargins }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) chart.containerWidth = adapterRun(renderTo, 'width'); chart.containerHeight = adapterRun(renderTo, 'height'); chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(optionsChart.height, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, optionsChart = chart.options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, containerId; chart.renderTo = renderTo = optionsChart.renderTo; containerId = PREFIX + idCounter++; if (isString(renderTo)) { chart.renderTo = renderTo = doc.getElementById(renderTo); } // Display an error if the renderTo is wrong if (!renderTo) { error(13, true); } // If the container already holds a chart, destroy it oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex]) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly if (!renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; chart.renderer = optionsChart.forExport ? // force SVG, used for SVG export new SVGRenderer(container, chartWidth, chartHeight, true) : new Renderer(container, chartWidth, chartHeight); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function () { var chart = this, spacing = chart.spacing, axisOffset, legend = chart.legend, margin = chart.margin, legendOptions = chart.options.legend, legendMargin = pick(legendOptions.margin, 10), legendX = legendOptions.x, legendY = legendOptions.y, align = legendOptions.align, verticalAlign = legendOptions.verticalAlign, titleOffset = chart.titleOffset; chart.resetMargins(); axisOffset = chart.axisOffset; // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend if (legend.display && !legendOptions.floating) { if (align === 'right') { // horizontal alignment handled first if (!defined(margin[1])) { chart.marginRight = mathMax( chart.marginRight, legend.legendWidth - legendX + legendMargin + spacing[1] ); } } else if (align === 'left') { if (!defined(margin[3])) { chart.plotLeft = mathMax( chart.plotLeft, legend.legendWidth + legendX + legendMargin + spacing[3] ); } } else if (verticalAlign === 'top') { if (!defined(margin[0])) { chart.plotTop = mathMax( chart.plotTop, legend.legendHeight + legendY + legendMargin + spacing[0] ); } } else if (verticalAlign === 'bottom') { if (!defined(margin[2])) { chart.marginBottom = mathMax( chart.marginBottom, legend.legendHeight - legendY + legendMargin + spacing[2] ); } } } // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { axis.getOffset(); }); } if (!defined(margin[3])) { chart.plotLeft += axisOffset[3]; } if (!defined(margin[0])) { chart.plotTop += axisOffset[0]; } if (!defined(margin[2])) { chart.marginBottom += axisOffset[2]; } if (!defined(margin[1])) { chart.marginRight += axisOffset[1]; } chart.setChartSize(); }, /** * Add the event handlers necessary for auto resizing * */ initReflow: function () { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, reflowTimeout; function reflow(e) { var width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win; // #805 - MooTools doesn't supply e // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && width && height && (target === win || target === doc)) { if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(reflowTimeout); chart.reflowTimeout = reflowTimeout = setTimeout(function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }, 100); } chart.containerWidth = width; chart.containerHeight = height; } } chart.reflow = reflow; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize; // Handle the isResizing counter chart.isResizing += 1; fireEndResize = function () { if (chart) { fireEvent(chart, 'endResize', null, function () { chart.isResizing -= 1; }); } }; // set the animation for the current process setAnimation(animation, chart); chart.oldChartHeight = chart.chartHeight; chart.oldChartWidth = chart.chartWidth; if (defined(width)) { chart.chartWidth = chartWidth = mathMax(0, mathRound(width)); chart.hasUserSize = !!chartWidth; } if (defined(height)) { chart.chartHeight = chartHeight = mathMax(0, mathRound(height)); } css(chart.container, { width: chartWidth + PX, height: chartHeight + PX }); chart.setChartSize(true); chart.renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // fire endResize and set isResizing back // If animation is disabled, fire without delay if (globalAnimation === false) { fireEndResize(); } else { // else set a timeout with the animation duration setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500); } }, /** * Set the public chart properties. This is done before and after the pre-render * to determine margin sizes */ setChartSize: function (skipAxes) { var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth; chart.plotLeft = plotLeft = mathRound(chart.plotLeft); chart.plotTop = plotTop = mathRound(chart.plotTop); chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight)); chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom)); chart.plotSizeX = inverted ? plotHeight : plotWidth; chart.plotSizeY = inverted ? plotWidth : plotHeight; chart.plotBorderWidth = optionsChart.plotBorderWidth || 0; // Set boxes used for alignment chart.spacingBox = renderer.spacingBox = { x: spacing[3], y: spacing[0], width: chartWidth - spacing[3] - spacing[1], height: chartHeight - spacing[0] - spacing[2] }; chart.plotBox = renderer.plotBox = { x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }; plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2); clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2); clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2); chart.clipBox = { x: clipX, y: clipY, width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX), height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this, spacing = chart.spacing, margin = chart.margin; chart.plotTop = pick(margin[0], spacing[0]); chart.marginRight = pick(margin[1], spacing[1]); chart.marginBottom = pick(margin[2], spacing[2]); chart.plotLeft = pick(margin[3], spacing[3]); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight) ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; } } }); }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options; var labels = options.labels, credits = options.credits, creditsHref; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); chart.getStacks(); // render stacks // Get margins by pre-rendering axes // set axes scales each(axes, function (axis) { axis.setScale(); }); chart.getMargins(); chart.maxTicks = null; // reset for second pass each(axes, function (axis) { axis.setTickPositions(true); // update to reflect the new margins axis.setMaxTicks(); }); chart.adjustTickAmounts(); chart.getMargins(); // second pass to check for new labels // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { axis.render(); }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } each(chart.series, function (serie) { serie.translate(); serie.setTooltipPoints(); serie.render(); }); // Labels if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } // Credits if (credits.enabled && !chart.credits) { creditsHref = credits.href; chart.credits = renderer.text( credits.text, 0, 0 ) .on('click', function () { if (creditsHref) { location.href = creditsHref; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } // Set flag chart.hasRendered = true; }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: in spite of JSLint's complaints, win == win.top is required /*jslint eqeq: true*/ if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { /*jslint eqeq: false*/ if (useCanVG) { // Delay rendering until canvg library is downloaded and ready CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL); } else { doc.attachEvent('onreadystatechange', function () { doc.detachEvent('onreadystatechange', chart.firstRender); if (doc.readyState === 'complete') { chart.firstRender(); } }); } return false; } return true; }, /** * Prepare for first rendering after all data are loaded */ firstRender: function () { var chart = this, options = chart.options, callback = chart.callback; // Check whether the chart is ready to render if (!chart.isReadyToRender()) { return; } // Create the container chart.getContainer(); // Run an early event after the container and renderer are established fireEvent(chart, 'init'); chart.resetMargins(); chart.setChartSize(); // Set the common chart properties (mainly invert) from the given series chart.propFromSeries(); // get axes chart.getAxes(); // Initialize the series each(options.series || [], function (serieOptions) { chart.initSeries(serieOptions); }); chart.linkSeries(); // Run an event after axes and series are initialized, but before render. At this stage, // the series data is indexed and cached in the xData and yData arrays, so we can access // those before rendering. Used in Highstock. fireEvent(chart, 'beforeRender'); // depends on inverted and on margins being set chart.pointer = new Pointer(chart, options); chart.render(); // add canvas chart.renderer.draw(); // run callbacks if (callback) { callback.apply(chart, [chart]); } each(chart.callbacks, function (fn) { fn.apply(chart, [chart]); }); // If the chart was rendered outside the top container, put it back in chart.cloneRenderTo(true); fireEvent(chart, 'load'); }, /** * Creates arrays for spacing and margin from given options. */ splashArray: function (target, options) { var oVar = options[target], tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar]; return [pick(options[target + 'Top'], tArray[0]), pick(options[target + 'Right'], tArray[1]), pick(options[target + 'Bottom'], tArray[2]), pick(options[target + 'Left'], tArray[3])]; } }; // end Chart // Hook for exporting module Chart.prototype.callbacks = []; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // If no x is set by now, get auto incremented value. All points must have an // x value, however the y value can be null to create a gap in the series if (point.x === UNDEFINED && series) { point.x = x === UNDEFINED ? series.autoIncrement() : x; } return point; }, /** * Transform number or array configs into objects */ optionsToObject: function (options) { var ret, series = this.series, pointArrayMap = series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret = { y: options }; } else if (isArray(options)) { ret = {}; // with leading x value if (options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { ret[pointArrayMap[j++]] = options[i++]; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { var point = this; return { x: point.category, y: point.y, key: point.name || point.category, series: point.series, point: point, percentage: point.percentage, total: point.total || point.stackTotal }; }, /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the defalut handler point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () { point.selected = point.options.selected = selected; series.options.data[inArray(point, series.data)] = point.options; point.setState(selected && SELECT_STATE); // unselect all other points unless Ctrl or Cmd + click if (!accumulate) { each(chart.getSelectedPoints(), function (loopPoint) { if (loopPoint.selected && loopPoint !== point) { loopPoint.selected = loopPoint.options.selected = false; series.options.data[inArray(loopPoint, series.data)] = loopPoint.options; loopPoint.setState(NORMAL_STATE); loopPoint.firePointEvent('unselect'); } }); } }); }, /** * Runs on mouse over the point */ onMouseOver: function (e) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); chart.hoverPoint = point; }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887 this.firePointEvent('mouseOut'); this.setState(); chart.hoverPoint = null; } }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation) { var point = this, series = point.series, graphic = point.graphic, i, data = series.data, chart = series.chart, seriesOptions = series.options; redraw = pick(redraw, true); // fire the event with a default handler of doing the update point.firePointEvent('update', { options: options }, function () { point.applyOptions(options); // update visuals if (isObject(options)) { series.getAttribs(); if (graphic) { if (options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } else { graphic.attr(point.pointAttr[point.state || '']); } } } // record changes in the parallel arrays i = inArray(point, data); series.xData[i] = point.x; series.yData[i] = series.toYData ? series.toYData(point) : point.y; series.zData[i] = point.z; seriesOptions.data[i] = point.options; // redraw series.isDirty = series.isDirtyData = true; if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320 chart.isDirtyBox = true; } if (seriesOptions.legendType === 'point') { // #1831, #1885 chart.legend.destroyItem(point); } if (redraw) { chart.redraw(animation); } }); }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var point = this, series = point.series, points = series.points, chart = series.chart, i, data = series.data; setAnimation(animation, chart); redraw = pick(redraw, true); // fire the event with a default handler of removing the point point.firePointEvent('remove', null, function () { // splice all the parallel arrays i = inArray(point, data); if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.xData.splice(i, 1); series.yData.splice(i, 1); series.zData.splice(i, 1); point.destroy(); // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }); }, /** * Fire an event on the Point object. Must not be renamed to fireEvent, as this * causes a name clash in MooTools * @param {String} eventType * @param {Object} eventArgs Additional event arguments * @param {Function} defaultFunction Default event handler */ firePointEvent: function (eventType, eventArgs, defaultFunction) { var point = this, series = this.series, seriesOptions = series.options; // load event handlers on demand to save time on mouseover/out if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) { this.importEvents(); } // add default handler if in selection mode if (eventType === 'click' && seriesOptions.allowPointSelect) { defaultFunction = function (event) { // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state) { var point = this, plotX = point.plotX, plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, newSymbol, pointAttr = point.pointAttr; state = state || NORMAL_STATE; // empty string if ( // already has this state state === point.state || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // point marker's state options is disabled (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled))) ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr[state].r; point.graphic.attr(merge( pointAttr[state], radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr[state]) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; // Move the existing graphic } else { stateMarkerGraphic.attr({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide'](); } } point.state = state; } }; /** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, colorCounter: 0, init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // set the data series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123) stableSort(chartSeries, function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, a._i); }); each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; if (series.isCartesian) { each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS]) { error(18, true); } }); } }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var series = this, options = series.options, xIncrement = series.xIncrement; xIncrement = pick(xIncrement, options.pointStart, 0); series.pointInterval = pick(series.pointInterval, options.pointInterval, 1); series.xIncrement = xIncrement + series.pointInterval; return xIncrement; }, /** * Divide the series data into segments divided by null values. */ getSegments: function () { var series = this, lastNull = -1, segments = [], i, points = series.points, pointsLength = points.length; if (pointsLength) { // no action required for [] // if connect nulls, just remove null points if (series.options.connectNulls) { i = pointsLength; while (i--) { if (points[i].y === null) { points.splice(i, 1); } } if (points.length) { segments = [points]; } // else, split on null points } else { each(points, function (point, i) { if (point.y === null) { if (i > lastNull + 1) { segments.push(points.slice(lastNull + 1, i)); } lastNull = i; } else if (i === pointsLength - 1) { // last value segments.push(points.slice(lastNull + 1, i + 1)); } }); } } // register it series.segments = segments; }, /** * Set the series options by merging from the options tree * @param {Object} itemOptions */ setOptions: function (itemOptions) { var chart = this.chart, chartOptions = chart.options, plotOptions = chartOptions.plotOptions, typeOptions = plotOptions[this.type], options; this.userOptions = itemOptions; options = merge( typeOptions, plotOptions.series, itemOptions ); // the tooltip options are merged between global and series specific options this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip); // Delte marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } return options; }, /** * Get the series' color */ getColor: function () { var options = this.options, userOptions = this.userOptions, defaultColors = this.chart.options.colors, counters = this.chart.counters, color, colorIndex; color = options.color || defaultPlotOptions[this.type].color; if (!color && !options.colorByPoint) { if (defined(userOptions._colorIndex)) { // after Series.update() colorIndex = userOptions._colorIndex; } else { userOptions._colorIndex = counters.color; colorIndex = counters.color++; } color = defaultColors[colorIndex]; } this.color = color; counters.wrapColor(defaultColors.length); }, /** * Get the series' symbol */ getSymbol: function () { var series = this, userOptions = series.userOptions, seriesMarkerOption = series.options.marker, chart = series.chart, defaultSymbols = chart.options.symbols, counters = chart.counters, symbolIndex; series.symbol = seriesMarkerOption.symbol; if (!series.symbol) { if (defined(userOptions._symbolIndex)) { // after Series.update() symbolIndex = userOptions._symbolIndex; } else { userOptions._symbolIndex = counters.symbol; symbolIndex = counters.symbol++; } series.symbol = defaultSymbols[symbolIndex]; } // don't substract radius in image symbols (#604) if (/^url/.test(series.symbol)) { seriesMarkerOption.radius = 0; } counters.wrapSymbol(defaultSymbols.length); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLegendSymbol: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendOptions = legend.options, legendSymbol, symbolWidth = legendOptions.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } }, /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, xData = series.xData, yData = series.yData, zData = series.zData, names = series.names, currentShift = (graph && graph.shift) || 0, dataOptions = seriesOptions.data, point, isInTheMiddle, x, i; setAnimation(animation, chart); // Make graph animate sideways if (shift) { each([graph, area, series.graphNeg, series.areaNeg], function (shape) { if (shape) { shape.shift = currentShift + 1; } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } xData.splice(i, 0, x); yData.splice(i, 0, series.toYData ? series.toYData(point) : point.y); zData.splice(i, 0, point.z); if (names) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); xData.shift(); yData.shift(); zData.shift(); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw) { var series = this, oldData = series.points, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, names = xAxis && xAxis.categories && !xAxis.categories.length ? [] : null, i; // reset properties series.xIncrement = null; series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // parallel arrays var xData = [], yData = [], zData = [], dataLength = data ? data.length : [], turboThreshold = pick(options.turboThreshold, 1000), pt, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length, hasToYData = !!series.toYData; // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); xData[i] = pt.x; yData[i] = hasToYData ? series.toYData(pt) : pt.y; zData[i] = pt.z; if (names && pt.name) { names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; series.xData = xData; series.yData = yData; series.zData = zData; series.names = names; // destroy old points i = (oldData && oldData.length) || 0; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(false); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; redraw = pick(redraw, true); if (!series.isRemoving) { /* prevent triggering native event in jQuery (calling the remove function from the remove event) */ series.isRemoving = true; // fire the event with a default handler of removing the point fireEvent(series, 'remove', null, function () { // destroy elements series.destroy(); // redraw chart.isDirtyLegend = chart.isDirtyBox = true; chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } series.isRemoving = false; }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, isCartesian = series.isCartesian; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { var min = xAxis.min, max = xAxis.max; // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points for (i = processedXData.length - 1; i >= 0; i--) { distance = processedXData[i] - processedXData[i - 1]; if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) { closestPointRange = distance; // Unsorted data is not supported by the line tooltip, as well as data grouping and // navigation in Stock charts (#725) and width calculation of columns (#1900) } else if (distance < 0 && series.requireSorting) { error(15); } } // Record the properties series.cropped = cropped; // undefined or true series.cropStart = cropStart; series.processedXData = processedXData; series.processedYData = processedYData; if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC series.pointRange = closestPointRange || 1; } series.closestPointRange = closestPointRange; }, /** * Iterate over xData and crop values between min and max. Returns object containing crop start/end * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range */ cropData: function (xData, yData, min, max) { var dataLength = xData.length, cropStart = 0, cropEnd = dataLength, cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside i; // iterate up to find slice start for (i = 0; i < dataLength; i++) { if (xData[i] >= min) { cropStart = mathMax(0, i - cropShoulder); break; } } // proceed to find slice end for (; i < dataLength; i++) { if (xData[i] > max) { cropEnd = i + cropShoulder; break; } } return { xData: xData.slice(cropStart, cropEnd), yData: yData.slice(cropStart, cropEnd), start: cropStart, end: cropEnd }; }, /** * Generate the data point after the data has been processed by cropping away * unused points and optionally grouped in Highcharts Stock. */ generatePoints: function () { var series = this, options = series.options, dataOptions = options.data, data = series.data, dataLength, processedXData = series.processedXData, processedYData = series.processedYData, pointClass = series.pointClass, processedDataLength = processedXData.length, cropStart = series.cropStart || 0, cursor, hasGroupedData = series.hasGroupedData, point, points = [], i; if (!data && !hasGroupedData) { var arr = []; arr.length = dataOptions.length; data = series.data = arr; } for (i = 0; i < processedDataLength; i++) { cursor = cropStart + i; if (!hasGroupedData) { if (data[cursor]) { point = data[cursor]; } else if (dataOptions[cursor] !== UNDEFINED) { // #970 data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]); } points[i] = point; } else { // splat the y data in case of ohlc data array points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i]))); } } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Adds series' points value to corresponding stack */ setStackedPoints: function () { if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) { return; } var series = this, xData = series.processedXData, yData = series.processedYData, stackedYData = [], yDataLength = yData.length, seriesOptions = series.options, threshold = seriesOptions.threshold, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, isNegative, stack, other, key, i, x, y; // loop over the non-null y values and read them into a local array for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // Read stacked values into a stack based on the x value, // the sign of y and the stack key. Stacking is also handled for null values (#739) isNegative = negStacks && y < threshold; key = isNegative ? negKey : stackKey; // Create empty object for this stack if it doesn't exist yet if (!stacks[key]) { stacks[key] = {}; } // Initialize StackItem for this x if (!stacks[key][x]) { if (oldStacks[key] && oldStacks[key][x]) { stacks[key][x] = oldStacks[key][x]; stacks[key][x].total = null; } else { stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption, stacking); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; stack.points[series.index] = [stack.cum || 0]; // Add value to the stack total if (stacking === 'percent') { // Percent stacked column, totals are the same for the positive and negative stacks other = isNegative ? stackKey : negKey; if (negStacks && stacks[other] && stacks[other][x]) { other = stacks[other][x]; stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0; // Percent stacked areas } else { stack.total += mathAbs(y) || 0; } } else { stack.total += y || 0; } stack.cum = (stack.cum || 0) + (y || 0); stack.points[series.index].push(stack.cum); stackedYData[i] = stack.cum; } if (stacking === 'percent') { yAxis.usePercentage = true; } this.stackedYData = stackedYData; // To be used in getExtremes // Reset old stacks yAxis.oldStacks = {}; }, /** * Iterate over all stacks and compute the absolute values to percent */ setPercentStacks: function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks; each([stackKey, '-' + stackKey], function (key) { var i = series.xData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = series.xData[i]; stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[series.index]; if (pointExtremes) { totalFactor = stack.total ? 100 / stack.total : 0; pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value series.stackedYData[i] = pointExtremes[1]; } } }); }, /** * Calculate Y extremes for visible data */ getExtremes: function () { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yData = this.stackedYData || this.processedYData, yDataLength = yData.length, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, dataMin, dataMax, x, y, i, j; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = pick(dataMin, arrayMin(activeYData)); this.dataMax = pick(dataMax, arrayMax(activeYData)); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes if (yAxis.isLog && yValue <= 0) { point.y = yValue = null; } // Get the plotX translation point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { pointStack = stack[xValue]; stackValues = pointStack.points[series.index]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === 0) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.percentage = stacking === 'percent' && yValue; point.total = point.stackTotal = pointStack.total; point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ? //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591 yAxis.translate(yValue, 0, 1, 0, 1) : UNDEFINED; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; } // now that we have the cropped data, build the segments series.getSegments(); }, /** * Memoize tooltip texts and positions */ setTooltipPoints: function (renew) { var series = this, points = [], pointsLength, low, high, xAxis = series.xAxis, xExtremes = xAxis && xAxis.getExtremes(), axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar point, pointX, nextPoint, i, tooltipPoints = []; // a lookup array for each pixel in the x dimension // don't waste resources if tracker is disabled if (series.options.enableMouseTracking === false) { return; } // renew if (renew) { series.tooltipPoints = null; } // concat segments to overcome null values each(series.segments || series.points, function (segment) { points = points.concat(segment); }); // Reverse the points in case the X axis is reversed if (xAxis && xAxis.reversed) { points = points.reverse(); } // Polar needs additional shaping if (series.orderTooltipPoints) { series.orderTooltipPoints(points); } // Assign each pixel position to the nearest point pointsLength = points.length; for (i = 0; i < pointsLength; i++) { point = points[i]; pointX = point.x; if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149 nextPoint = points[i + 1]; // Set this range's low to the last range's high plus one low = high === UNDEFINED ? 0 : high + 1; // Now find the new high high = points[i + 1] ? mathMin(mathMax(0, mathFloor( // #2070 (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2 )), axisLength) : axisLength; while (low >= 0 && low <= high) { tooltipPoints[low++] = point; } } } series.tooltipPoints = tooltipPoints; }, /** * Format the header of the tooltip */ tooltipHeaderFormatter: function (point) { var series = this, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime', headerFormat = tooltipOptions.headerFormat, closestPointRange = xAxis && xAxis.closestPointRange, n; // Guess the best date format based on the closest point distance (#568) if (isDateTime && !xDateFormat) { if (closestPointRange) { for (n in timeUnits) { if (timeUnits[n] >= closestPointRange) { xDateFormat = dateTimeLabelFormats[n]; break; } } } else { xDateFormat = dateTimeLabelFormats.day; } } // Insert the header date format if any if (isDateTime && xDateFormat && isNumber(point.key)) { headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(headerFormat, { point: point, series: series }); }, /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); chart.hoverSeries = null; }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, renderer = chart.renderer, clipRect, markerClipRect, animation = series.options.animation, clipBox = chart.clipBox, inverted = chart.inverted, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } sharedClipKey = '_sharedClip' + animation.duration + animation.easing; // Initialize the animation. Set up the clipping rectangle. if (init) { // If a clipping rectangle with the same properties is currently present in the chart, use that. clipRect = chart[sharedClipKey]; markerClipRect = chart[sharedClipKey + 'm']; if (!clipRect) { chart[sharedClipKey] = clipRect = renderer.clipRect( extend(clipBox, { width: 0 }) ); chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } series.group.clip(clipRect); series.markerGroup.clip(markerClipRect); series.sharedClipKey = sharedClipKey; // Run the animation } else { clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animation.duration); } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { var chart = this.chart, sharedClipKey = this.sharedClipKey, group = this.group; if (group && this.options.clip !== false) { group.clip(chart.clipRect); this.markerGroup.clip(); // no clip } // Remove the shared clipping rectancgle when all series are shown setTimeout(function () { if (sharedClipKey && chart[sharedClipKey]) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } }, 100); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, pointMarkerOptions, enabled, isInside, markerGroup = series.markerGroup; if (seriesMarkerOptions.enabled || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858 // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic .attr({ // Since the marker group isn't clipped, each individual marker must be toggled visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN }) .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions, negativeColor = seriesOptions.negativeColor, defaultLineColor = normalOptions.lineColor, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (point.negative && negativeColor) { point.color = point.fillColor = negativeColor; } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker) { // column, bar, point // if no hover color is given, brighten the normal color pointStateOptionsHover.color = Color(pointStateOptionsHover.color || point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness).get(); } // normal point state inherits series wide normal state pointAttr[NORMAL_STATE] = series.convertAttribs(extend({ color: point.color, // #868 fillColor: point.color, // Individual point color or negative color markers (#2219) lineColor: defaultLineColor === null ? point.color : UNDEFINED // Bubbles take point color, line markers use white }, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, n; // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and reinsert methods from the type prototype this.remove(false); for (n in proto) { // Overwrite series-type specific methods (#2270) if (proto.hasOwnProperty(n)) { this[n] = UNDEFINED; } } extend(this, seriesTypes[newOptions.type || oldType].prototype); this.init(chart, newOptions); if (pick(redraw, true)) { chart.redraw(false); } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(['xAxis', 'yAxis'], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; axis.stacks = {}; // Rebuild stacks when updating (#2229) } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // destroy all SVGElements associated to the series each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker', 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) { if (series[prop]) { // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } }); // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * Draw the data labels */ drawDataLabels: function () { var series = this, seriesOptions = series.options, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, str, dataLabelsGroup; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', series.visible ? VISIBLE : HIDDEN, options.zIndex || 6 ); // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true; // Determine if each data label is enabled pointOptions = point.options && point.options.dataLabels; enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282 // If the point is outside the plot area, destroy it. #678, #820 if (dataLabel && !enabled) { point.dataLabel = dataLabel.destroy(); // Individual labels are disabled if the are explicitly disabled // in the point options, or if they fall outside the plot area. } else if (enabled) { // Create individual options structure that can be extended without // affecting others options = merge(generalOptions, pointOptions); rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color options.style.color = pick(options.color, options.style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, null, null, null, options.useHTML ) .attr(attr) .css(options.style) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }, /** * Align each individual data label */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), visible = this.visible && chart.isInsidePlot(point.plotX, point.plotY, inverted), alignAttr; // the final position; if (visible) { // The alignment box is a singular point alignTo = extend({ x: inverted ? chart.plotWidth - plotY : plotX, y: mathRound(inverted ? chart.plotHeight - plotX : plotY), width: 0, height: 0 }, alignTo); // Add the text size for alignment calculation extend(options, { width: bBox.width, height: bBox.height }); // Allow a hook for changing alignment in the last moment, then do the alignment if (options.rotation) { // Fancy box alignment isn't supported for rotated text alignAttr = { align: options.align, x: alignTo.x + options.x + alignTo.width / 2, y: alignTo.y + options.y + alignTo.height / 2 }; dataLabel[isNew ? 'attr' : 'animate'](alignAttr); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === 'justify') { // docs: overflow: justify, also crop only applies when not justify this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew); } else if (pick(options.crop, true)) { // Now check that the data label is within the plot area visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height); } } } // Show or hide based on the final aligned position if (!visible) { dataLabel.attr({ y: -999 }); } }, /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ justifyDataLabel: function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified; // Off left off = alignAttr.x; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }, /** * Return the graph path of a segment */ getSegmentPath: function (segment) { var series = this, segmentPath = [], step = series.options.step; // build the segment line each(segment, function (point, i) { var plotX = point.plotX, plotY = point.plotY, lastPoint; if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i)); } else { // moveTo or lineTo segmentPath.push(i ? L : M); // step line? if (step && i) { lastPoint = segment[i - 1]; if (step === 'right') { segmentPath.push( lastPoint.plotX, plotY ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, (lastPoint.plotX + plotX) / 2, plotY ); } else { segmentPath.push( plotX, lastPoint.plotY ); } } // normal line to next point segmentPath.push( point.plotX, point.plotY ); } }); return segmentPath; }, /** * Get the graph path */ getGraphPath: function () { var series = this, graphPath = [], segmentPath, singlePoints = []; // used in drawTracker // Divide into segments and build graph and area paths each(series.segments, function (segment) { segmentPath = series.getSegmentPath(segment); // add the segment to the graph, or a single point for tracking if (segment.length > 1) { graphPath = graphPath.concat(segmentPath); } else { singlePoints.push(segment[0]); } }); // Record it for use in drawGraph and drawTracker, and return graphPath series.singlePoints = singlePoints; series.graphPath = graphPath; return graphPath; }, /** * Draw the actual graph */ drawGraph: function () { var series = this, options = this.options, props = [['graph', options.lineColor || this.color]], lineWidth = options.lineWidth, dashStyle = options.dashStyle, graphPath = this.getGraphPath(), negativeColor = options.negativeColor; if (negativeColor) { props.push(['graphNeg', negativeColor]); } // draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { stop(graph); // cancel running animations, #459 graph.animate({ d: graphPath }); } else if (lineWidth && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, zIndex: 1 // #1069 }; if (dashStyle) { attribs.dashstyle = dashStyle; } else { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow(!i && options.shadow); } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ clipNeg: function () { var options = this.options, chart = this.chart, renderer = chart.renderer, negativeColor = options.negativeColor || options.negativeFillColor, translatedThreshold, posAttr, negAttr, graph = this.graph, area = this.area, posClip = this.posClip, negClip = this.negClip, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartSizeMax = mathMax(chartWidth, chartHeight), yAxis = this.yAxis, above, below; if (negativeColor && (graph || area)) { translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true)); above = { x: 0, y: 0, width: chartSizeMax, height: translatedThreshold }; below = { x: 0, y: translatedThreshold, width: chartSizeMax, height: chartSizeMax }; if (chart.inverted) { above.height = below.y = chart.plotWidth - translatedThreshold; if (renderer.isVML) { above = { x: chart.plotWidth - translatedThreshold - chart.plotLeft, y: 0, width: chartWidth, height: chartHeight }; below = { x: translatedThreshold + chart.plotLeft - chartWidth, y: 0, width: chart.plotLeft + translatedThreshold, height: chartWidth }; } } if (yAxis.reversed) { posAttr = below; negAttr = above; } else { posAttr = above; negAttr = below; } if (posClip) { // update posClip.animate(posAttr); negClip.animate(negAttr); } else { this.posClip = posClip = renderer.clipRect(posAttr); this.negClip = negClip = renderer.clipRect(negAttr); if (graph && this.graphNeg) { graph.clip(posClip); this.graphNeg.clip(negClip); } if (area) { area.clip(posClip); this.areaNeg.clip(negClip); } } } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); } // Place it on first and subsequent (redraw) calls group[isNew ? 'attr' : 'animate'](this.getPlotBox()); return group; }, /** * Get the translation and scale for the plot area of this series */ getPlotBox: function () { return { translateX: this.xAxis ? this.xAxis.left : this.chart.plotLeft, translateY: this.yAxis ? this.yAxis.top : this.chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, doAnimation = animation && !!series.animate && chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE visibility = series.visible ? VISIBLE : HIDDEN, zIndex = options.zIndex, hasRendered = series.hasRendered, chartSeriesGroup = chart.seriesGroup; // the group group = series.plotGroup( 'group', 'series', visibility, zIndex, chartSeriesGroup ); series.markerGroup = series.plotGroup( 'markerGroup', 'markers', visibility, zIndex, chartSeriesGroup ); // initiate the animation if (doAnimation) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.clipNeg(); } // draw the data labels (inn pies they go before the points) series.drawDataLabels(); // draw the points series.drawPoints(); // draw the mouse tracking area if (series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (doAnimation) { series.animate(); } else if (!hasRendered) { series.afterAnimate(); } series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see series.hasRendered = true; }, /** * Redraw the series after an update in the axes. */ redraw: function () { var series = this, chart = series.chart, wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.setTooltipPoints(true); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, graphNeg = series.graphNeg, stateOptions = options.states, lineWidth = options.lineWidth, attribs; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + 1; } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); if (graphNeg) { graphNeg.attr(attribs); } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTracker: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; // end Series prototype /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { threshold: 0 // trackByArea: false, // lineColor: null, // overrides color, but lets fillColor be unaltered // fillOpacity: 0.75, // fillColor: null }); /** * AreaSeries object */ var AreaSeries = extendClass(Series, { type: 'area', /** * For stacks, don't split segments on null values. Instead, draw null values with * no marker. Also insert dummy points for any X position that exists in other series * in the stack. */ getSegments: function () { var segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, val, i, x; if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue // Create a map where we can quickly look up the points by their X value. for (i = 0; i < points.length; i++) { pointMap[points[i].x] = points[i]; } // Sort the keys (#1651) for (x in stack) { keys.push(+x); } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836 return; // The point exists, push it to the segment } else if (pointMap[x]) { segment.push(pointMap[x]); // There is no point for this X value in this series, so we // insert a dummy point in order for the areas to be drawn // correctly. } else { plotX = xAxis.translate(x); val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991 plotY = yAxis.toPixels(val, true); segment.push({ y: null, plotX: plotX, clientX: plotX, plotY: plotY, yBottom: plotY, onMouseOver: noop }); } }); if (segment.length) { segments.push(segment); } } else { Series.prototype.getSegments.call(this); segments = this.segments; } this.segments = segments; }, /** * Extend the base Series getSegmentPath method by adding the path for the area. * This path is pushed to the series.areaPath property. */ getSegmentPath: function (segment) { var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path i, options = this.options, segLength = segmentPath.length, translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181 yBottom; if (segLength === 3) { // for animation from 1 to two points areaSegmentPath.push(L, segmentPath[1], segmentPath[2]); } if (options.stacking && !this.closedStacks) { // Follow stack back. Todo: implement areaspline. A general solution could be to // reverse the entire graphPath of the previous series, though may be hard with // splines and with series with different extremes for (i = segment.length - 1; i >= 0; i--) { yBottom = pick(segment[i].yBottom, translatedThreshold); // step line? if (i < segment.length - 1 && options.step) { areaSegmentPath.push(segment[i + 1].plotX, yBottom); } areaSegmentPath.push(segment[i].plotX, yBottom); } } else { // follow zero line back this.closeSegment(areaSegmentPath, segment, translatedThreshold); } this.areaPath = this.areaPath.concat(areaSegmentPath); return segmentPath; }, /** * Extendable method to close the segment path of an area. This is overridden in polar * charts. */ closeSegment: function (path, segment, translatedThreshold) { path.push( L, segment[segment.length - 1].plotX, translatedThreshold, L, segment[0].plotX, translatedThreshold ); }, /** * Draw the graph and the underlying area. This method calls the Series base * function and adds the area. The areaPath is calculated in the getSegmentPath * method called from Series.prototype.drawGraph. */ drawGraph: function () { // Define or reset areaPath this.areaPath = []; // Call the base method Series.prototype.drawGraph.apply(this); // Define local variables var series = this, areaPath = this.areaPath, options = this.options, negativeColor = options.negativeColor, negativeFillColor = options.negativeFillColor, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color if (negativeColor || negativeFillColor) { props.push(['areaNeg', negativeColor, negativeFillColor]); } each(props, function (prop) { var areaKey = prop[0], area = series[areaKey]; // Create or update the area if (area) { // update area.animate({ d: areaPath }); } else { // create series[areaKey] = series.chart.renderer.path(areaPath) .attr({ fill: pick( prop[2], Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get() ), zIndex: 0 // #1069 }).add(series.group); } }); }, /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawLegendSymbol: function (legend, item) { item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - 11, legend.options.symbolWidth, 12, 2 ).attr({ zIndex: 3 }).add(item.legendGroup); } }); seriesTypes.area = AreaSeries;/** * Set the default options for spline */ defaultPlotOptions.spline = merge(defaultSeriesOptions); /** * SplineSeries object */ var SplineSeries = extendClass(Series, { type: 'spline', /** * Get the spline segment from a given point's previous neighbour to the given point */ getPointSpline: function (segment, point, i) { var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc denom = smoothing + 1, plotX = point.plotX, plotY = point.plotY, lastPoint = segment[i - 1], nextPoint = segment[i + 1], leftContX, leftContY, rightContX, rightContY, ret; // find control points if (lastPoint && nextPoint) { var lastX = lastPoint.plotX, lastY = lastPoint.plotY, nextX = nextPoint.plotX, nextY = nextPoint.plotY, correction; leftContX = (smoothing * plotX + lastX) / denom; leftContY = (smoothing * plotY + lastY) / denom; rightContX = (smoothing * plotX + nextX) / denom; rightContY = (smoothing * plotY + nextY) / denom; // have the two control points make a straight line through main point correction = ((rightContY - leftContY) * (rightContX - plotX)) / (rightContX - leftContX) + plotY - rightContY; leftContY += correction; rightContY += correction; // to prevent false extremes, check that control points are between // neighbouring points' y values if (leftContY > lastY && leftContY > plotY) { leftContY = mathMax(lastY, plotY); rightContY = 2 * plotY - leftContY; // mirror of left control point } else if (leftContY < lastY && leftContY < plotY) { leftContY = mathMin(lastY, plotY); rightContY = 2 * plotY - leftContY; } if (rightContY > nextY && rightContY > plotY) { rightContY = mathMax(nextY, plotY); leftContY = 2 * plotY - rightContY; } else if (rightContY < nextY && rightContY < plotY) { rightContY = mathMin(nextY, plotY); leftContY = 2 * plotY - rightContY; } // record for drawing in next point point.rightContX = rightContX; point.rightContY = rightContY; } // Visualize control points for debugging /* if (leftContX) { this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2) .attr({ stroke: 'red', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'red', 'stroke-width': 1 }) .add(); this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2) .attr({ stroke: 'green', 'stroke-width': 1, fill: 'none' }) .add(); this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop]) .attr({ stroke: 'green', 'stroke-width': 1 }) .add(); } */ // moveTo or lineTo if (!i) { ret = [M, plotX, plotY]; } else { // curve from last point to this ret = [ 'C', lastPoint.rightContX || lastPoint.plotX, lastPoint.rightContY || lastPoint.plotY, leftContX || plotX, leftContY || plotY, plotX, plotY ]; lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later } return ret; } }); seriesTypes.spline = SplineSeries; /** * Set the default options for areaspline */ defaultPlotOptions.areaspline = merge(defaultPlotOptions.area); /** * AreaSplineSeries object */ var areaProto = AreaSeries.prototype, AreaSplineSeries = extendClass(SplineSeries, { type: 'areaspline', closedStacks: true, // instead of following the previous graph back, follow the threshold back // Mix in methods from the area series getSegmentPath: areaProto.getSegmentPath, closeSegment: areaProto.closeSegment, drawGraph: areaProto.drawGraph, drawLegendSymbol: areaProto.drawLegendSymbol }); seriesTypes.areaspline = AreaSplineSeries; /** * Set the default options for column */ defaultPlotOptions.column = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, borderRadius: 0, //colorByPoint: undefined, groupPadding: 0.2, //grouping: true, marker: null, // point options are specified in the base options pointPadding: 0.1, //pointWidth: null, minPointLength: 0, cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories states: { hover: { brightness: 0.1, shadow: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, stickyTracking: false, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, columnIndex, columnCount = 0; // Get the total number of column type series. // This is called on every series. Consider moving this logic to a // chart.orderStacks() function and call it on init, addSeries and removeSeries if (options.grouping === false) { columnCount = 1; } else { each(series.chart.series, function (otherSeries) { var otherOptions = otherSeries.options, otherYAxis = otherSeries.yAxis; if (otherSeries.type === series.type && otherSeries.visible && yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086 if (otherOptions.stacking) { stackKey = otherSeries.stackKey; if (stackGroups[stackKey] === UNDEFINED) { stackGroups[stackKey] = columnCount++; } columnIndex = stackGroups[stackKey]; } else if (otherOptions.grouping !== false) { // #1162 columnIndex = columnCount++; } otherSeries.columnIndex = columnIndex; } }); } var categoryWidth = mathMin( mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1), xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, optionPointWidth = options.pointWidth, pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 : pointOffsetWidth * options.pointPadding, pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts colIndex = (reversedXAxis ? columnCount - (series.columnIndex || 0) : // #1251 series.columnIndex) || 0, pointXOffset = pointPadding + (groupPadding + colIndex * pointOffsetWidth - (categoryWidth / 2)) * (reversedXAxis ? -1 : 1); // Save it for reading in linked series (Error bars particularly) return (series.columnMetrics = { width: pointWidth, offset: pointXOffset }); }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = options.borderWidth, yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1; if (chart.renderer.isVML && chart.inverted) { yCrisp += 1; } Series.prototype.translate.apply(series); // record the new values each(series.points, function (point) { var yBottom = pick(point.yBottom, translatedThreshold), plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), right, bottom, fromTop, fromLeft, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; barY = mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485) } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Round off to obtain crisp edges fromLeft = mathAbs(barX) < 0.5; right = mathRound(barX + barW) + xCrisp; barX = mathRound(barX) + xCrisp; barW = right - barX; fromTop = mathAbs(barY) < 0.5; bottom = mathRound(barY + barH) + yCrisp; barY = mathRound(barY) + yCrisp; barH = bottom - barY; // Top and left edges are exceptions if (fromLeft) { barX += 1; barW -= 1; } if (fromTop) { barY -= 1; barH += 1; } // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = { x: barX, y: barY, width: barW, height: barH }; }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, options = series.options, renderer = series.chart.renderer, shapeArgs; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; if (graphic) { // update stop(graphic); graphic.animate(merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]) .add(series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ drawTracker: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; if (chart.hoverSeries !== series) { series.onMouseOver(); } while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Override the basic data label alignment by adjusting for the position of the column */ alignDataLabel: function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)), inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // Align to the column itself, or the top of it if (dlBox) { // Area range uses this method but not alignTo alignTo = merge(dlBox); if (inverted) { alignTo = { x: chart.plotWidth - alignTo.y - alignTo.height, y: chart.plotHeight - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for bar */ defaultPlotOptions.bar = merge(defaultPlotOptions.column); /** * The Bar series class */ var BarSeries = extendClass(ColumnSeries, { type: 'bar', inverted: true }); seriesTypes.bar = BarSeries; /** * Set the default options for scatter */ defaultPlotOptions.scatter = merge(defaultSeriesOptions, { lineWidth: 0, tooltip: { headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>', followPointer: true }, stickyTracking: false }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['markerGroup'], drawTracker: ColumnSeries.prototype.drawTracker, setTooltipPoints: noop }); seriesTypes.scatter = ScatterSeries; /** * Set the default options for pie */ defaultPlotOptions.pie = merge(defaultSeriesOptions, { borderColor: '#FFFFFF', borderWidth: 1, center: [null, null], clip: false, colorByPoint: true, // always true for pies dataLabels: { // align: null, // connectorWidth: 1, // connectorColor: point.color, // connectorPadding: 5, distance: 30, enabled: true, formatter: function () { return this.point.name; } // softConnector: true, //y: 0 }, ignoreHiddenPoint: true, //innerSize: 0, legendType: 'point', marker: null, // point options are specified in the base options size: null, showInLegend: false, slicedOffset: 10, states: { hover: { brightness: 0.1, shadow: false } }, stickyTracking: false, tooltip: { followPointer: true } }); /** * Extended point object for pies */ var PiePoint = extendClass(Point, { /** * Initiate the pie slice */ init: function () { Point.prototype.init.apply(this, arguments); var point = this, toggleSlice; // Disallow negative values (#1530) if (point.y < 0) { point.y = null; } //visible: options.visible !== false, extend(point, { visible: point.visible !== false, name: pick(point.name, 'Slice') }); // add event listener for select toggleSlice = function (e) { point.slice(e.type === 'select'); }; addEvent(point, 'select', toggleSlice); addEvent(point, 'unselect', toggleSlice); return point; }, /** * Toggle the visibility of the pie slice * @param {Boolean} vis Whether to show the slice or not. If undefined, the * visibility is toggled */ setVisible: function (vis) { var point = this, series = point.series, chart = series.chart, method; // if called without an argument, toggle visibility point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data method = vis ? 'show' : 'hide'; // Show and hide associated elements each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][method](); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // Handle ignore hidden slices if (!series.isDirty && series.options.ignoreHiddenPoint) { series.isDirty = true; chart.redraw(); } }, /** * Set or toggle whether the slice is cut out from the pie * @param {Boolean} sliced When undefined, the slice state is toggled * @param {Boolean} redraw Whether to redraw the chart. True by default. */ slice: function (sliced, redraw, animation) { var point = this, series = point.series, chart = series.chart, translation; setAnimation(animation, chart); // redraw is true by default redraw = pick(redraw, true); // if called without an argument, toggle point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced; series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data translation = sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; point.graphic.animate(translation); if (point.shadowGroup) { point.shadowGroup.animate(translation); } } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * Pies have one color each point */ getColor: noop, /** * Animate the pies in */ animate: function (init) { var series = this, points = series.points, startAngleRad = series.startAngleRad; if (!init) { each(points, function (point) { var graphic = point.graphic, args = point.shapeArgs; if (graphic) { // start values graphic.attr({ r: series.center[3] / 2, // animate from inner radius (#779) start: startAngleRad, end: startAngleRad }); // animate graphic.animate({ r: args.r, start: args.start, end: args.end }, series.options.animation); } }); // delete this function to allow it only once series.animate = null; } }, /** * Extend the basic setData method by running processData and generatePoints immediately, * in order to access the points from the legend. */ setData: function (data, redraw) { Series.prototype.setData.call(this, data, false); this.processData(); this.generatePoints(); if (pick(redraw, true)) { this.chart.redraw(); } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { var i, total = 0, points, len, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; Series.prototype.generatePoints.call(this); // Populate local vars points = this.points; len = points.length; // Get the total sum for (i = 0; i < len; i++) { point = points[i]; total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y; } this.total = total; // Set each point's properties for (i = 0; i < len; i++) { point = points[i]; point.percentage = total > 0 ? (point.y / total) * 100 : 0; point.total = total; } }, /** * Get the center of the pie based on the size and center options relative to the * plot area. Borrowed by the polar and gauge series types. */ getCenter: function () { var options = this.options, chart = this.chart, slicingRoom = 2 * (options.slicedOffset || 0), handleSlicingRoom, plotWidth = chart.plotWidth - 2 * slicingRoom, plotHeight = chart.plotHeight - 2 * slicingRoom, centerOption = options.center, positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0], smallestSize = mathMin(plotWidth, plotHeight), isPercent; return map(positions, function (length, i) { isPercent = /%$/.test(length); handleSlicingRoom = i < 2 || (i === 2 && isPercent); return (isPercent ? // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 4: innerSize, relative to smallestSize [plotWidth, plotHeight, smallestSize, smallestSize][i] * pInt(length) / 100 : length) + (handleSlicingRoom ? slicingRoom : 0); }); }, /** * Do translation for pie slices */ translate: function (positions) { this.generatePoints(); var series = this, cumulative = 0, precision = 1000, // issue #172 options = series.options, slicedOffset = options.slicedOffset, connectorOffset = slicedOffset + options.borderWidth, start, end, angle, startAngle = options.startAngle || 0, startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90), endAngleRad = series.endAngleRad = mathPI / 180 * ((options.endAngle || (startAngle + 360)) - 90), // docs circ = endAngleRad - startAngleRad, //2 * mathPI, points = series.points, radiusX, // the x component of the radius vector for a given point radiusY, labelDistance = options.dataLabels.distance, ignoreHiddenPoint = options.ignoreHiddenPoint, i, len = points.length, point; // Get positions - either an integer or a percentage string must be given. // If positions are passed as a parameter, we're in a recursive loop for adjusting // space for data labels. if (!positions) { series.center = positions = series.getCenter(); } // utility for getting the x value from a given y, used for anticollision logic in data labels series.getX = function (y, left) { angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance)); return positions[0] + (left ? -1 : 1) * (mathCos(angle) * (positions[2] / 2 + labelDistance)); }; // Calculate the geometry for each point for (i = 0; i < len; i++) { point = points[i]; // set start and end angle start = startAngleRad + (cumulative * circ); if (!ignoreHiddenPoint || point.visible) { cumulative += point.percentage / 100; } end = startAngleRad + (cumulative * circ); // set the shape point.shapeType = 'arc'; point.shapeArgs = { x: positions[0], y: positions[1], r: positions[2] / 2, innerR: positions[3] / 2, start: mathRound(start * precision) / precision, end: mathRound(end * precision) / precision }; // center for the sliced out slice angle = (end + start) / 2; if (angle > 0.75 * circ) { angle -= 2 * mathPI; } point.slicedTranslation = { translateX: mathRound(mathCos(angle) * slicedOffset), translateY: mathRound(mathSin(angle) * slicedOffset) }; // set the anchor point for tooltips radiusX = mathCos(angle) * positions[2] / 2; radiusY = mathSin(angle) * positions[2] / 2; point.tooltipPos = [ positions[0] + radiusX * 0.7, positions[1] + radiusY * 0.7 ]; point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0; point.angle = angle; // set the anchor point for data labels connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678 point.labelPos = [ positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a positions[0] + radiusX, // landing point for connector positions[1] + radiusY, // a/a labelDistance < 0 ? // alignment 'center' : point.half ? 'right' : 'left', // alignment angle // center angle ]; } }, setTooltipPoints: noop, drawGraph: null, /** * Draw the data points */ drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, groupTranslation, //center, graphic, //group, shadow = series.options.shadow, shadowGroup, shapeArgs; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { graphic = point.graphic; shapeArgs = point.shapeArgs; shadowGroup = point.shadowGroup; // put the shadow behind all points if (shadow && !shadowGroup) { shadowGroup = point.shadowGroup = renderer.g('shadow') .add(series.shadowGroup); } // if the point is sliced, use special translation, else use plot area traslation groupTranslation = point.sliced ? point.slicedTranslation : { translateX: 0, translateY: 0 }; //group.translate(groupTranslation[0], groupTranslation[1]); if (shadowGroup) { shadowGroup.attr(groupTranslation); } // draw the slice if (graphic) { graphic.animate(extend(shapeArgs, groupTranslation)); } else { point.graphic = graphic = renderer.arc(shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr({ 'stroke-linejoin': 'round' }) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } // detect point specific visibility if (point.visible === false) { point.setVisible(false); } }); }, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Override the base drawDataLabels method by pie specific functionality */ drawDataLabels: function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel) { // it may have been cancelled in the base method (#407) halves[point.half].push(point); } }); // assume equal label heights i = 0; while (!labelHeight && data[i]) { // #1569 labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968 i++; } /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, length = points.length, slotIndex; // Sort by angle series.sortByAngle(points, i - 0.5); // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // build the slots for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) { slots.push(pos); // visualize the slot /* var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver' }) .add(); chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4) .attr({ fill: 'silver' }).add(); } */ } slotsLength = slots.length; // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : VISIBLE; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = naturalY; } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility }) .add(series.group); } } else if (connector) { point.connector = connector.destroy(); } }); } } }, /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ verifyDataLabelOverflow: function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); this.drawDataLabels(); // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }, /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ placeDataLabels: function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }, alignDataLabel: noop, /** * Draw point specific tracker objects. Inherit directly from column series. */ drawTracker: ColumnSeries.prototype.drawTracker, /** * Use a simple symbol from column prototype */ drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; // global variables extend(Highcharts, { // Constructors Axis: Axis, Chart: Chart, Color: Color, Legend: Legend, Pointer: Pointer, Point: Point, Tick: Tick, Tooltip: Tooltip, Renderer: Renderer, Series: Series, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, numberFormat: numberFormat, seriesTypes: seriesTypes, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, extend: extend, map: map, merge: merge, pick: pick, splat: splat, extendClass: extendClass, pInt: pInt, wrap: wrap, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
src/pages/error/index.js
RyszardRzepa/React-Redux-Firebase-Boilerplate
import React from 'react'; import history from '../../history'; import Link from '../../components/Link'; import s from './styles.css'; class ErrorPage extends React.Component { componentDidMount() { document.title = this.props.error && this.props.error.status === 404 ? 'Page Not Found' : 'Error'; } goBack = (event) => { event.preventDefault(); history.goBack(); }; render() { if (this.props.error) console.error(this.props.error); // eslint-disable-line no-console const [code, title] = this.props.error && this.props.error.status === 404 ? ['404', 'Page not found'] : ['Error', 'Oups, something went wrong']; return ( <div className={s.container}> <main className={s.content}> <h1 className={s.code}>{code}</h1> <p className={s.title}>{title}</p> {code === '404' && <p className={s.text}> The page you&apos;re looking for does not exist or an another error occurred. </p> } <p className={s.text}> <a href="/" onClick={this.goBack}>Go back</a>, or head over to the&nbsp; <Link to="/">home page</Link> to choose a new direction. </p> </main> </div> ); } } const propTypes = { error: React.PropTypes.object, // eslint-disable-line react/forbid-prop-types }; export default ErrorPage;
src/index.js
SpongeComing/react-demo
import 'core-js/fn/object/assign'; import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/Main'; // Render the main component into the dom ReactDOM.render(<App />, document.getElementById('app'));
templates/rubix/demo/src/routes/Editor.js
jeffthemaximum/jeffline
import React from 'react'; import ReactDOM from 'react-dom'; import { Row, Col, Grid, Panel, PanelBody, PanelHeader, PanelContainer, } from '@sketchpixy/rubix'; class TrumbowygEditor extends React.Component { componentDidMount() { $(ReactDOM.findDOMNode(this._el)).trumbowyg({ autogrow: true, dir: $('html').attr('dir'), btns: [ ['viewHTML'], ['undo', 'redo'], ['formatting'], 'btnGrp-semantic', ['superscript', 'subscript'], ['link'], ['insertImage'], 'btnGrp-justify', 'btnGrp-lists', ['horizontalRule'], ['removeformat'], ] }).trumbowyg('html', '<p>Steve Jobs became the greatest business executive of our era, the one most certain to be remembered a century from now. History will place him in the pantheon right next to Edison and Ford. More than anyone else of his time, he made products that were completely innovative, combining the power of poetry and processors.</p><blockquote><p style="margin-bottom: 12.5px;"><span style="font-size: 11pt; line-height: 1.78571;">Some people say, “Give the customers what they want.” But that’s not my approach. Our job is to figure out what they’re going to want before they do. I think Henry Ford once said, <b>“If I’d asked customers what they wanted, they would have told me, ‘A faster horse!’”</b> People don’t know what they want until you show it to them. That’s why I never rely on market research. Our task is to read things that are not yet on the page.&nbsp;</span><br></p><div><span style="font-size: 11pt; line-height: 1.78571;">- Steve Jobs in <i>Steve Jobs by Walter Isaacson</i></span></div></blockquote><p>Was he smart? No, not exceptionally. Instead, he was a <b><i>genius</i></b>. His imaginative leaps were instinctive, unexpected, and at times <b><i>magical</i></b>. He was, indeed, an example of what the mathematician Mark Kac called a magician genius, someone whose insights come out of the blue and require intuition more than mere mental processing power. Like a pathfinder, he could absorb information, sniff the winds, and sense what lay ahead.</p>'); } render() { return <div id='trumbowyg-demo' ref={(el) => this._el = el}></div>; } } export default class Editor extends React.Component { render() { return ( <div> <PanelContainer> <Panel> <PanelHeader> <Grid> <Row> <Col xs={12}> <h3 className='text-center'>Trumbowyg Editor</h3> </Col> </Row> </Grid> </PanelHeader> <PanelBody> <TrumbowygEditor /> </PanelBody> </Panel> </PanelContainer> </div> ); } }
src/client/mindmap/entry.react.js
dfogas/my-mindmap
import './mindmap.styl'; import Component from '../components/component.react'; import DocumentTitle from 'react-document-title'; import React from 'react'; import {FormattedHTMLMessage} from 'react-intl'; import {msg} from '../intl/store'; import EntryLink from './link.react'; import links from '../links'; class Entry extends Component { render() { const {head} = this.props; return ( <div className='mindmap-entry'> <FormattedHTMLMessage message={msg('mindmap.' + head)} /> {' '} <div id='ListOfLinks'> {links[head].map(link => { return ( <EntryLink entry={link} /> ); })} </div> </div> ); } } export default Entry;
app/assets/javascripts/components/story/AddStoryButton.js
Codeminer42/cm42-central
import React from 'react'; import PropTypes from 'prop-types'; const AddStoryButton = ({ onAdd }) => ( <button className="btn btn-primary Column__btn-add-story" onClick={onAdd} > <i className="mi md-light md-18 md-add">add</i> {I18n.t('add story')} </button> ); AddStoryButton.propTypes = { onAdd: PropTypes.func.isRequired }; export default AddStoryButton;
frontend/src/components/common/Field.js
jf248/scrape-the-plate
import React from 'react'; import * as Enhanced from 'lib/mui-components'; import * as utils from 'utils'; Field.defaultProps = { component: Enhanced.TextField, }; function Field({ error: errorProp, touched, component: Component, formatValue, value: valueProp, ...rest }) { // Check error is not an object const error = utils.isObject(errorProp) ? undefined : errorProp; const value = formatValue ? formatValue(valueProp) : valueProp; return ( <Component helperText={touched && error} error={touched && !!error} margin="dense" value={value} {...rest} /> ); } export default Field;
node_modules/react-icons/io/android-playstore.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoAndroidPlaystore = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m36 11.9c-1.5 16.7-1 24.4-1 24.4h-30.5s0.5-7.5-1-24.4h8.1c0-4.5 3.7-8.1 8.1-8.1s8.2 3.6 8.2 8.1h8.1z m-16.2-6.1c-3.4 0-6.1 2.7-6.1 6.1h12.1c0-3.4-2.7-6.1-6-6.1z m-4.1 25.3l11.2-6.6-11.2-6.6v13.2z"/></g> </Icon> ) export default IoAndroidPlaystore
examples/src/components/States.js
f-camacho/react-select
import React from 'react'; import createClass from 'create-react-class'; import PropTypes from 'prop-types'; import Select from 'react-select'; const STATES = require('../data/states'); var StatesField = createClass({ displayName: 'StatesField', propTypes: { label: PropTypes.string, searchable: PropTypes.bool, }, getDefaultProps () { return { label: 'States:', searchable: true, }; }, getInitialState () { return { country: 'AU', disabled: false, searchable: this.props.searchable, selectValue: 'new-south-wales', clearable: true, }; }, switchCountry (e) { var newCountry = e.target.value; console.log('Country changed to ' + newCountry); this.setState({ country: newCountry, selectValue: null }); }, updateValue (newValue) { console.log('State changed to ' + newValue); this.setState({ selectValue: newValue }); }, focusStateSelect () { this.refs.stateSelect.focus(); }, toggleCheckbox (e) { let newState = {}; newState[e.target.name] = e.target.checked; this.setState(newState); }, render () { var options = STATES[this.state.country]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select ref="stateSelect" autofocus options={options} simpleValue clearable={this.state.clearable} name="selected-state" disabled={this.state.disabled} value={this.state.selectValue} onChange={this.updateValue} searchable={this.state.searchable} /> <div style={{ marginTop: 14 }}> <button type="button" onClick={this.focusStateSelect}>Focus Select</button> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="searchable" checked={this.state.searchable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Searchable</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="disabled" checked={this.state.disabled} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Disabled</span> </label> <label className="checkbox" style={{ marginLeft: 10 }}> <input type="checkbox" className="checkbox-control" name="clearable" checked={this.state.clearable} onChange={this.toggleCheckbox}/> <span className="checkbox-label">Clearable</span> </label> </div> <div className="checkbox-list"> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'AU'} value="AU" onChange={this.switchCountry}/> <span className="checkbox-label">Australia</span> </label> <label className="checkbox"> <input type="radio" className="checkbox-control" checked={this.state.country === 'US'} value="US" onChange={this.switchCountry}/> <span className="checkbox-label">United States</span> </label> </div> </div> ); } }); module.exports = StatesField;
example/examples/LabelKeyExample.react.js
Neophy7e/react-bootstrap-typeahead
import React from 'react'; import {Typeahead} from '../../src/'; /* example-start */ const LabelKeyExample = React.createClass({ render() { return ( <Typeahead labelKey={option => `${option.firstName} ${option.lastName}`} options={[ {firstName: 'Art', lastName: 'Blakey'}, {firstName: 'John', lastName: 'Coltrane'}, {firstName: 'Miles', lastName: 'Davis'}, {firstName: 'Herbie', lastName: 'Hancock'}, {firstName: 'Charlie', lastName: 'Parker'}, {firstName: 'Tony', lastName: 'Williams'}, ]} placeholder="Who's the coolest cat?" /> ); }, }); /* example-end */ export default LabelKeyExample;
ajax/libs/yui/3.11.0/simpleyui/simpleyui.js
joeylakay/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 **/ /** The minimum log level to log messages for. Log levels are defined incrementally. Messages greater than or equal to the level specified will be shown. All others will be discarded. The order of log levels in increasing priority is: debug info warn error @property {String} logLevel @default 'debug' @since 3.10.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 {Object|String} delayUntil @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. }); **/ 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, WHITESPACE = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF", WHITESPACE_CLASS = "[\x09-\x0D\x20\xA0\u1680\u180E\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]+", TRIM_LEFT_REGEX = new RegExp("^" + WHITESPACE_CLASS), TRIM_RIGHT_REGEX = new RegExp(WHITESPACE_CLASS + "$"), TRIMREGEX = new RegExp(TRIM_LEFT_REGEX.source + "|" + TRIM_RIGHT_REGEX.source, "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 = L._isNative(STRING_PROTO.trim) && !WHITESPACE.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 = L._isNative(STRING_PROTO.trimLeft) && !WHITESPACE.trimLeft() ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(TRIM_LEFT_REGEX, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = L._isNative(STRING_PROTO.trimRight) && !WHITESPACE.trimRight() ? function (s) { return s.trimRight(); } : function (s) { return s.replace(TRIM_RIGHT_REGEX, ''); }; /** 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 arrays consisting entirely of strings or entirely of numbers, whereas `unique` may be used with other value types (but is slower). Using `dedupe()` with values other than strings or numbers, or with arrays containing a mix of strings and numbers, may result in unexpected behavior. @method dedupe @param {String[]|Number[]} array Array of strings or numbers to dedupe. @return {Array} Copy of _array_ containing no duplicate values. @static @since 3.4.0 **/ YArray.dedupe = Lang._isNative(Object.create) ? function (array) { var hash = Object.create(null), results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hash[item]) { hash[item] = 1; results.push(item); } } return results; } : 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 and Android 2.3.x. * * @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 and non-buggy. The Opera 11.50 and Android 2.3.x versions of * `Object.keys()` have an inconsistency as they consider `prototype` to be * enumerable, so a non-native shim is used to rectify the difference. * * @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) && !hasProtoEnumBug ? 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(/OPR\/(\d+\.\d+)/); if (m && m[1]) { // Opera 15+ with Blink (pretends to be both Chrome and Safari) o.opera = numberify(m[1]); } else { 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 ([^;]*)|Trident.*; rv ([0-9.]+)/); if (m && (m[1] || m[2])) { o.ie = numberify(m[1] || m[2]); } 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]); if (/Mobile|Tablet/.test(ua)) { o.mobile = "ffos"; } } } } } } } //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: 2, warn: 4, error: 8 }; /** * 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, minlevel, 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]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } 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 recursively iterate down non-primitive properties. Clone should be used only when a deep clone down to leaf level properties is explicitly required. This method will also 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) { var o2, marked, stamp; // Does not attempt to clone: // // * Non-typeof-object values, "primitive" values don't need cloning. // // * YUI instances, cloning complex object like YUI instances is not // advised, this is like cloning the world. // // * DOM nodes (#2528250), common host objects like DOM nodes cannot be // "subclassed" in Firefox and old versions of IE. Trying to use // `Object.create()` or `Y.extend()` on a DOM node will throw an error in // these browsers. // // Instad, the passed-in `o` will be return as-is when it matches one of the // above criteria. if (!L.isObject(o) || Y.instanceOf(o, YUI) || (o.addEventListener || o.attachEvent)) { return o; } marked = cloned || {}; 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; } Y.each(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('color-base', function (Y, NAME) { /** Color provides static methods for color conversion. Y.Color.toRGB('f00'); // rgb(255, 0, 0) Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00 @module color @submodule color-base @class Color @since 3.8.0 **/ var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})(\ufffe)?/, REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})(\ufffe)?/, REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/, TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' }, CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' }; Y.Color = { /** @static @property KEYWORDS @type Object @since 3.8.0 **/ 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' }, /** NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression @static @property REGEX_HEX @type RegExp @default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})(\ufffe)?/ @since 3.8.0 **/ REGEX_HEX: REGEX_HEX, /** NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression @static @property REGEX_HEX3 @type RegExp @default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})(\ufffe)?/ @since 3.8.0 **/ REGEX_HEX3: REGEX_HEX3, /** @static @property REGEX_RGB @type RegExp @default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/ @since 3.8.0 **/ REGEX_RGB: REGEX_RGB, re_RGB: REGEX_RGB, re_hex: REGEX_HEX, re_hex3: REGEX_HEX3, /** @static @property STR_HEX @type String @default #{*}{*}{*} @since 3.8.0 **/ STR_HEX: '#{*}{*}{*}', /** @static @property STR_RGB @type String @default rgb({*}, {*}, {*}) @since 3.8.0 **/ STR_RGB: 'rgb({*}, {*}, {*})', /** @static @property STR_RGBA @type String @default rgba({*}, {*}, {*}, {*}) @since 3.8.0 **/ STR_RGBA: 'rgba({*}, {*}, {*}, {*})', /** @static @property TYPES @type Object @default {'rgb':'rgb', 'rgba':'rgba'} @since 3.8.0 **/ TYPES: TYPES, /** @static @property CONVERTS @type Object @default {} @since 3.8.0 **/ CONVERTS: CONVERTS, /** Converts the provided string to the provided type. You can use the `Y.Color.TYPES` to get a valid `to` type. If the color cannot be converted, the original color will be returned. @public @method convert @param {String} str @param {String} to @return {String} @since 3.8.0 **/ convert: function (str, to) { var convert = Y.Color.CONVERTS[to.toLowerCase()], clr = str; if (convert && Y.Color[convert]) { clr = Y.Color[convert](str); } return clr; }, /** Converts provided color value to a hex value string @public @method toHex @param {String} str Hex or RGB value string @return {String} returns array of values or CSS string if options.css is true @since 3.8.0 **/ toHex: function (str) { var clr = Y.Color._convertTo(str, 'hex'), isTransparent = clr.toLowerCase() === 'transparent'; if (clr.charAt(0) !== '#' && !isTransparent) { clr = '#' + clr; } return isTransparent ? clr.toLowerCase() : clr.toUpperCase(); }, /** Converts provided color value to an RGB value string @public @method toRGB @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGB: function (str) { var clr = Y.Color._convertTo(str, 'rgb'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGBA @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGBA: function (str) { var clr = Y.Color._convertTo(str, 'rgba' ); return clr.toLowerCase(); }, /** Converts the provided color string to an array of values where the last value is the alpha value. Will return an empty array if the provided string is not able to be parsed. NOTE: `(\ufffe)?` is added to `HEX` and `HEX3` Regular Expressions to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression Y.Color.toArray('fff'); // ['ff', 'ff', 'ff', 1] Y.Color.toArray('rgb(0, 0, 0)'); // ['0', '0', '0', 1] Y.Color.toArray('rgba(0, 0, 0, 0)'); // ['0', '0', '0', 1] @public @method toArray @param {String} str @return {Array} @since 3.8.0 **/ toArray: function(str) { // parse with regex and return "matches" array var type = Y.Color.findType(str).toUpperCase(), regex, arr, length, lastItem; if (type === 'HEX' && str.length < 5) { type = 'HEX3'; } if (type.charAt(type.length - 1) === 'A') { type = type.slice(0, -1); } regex = Y.Color['REGEX_' + type]; if (regex) { arr = regex.exec(str) || []; length = arr.length; if (length) { arr.shift(); length--; if (type === 'HEX3') { arr[0] += arr[0]; arr[1] += arr[1]; arr[2] += arr[2]; } lastItem = arr[length - 1]; if (!lastItem) { arr[length - 1] = 1; } } } return arr; }, /** Converts the array of values to a string based on the provided template. @public @method fromArray @param {Array} arr @param {String} template @return {String} @since 3.8.0 **/ fromArray: function(arr, template) { arr = arr.concat(); if (typeof template === 'undefined') { return arr.join(', '); } var replace = '{*}'; template = Y.Color['STR_' + template.toUpperCase()]; if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) { arr.push(1); } while ( template.indexOf(replace) >= 0 && arr.length > 0) { template = template.replace(replace, arr.shift()); } return template; }, /** Finds the value type based on the str value provided. @public @method findType @param {String} str @return {String} @since 3.8.0 **/ findType: function (str) { if (Y.Color.KEYWORDS[str]) { return 'keyword'; } var index = str.indexOf('('), key; if (index > 0) { key = str.substr(0, index); } if (key && Y.Color.TYPES[key.toUpperCase()]) { return Y.Color.TYPES[key.toUpperCase()]; } return 'hex'; }, // return 'keyword', 'hex', 'rgb' /** Retrives the alpha channel from the provided string. If no alpha channel is present, `1` will be returned. @protected @method _getAlpha @param {String} clr @return {Number} @since 3.8.0 **/ _getAlpha: function (clr) { var alpha, arr = Y.Color.toArray(clr); if (arr.length > 3) { alpha = arr.pop(); } return +alpha || 1; }, /** Returns the hex value string if found in the KEYWORDS object @protected @method _keywordToHex @param {String} clr @return {String} @since 3.8.0 **/ _keywordToHex: function (clr) { var keyword = Y.Color.KEYWORDS[clr]; if (keyword) { return keyword; } }, /** Converts the provided color string to the value type provided as `to` @protected @method _convertTo @param {String} clr @param {String} to @return {String} @since 3.8.0 **/ _convertTo: function(clr, to) { if (clr === 'transparent') { return clr; } var from = Y.Color.findType(clr), originalTo = to, needsAlpha, alpha, method, ucTo; if (from === 'keyword') { clr = Y.Color._keywordToHex(clr); from = 'hex'; } if (from === 'hex' && clr.length < 5) { if (clr.charAt(0) === '#') { clr = clr.substr(1); } clr = '#' + clr.charAt(0) + clr.charAt(0) + clr.charAt(1) + clr.charAt(1) + clr.charAt(2) + clr.charAt(2); } if (from === to) { return clr; } if (from.charAt(from.length - 1) === 'a') { from = from.slice(0, -1); } needsAlpha = (to.charAt(to.length - 1) === 'a'); if (needsAlpha) { to = to.slice(0, -1); alpha = Y.Color._getAlpha(clr); } ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase(); method = Y.Color['_' + from + 'To' + ucTo ]; // check to see if need conversion to rgb first // check to see if there is a direct conversion method // convertions are: hex <-> rgb <-> hsl if (!method) { if (from !== 'rgb' && to !== 'rgb') { clr = Y.Color['_' + from + 'ToRgb'](clr); from = 'rgb'; method = Y.Color['_' + from + 'To' + ucTo ]; } } if (method) { clr = ((method)(clr, needsAlpha)); } // process clr from arrays to strings after conversions if alpha is needed if (needsAlpha) { if (!Y.Lang.isArray(clr)) { clr = Y.Color.toArray(clr); } clr.push(alpha); clr = Y.Color.fromArray(clr, originalTo.toUpperCase()); } return clr; }, /** Processes the hex string into r, g, b values. Will return values as an array, or as an rgb string. @protected @method _hexToRgb @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _hexToRgb: function (str, toArray) { var r, g, b; /*jshint bitwise:false*/ if (str.charAt(0) === '#') { str = str.substr(1); } str = parseInt(str, 16); r = str >> 16; g = str >> 8 & 0xFF; b = str & 0xFF; if (toArray) { return [r, g, b]; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }, /** Processes the rgb string into r, g, b values. Will return values as an array, or as a hex string. @protected @method _rgbToHex @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _rgbToHex: function (str) { /*jshint bitwise:false*/ var rgb = Y.Color.toArray(str), hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16); hex = (+hex).toString(16); while (hex.length < 6) { hex = '0' + hex; } return '#' + hex; } }; }, '@VERSION@', {"requires": ["yui-base"]}); 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); }, '@VERSION@', {"requires": ["dom-base", "color-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 || Y.UA.opera) && // webkit (chrome, safari) and Opera selector.indexOf(':checked') > -1 && // fail to pick up "selected" with ":checked" (Y.Selector.pseudos && Y.Selector.pseudos.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(); } } }; 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; ////////////////////////////////////////////////////////////////////////// /** * 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} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * 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 */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, 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, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * 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 */ /** * 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 event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * 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; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default 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 */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * 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 */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * 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 */ 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 */ bubbles : true, /** * 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 = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += 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 sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * 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), firedWith; if (this.fireOnce && this.fired) { firedWith = this.firedWith; // It's a little ugly for this to know about facades, // but given the current breakup, not much choice without // moving a whole lot of stuff around. if (this.emitFacade && this._addFacadeToArgs) { this._addFacadeToArgs(firedWith); } if (this.async) { setTimeout(Y.bind(this._notify, this, s, firedWith), 0); } else { this._notify(s, firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; } 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; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { 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() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // 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); } if (this.broadcast) { 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; } if (subs) { 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.guid(); /** * 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 = function(type, pre) { if (!pre || 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 etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; 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); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = 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 ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * 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. * * 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. * * 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. * * @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 {Boolean} True if the whole lifecycle of the event went through, * false if at any point the event propagation was halted. */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { 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 { if (ce2) { ce.sibling = ce2; } ret = ce._fire(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); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } 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, YObject = Y.Object, 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) { if (!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 = true, events, subs, ons, afters, afterQueue, postponed, prevented, preventedFn, defaultFn, self = this, host = self.host || self, next, oldbubble, stack = self.stack, yuievt = host._yuievt, hasPotentialSubscribers; if (stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type !== stack.next.type) { self.log('queue ' + self.type); if (!stack.queue) { stack.queue = []; } stack.queue.push([self, args]); return true; } } hasPotentialSubscribers = self.hasSubs() || yuievt.hasTargets || self.broadcast; self.target = self.target || host; self.currentTarget = host; self.details = args.concat(); if (hasPotentialSubscribers) { es = stack || { id: self.id, // id of the first event in the stack next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly }; subs = self.getSubs(); ons = subs[0]; afters = subs[1]; self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; if (self.stoppedFn) { // PERF TODO: Can we replace with callback, like preventedFn. Look into history events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._createFacade(args); if (ons) { self._procSubs(ons, 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; } prevented = self.prevented; if (prevented) { preventedFn = self.preventedFn; if (preventedFn) { preventedFn.apply(host, args); } } else { defaultFn = self.defaultFn; if (defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { defaultFn.apply(host, args); } } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. if (self.broadcast) { self._broadcast(args); } if (afters && !self.prevented && self.stopped < 2) { // Queue the after afterQueue = es.afterQueue; if (es.id === self.id || self.type !== yuievt.bubbling) { self._procSubs(afters, args, ef); if (afterQueue) { while ((next = afterQueue.last())) { next(); } } } else { postponed = afters; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } if (!afterQueue) { es.afterQueue = new Y.Queue(); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; if (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(q[1]); } } self.stack = null; } ret = !(self.stopped); if (self.type !== yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } } else { defaultFn = self.defaultFn; if(defaultFn) { ef = self._createFacade(args); if ((!self.defaultTargetOnly) || (host === ef.target)) { defaultFn.apply(host, args); } } } // 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; }; /** * @method _hasPotentialSubscribers * @for CustomEvent * @private * @return {boolean} Whether the event has potential subscribers or not */ CEProto._hasPotentialSubscribers = function() { return this.hasSubs() || this.host._yuievt.hasTargets || this.broadcast; }; /** * Internal utility method to create a new facade instance and * insert it into the fire argument list, accounting for any payload * merging which needs to happen. * * This used to be called `_getFacade`, but the name seemed inappropriate * when it was used without a need for the return value. * * @method _createFacade * @private * @param fireArgs {Array} The arguments passed to "fire", which need to be * shifted (and potentially merged) when the facade is added. * @return {EventFacade} The event facade created. */ // TODO: Remove (private) _getFacade alias, once synthetic.js is updated. CEProto._createFacade = CEProto._getFacade = function(fireArgs) { var userArgs = this.details, firstArg = userArgs && userArgs[0], firstArgIsObj = (firstArg && (typeof firstArg === "object")), ef = this._facade; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } if (firstArgIsObj) { // protect the event facade properties mixFacadeProps(ef, firstArg); // Allow the event type to be faked http://yuilibrary.com/projects/yui3/ticket/2528376 if (firstArg.type) { ef.type = firstArg.type; } if (fireArgs) { fireArgs[0] = ef; } } else { if (fireArgs) { fireArgs.unshift(ef); } } // update the details field with the arguments 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; }; /** * Utility method to manipulate the args array passed in, to add the event facade, * if it's not already the first arg. * * @method _addFacadeToArgs * @private * @param {Array} The arguments to manipulate */ CEProto._addFacadeToArgs = function(args) { var e = args[0]; // Trying not to use instanceof, just to avoid potential cross Y edge case issues. if (!(e && e.halt && e.stopImmediatePropagation && e.stopPropagation && e._event)) { this._createFacade(args); } }; /** * 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) { var etState = this._yuievt; if (!etState.targets) { etState.targets = {}; } etState.targets[Y.stamp(o)] = o; etState.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { var targets = this._yuievt.targets; return targets ? YObject.values(targets) : []; }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { var targets = this._yuievt.targets; if (targets) { delete targets[Y.stamp(o, true)]; if (YObject.size(targets) === 0) { this._yuievt.hasTargets = false; } } }; /** * 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, ce, i, bc, ce2, type = evt && evt.type, 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._yuievt.events[type]; if (t._hasSiblings) { 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 { if (ce2) { 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; // TODO: See what's getting in the way of changing this to use // the more performant ce._fire(args || evt.details || []). // Something in Widget Parent/Child tests is not happy if we // change it - maybe evt.details related? 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; }; /** * @method _hasPotentialSubscribers * @for EventTarget * @private * @param {String} fullType The fully prefixed type name * @return {boolean} Whether the event has potential subscribers or not */ ETProto._hasPotentialSubscribers = function(fullType) { var etState = this._yuievt, e = etState.events[fullType]; if (e) { return e.hasSubs() || etState.hasTargets || e.broadcast; } else { return false; } }; 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; if (this._node) { nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; } return nodelist || Y.all([]); }, // 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 | null} The last item in the NodeList, or null if the list is empty. */ '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 | null} The first item in the NodeList, or null if the NodeList is empty. */ '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() { var node = this; if (node._node.nodeType === 11) { // 11 === Node.DOCUMENT_FRAGMENT_NODE // "this", when it is a document fragment, must be cloned because // the nodes contained in the fragment actually disappear once // the fragment is appended anywhere node = node.create("<div/>").append(node.cloneNode(true)); } return node.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 remove the hidden attribute and reset the CSS style.display property. * @method _show * @protected * @chainable */ _show: function() { this.removeAttribute('hidden'); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getAttribute(this._node, 'hidden') === 'true'; }, /** * 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 set the hidden attribute to true and set the CSS style.display to 'none'. * @method _hide * @protected * @chainable */ _hide: function() { this.setAttribute('hidden', true); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. 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 _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 && !Y.DOM.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, emitFacade: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 = Y.DOM.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 = Y.DOM.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 Y.DOM.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) ? Y.DOM.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) ? Y.DOM.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) { /*jshint maxlen:300*/ } 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 {Boolean} True if in region, false if not. */ 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> * <dt>credentials</dt> * <dd>Set the value to 'true' to set XHR.withCredentials property to true.</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 = [], visited, tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName, isUniversal; 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() visited = []; child = root.firstChild; isUniversal = tagName === "*"; while (child) { while (child) { // IE 6-7 considers comment nodes as element nodes, and gives them the tagName "!". // We can filter them out by checking if its tagName is > "@". // This also avoids a superflous nodeType === 1 check. if (child.tagName > "@" && (isUniversal || child.tagName === tagName)) { nodes.push(child); } // We may need to traverse back up the tree to find more unvisited subtrees. visited.push(child); child = child.firstChild; } // Find the most recently visited node who has a next sibling. while (visited.length > 0 && !child) { child = visited.pop().nextSibling; } } } 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: 2, warn: 4, error: 8 }; /** * 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, minlevel, 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]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } 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('*');
plain/static/aloha/demo/boilerplate/js/libs/jquery-1.6.1.js
goodagood/gg
/*! * jQuery JavaScript Library v1.6.1 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu May 12 15:04:36 2011 -0400 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document, navigator = window.navigator, location = window.location; var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for digits rdigit = /\d/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, // Useragent RegExp rwebkit = /(webkit)[ \/]([\w.]+)/, ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, rmsie = /(msie) ([\w.]+)/, rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // The deferred used on DOM ready readyList, // The ready event handler DOMContentLoaded, // Save a reference to some core methods toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty, push = Array.prototype.push, slice = Array.prototype.slice, trim = String.prototype.trim, indexOf = Array.prototype.indexOf, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), or $(undefined) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // The body element only exists once, optimize finding it if ( selector === "body" && !context && document.body ) { this.context = document; this[0] = document.body; this.selector = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? 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 = quickExpr.exec( selector ); } // Verify a match, and that no context was specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = (context ? context.ownerDocument || context : document); // If a single string is passed in and it's a single tag // just do a createElement and skip the rest ret = rsingleTag.exec( selector ); if ( ret ) { if ( jQuery.isPlainObject( context ) ) { selector = [ document.createElement( ret[1] ) ]; jQuery.fn.attr.call( selector, context, true ); } else { selector = [ doc.createElement( ret[1] ) ]; } } else { ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); selector = (ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment).childNodes; } 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.6.1", // 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 slice.call( this, 0 ); }, // 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 = this.constructor(); if ( jQuery.isArray( elems ) ) { push.apply( ret, elems ); } else { jQuery.merge( ret, 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 ) { // Attach the listeners jQuery.bindReady(); // Add the callback readyList.done( fn ); return this; }, eq: function( 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( slice.apply( this, arguments ), "slice", 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: 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 ) { // Either a released hold or an DOMready/load event and not yet ready if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { // 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" ).unbind( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery._Deferred(); // Catch cases where $(document).ready() is called after the // browser event has already occurred. if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready return setTimeout( jQuery.ready, 1 ); } // Mozilla, Opera and webkit nightlies currently support this event 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 if ( document.attachEvent ) { // 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 toplevel = false; try { toplevel = window.frameElement == null; } catch(e) {} if ( document.documentElement.doScroll && toplevel ) { doScrollCheck(); } } }, // 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"; }, // A crude way of determining if an object is a window isWindow: function( obj ) { return obj && typeof obj === "object" && "setInterval" in obj; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ 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; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { 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 || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw msg; }, parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { 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 // (xml & tmp used internally) parseXML: function( data , xml , tmp ) { 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 ); } tmp = xml.documentElement; if ( ! tmp || ! tmp.nodeName || tmp.nodeName === "parsererror" ) { 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 && 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 ); } }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( object, callback, args ) { var name, i = 0, length = object.length, isObj = length === undefined || jQuery.isFunction( object ); if ( args ) { if ( isObj ) { for ( name in object ) { if ( callback.apply( object[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( object[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in object ) { if ( callback.call( object[ name ], name, object[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { break; } } } } return object; }, // Use native String.trim function wherever possible trim: trim ? function( text ) { return text == null ? "" : trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); }, // results is for internal usage only makeArray: function( array, results ) { var ret = results || []; if ( array != null ) { // The window, strings (and functions) also have 'length' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 var type = jQuery.type( array ); if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { push.call( ret, array ); } else { jQuery.merge( ret, array ); } } return ret; }, inArray: function( elem, array ) { if ( indexOf ) { return indexOf.call( array, elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; }, merge: function( first, second ) { var i = first.length, j = 0; if ( typeof second.length === "number" ) { for ( var l = second.length; 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 ret = [], retVal; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( var i = 0, length = elems.length; 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 ) { if ( typeof context === "string" ) { var 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 var args = slice.call( arguments, 2 ), proxy = function() { return fn.apply( context, args.concat( 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 || proxy.guid || jQuery.guid++; return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its a function access: function( elems, key, value, exec, fn, pass ) { var length = elems.length; // Setting many attributes if ( typeof key === "object" ) { for ( var k in key ) { jQuery.access( elems, k, key[k], exec, fn, value ); } return elems; } // Setting one attribute if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = !pass && exec && jQuery.isFunction(value); for ( var i = 0; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } return elems; } // Getting an attribute return length ? fn( elems[0], key ) : undefined; }, now: function() { return (new Date()).getTime(); }, // Use of jQuery.browser is frowned upon. // More details: http://docs.jquery.com/Utilities/jQuery.browser uaMatch: function( ua ) { ua = ua.toLowerCase(); var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }, 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; }, browser: {} }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); browserMatch = jQuery.uaMatch( userAgent ); if ( browserMatch.browser ) { jQuery.browser[ browserMatch.browser ] = true; jQuery.browser.version = browserMatch.version; } // Deprecated, use jQuery.browser.webkit instead if ( jQuery.browser.webkit ) { jQuery.browser.safari = true; } // IE doesn't match non-breaking spaces with \s if ( rnotwhite.test( "\xA0" ) ) { trimLeft = /^[\s\xA0]+/; trimRight = /[\s\xA0]+$/; } // All jQuery objects should point back to these rootjQuery = jQuery(document); // Cleanup functions for the document ready method if ( document.addEventListener ) { DOMContentLoaded = function() { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); }; } else if ( document.attachEvent ) { DOMContentLoaded = function() { // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( document.readyState === "complete" ) { document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; } // The DOM ready check for Internet Explorer function doScrollCheck() { if ( jQuery.isReady ) { return; } try { // If IE is used, use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ document.documentElement.doScroll("left"); } catch(e) { setTimeout( doScrollCheck, 1 ); return; } // and execute any waiting functions jQuery.ready(); } // Expose jQuery to the global object return jQuery; })(); var // Promise methods promiseMethods = "done fail isResolved isRejected promise then always pipe".split( " " ), // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ // Create a simple deferred (one callbacks list) _Deferred: function() { var // callbacks list callbacks = [], // stored [ context , args ] fired, // to avoid firing when already doing so firing, // flag to know if the deferred has been cancelled cancelled, // the deferred itself deferred = { // done( f1, f2, ...) done: function() { if ( !cancelled ) { var args = arguments, i, length, elem, type, _fired; if ( fired ) { _fired = fired; fired = 0; } for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { deferred.done.apply( deferred, elem ); } else if ( type === "function" ) { callbacks.push( elem ); } } if ( _fired ) { deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] ); } } return this; }, // resolve with given context and args resolveWith: function( context, args ) { if ( !cancelled && !fired && !firing ) { // make sure args are available (#8421) args = args || []; firing = 1; try { while( callbacks[ 0 ] ) { callbacks.shift().apply( context, args ); } } finally { fired = [ context, args ]; firing = 0; } } return this; }, // resolve with this as context and given arguments resolve: function() { deferred.resolveWith( this, arguments ); return this; }, // Has this deferred been resolved? isResolved: function() { return !!( firing || fired ); }, // Cancel cancel: function() { cancelled = 1; callbacks = []; return this; } }; return deferred; }, // Full fledged deferred (two callbacks list) Deferred: function( func ) { var deferred = jQuery._Deferred(), failDeferred = jQuery._Deferred(), promise; // Add errorDeferred methods, then and promise jQuery.extend( deferred, { then: function( doneCallbacks, failCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ); return this; }, always: function() { return deferred.done.apply( deferred, arguments ).fail.apply( this, arguments ); }, fail: failDeferred.done, rejectWith: failDeferred.resolveWith, reject: failDeferred.resolve, isRejected: failDeferred.isResolved, pipe: function( fnDone, fnFail ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ] }, function( handler, data ) { var fn = data[ 0 ], action = data[ 1 ], returned; if ( jQuery.isFunction( fn ) ) { deferred[ handler ](function() { returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise().then( newDefer.resolve, newDefer.reject ); } else { newDefer[ action ]( returned ); } }); } else { deferred[ handler ]( newDefer[ action ] ); } }); }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { if ( obj == null ) { if ( promise ) { return promise; } promise = obj = {}; } var i = promiseMethods.length; while( i-- ) { obj[ promiseMethods[i] ] = deferred[ promiseMethods[i] ]; } return obj; } }); // Make sure only one callback list will be used deferred.done( failDeferred.cancel ).fail( deferred.cancel ); // Unexpose cancel delete deferred.cancel; // Call given func if any if ( func ) { func.call( deferred, deferred ); } return deferred; }, // Deferred helper when: function( firstParam ) { var args = arguments, i = 0, length = args.length, count = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { // Strange bug in FF4: // Values changed onto the arguments object sometimes end up as undefined values // outside the $.when method. Cloning the object into a fresh array solves the issue deferred.resolveWith( deferred, sliceDeferred.call( args, 0 ) ); } }; } if ( length > 1 ) { for( ; i < length; i++ ) { if ( args[ i ] && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return deferred.promise(); } }); jQuery.support = (function() { var div = document.createElement( "div" ), documentElement = document.documentElement, all, a, select, opt, input, marginDiv, support, fragment, body, bodyStyle, tds, events, eventName, i, isSupported; // Preliminary tests div.setAttribute("className", "t"); div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName( "*" ); a = div.getElementsByTagName( "a" )[ 0 ]; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement( "select" ); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName( "input" )[ 0 ]; 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.55$/.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", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true }; // 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", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; div.detachEvent( "onclick", click ); }); div.cloneNode( true ).fireEvent( "onclick" ); } // Check if a radio maintains it's 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"); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; div.innerHTML = ""; // Figure out if the W3C box model works as expected div.style.width = div.style.paddingLeft = "1px"; // We use our own, invisible, body body = document.createElement( "body" ); bodyStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, // Set background to avoid IE crashes when removing (#9028) background: "none" }; for ( i in bodyStyle ) { body.style[ i ] = bodyStyle[ i ]; } body.appendChild( div ); documentElement.insertBefore( body, documentElement.firstChild ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // 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.style.display = "inline"; div.style.zoom = 1; support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = ""; div.innerHTML = "<div style='width:4px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); } div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); // 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) 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 ); div.innerHTML = ""; // 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 if ( document.defaultView && document.defaultView.getComputedStyle ) { marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( document.defaultView.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } // Remove the body element we added body.innerHTML = ""; documentElement.removeChild( body ); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/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: 1, change: 1, focusin: 1 } ) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } return support; })(); // Keep track of boxModel jQuery.boxModel = jQuery.support.boxModel; var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([a-z])([A-Z])/g; jQuery.extend({ cache: {}, // Please use with caution 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 internalKey = jQuery.expando, getByName = typeof name === "string", thisCache, // 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[ jQuery.expando ] : elem[ jQuery.expando ] && jQuery.expando; // 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 || (pvt && id && !cache[ id ][ internalKey ])) && 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[ jQuery.expando ] = id = ++jQuery.uuid; } else { id = jQuery.expando; } } if ( !cache[ id ] ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. 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 ][ internalKey ] = jQuery.extend(cache[ id ][ internalKey ], name); } else { cache[ id ] = jQuery.extend(cache[ id ], name); } } thisCache = cache[ id ]; // Internal jQuery data is stored in a separate object inside the object's data // cache in order to avoid key collisions between internal data and user-defined // data if ( pvt ) { if ( !thisCache[ internalKey ] ) { thisCache[ internalKey ] = {}; } thisCache = thisCache[ internalKey ]; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // TODO: This is a hack for 1.5 ONLY. It will be removed in 1.6. Users should // not attempt to inspect the internal events object using jQuery.data, as this // internal data object is undocumented and subject to change. if ( name === "events" && !thisCache[name] ) { return thisCache[ internalKey ] && thisCache[ internalKey ].events; } return getByName ? thisCache[ jQuery.camelCase( name ) ] : thisCache; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var internalKey = jQuery.expando, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, // See jQuery.data for more information 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 ) { var thisCache = pvt ? cache[ id ][ internalKey ] : cache[ id ]; if ( thisCache ) { delete thisCache[ name ]; // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !isEmptyDataObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( pvt ) { delete cache[ id ][ internalKey ]; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject(cache[ id ]) ) { return; } } var internalCache = cache[ id ][ internalKey ]; // Browsers that fail expando deletion also refuse to delete expandos on // the window, but it will allow it on all other JS objects; other browsers // don't care if ( jQuery.support.deleteExpando || cache != window ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the entire user cache at once because it's faster than // iterating through each key, but we need to continue to persist internal // data if it existed if ( internalCache ) { cache[ id ] = {}; // TODO: This is a hack for 1.5 ONLY. Avoids exposing jQuery // metadata on plain JS objects when the object is serialized using // JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } cache[ id ][ internalKey ] = internalCache; // Otherwise, we need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist } else if ( isNode ) { // 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 ( jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } else { elem[ jQuery.expando ] = 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 ) { if ( elem.nodeName ) { var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; if ( match ) { return !(match === true || elem.getAttribute("classid") !== match); } } return true; } }); jQuery.fn.extend({ data: function( key, value ) { var data = null; if ( typeof key === "undefined" ) { if ( this.length ) { data = jQuery.data( this[0] ); if ( this[0].nodeType === 1 ) { var attr = this[0].attributes, name; for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( this[0], name, data[ name ] ); } } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var parts = key.split("."); parts[1] = parts[1] ? "." + parts[1] : ""; if ( value === undefined ) { data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); // Try to fetch any internally stored data first if ( data === undefined && this.length ) { data = jQuery.data( this[0], key ); data = dataAttr( this[0], key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } else { return this.each(function() { var $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.triggerHandler( "changeData" + parts[1] + "!", args ); }); } }, 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-$2" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( data ) ? parseFloat( 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; } // TODO: This is a hack for 1.5 ONLY to allow objects with a single toJSON // property to be considered empty objects; this property always exists in // order to make sure JSON.stringify does not expose internal metadata function isEmptyDataObject( obj ) { for ( var name in obj ) { if ( name !== "toJSON" ) { return false; } } return true; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery.data( elem, deferDataKey, undefined, true ); if ( defer && ( src === "queue" || !jQuery.data( elem, queueDataKey, undefined, true ) ) && ( src === "mark" || !jQuery.data( elem, markDataKey, undefined, true ) ) ) { // Give room for hard-coded callbacks to fire first // and eventually mark/queue something else on the element setTimeout( function() { if ( !jQuery.data( elem, queueDataKey, undefined, true ) && !jQuery.data( elem, markDataKey, undefined, true ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.resolve(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = (type || "fx") + "mark"; jQuery.data( elem, type, (jQuery.data(elem,type,undefined,true) || 0) + 1, true ); } }, _unmark: function( force, elem, type ) { if ( force !== true ) { type = elem; elem = force; force = false; } if ( elem ) { type = type || "fx"; var key = type + "mark", count = force ? 0 : ( (jQuery.data( elem, key, undefined, true) || 1 ) - 1 ); if ( count ) { jQuery.data( elem, key, count, true ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { if ( elem ) { type = (type || "fx") + "queue"; var q = jQuery.data( elem, type, undefined, true ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !q || jQuery.isArray(data) ) { q = jQuery.data( elem, type, jQuery.makeArray(data), true ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), defer; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift("inprogress"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); jQuery.fn.extend({ queue: function( type, data ) { if ( typeof type !== "string" ) { data = type; type = "fx"; } if ( data === undefined ) { return jQuery.queue( this[0], type ); } return this.each(function() { var queue = jQuery.queue( this, type, data ); 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() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, 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, object ) { if ( typeof type !== "string" ) { object = type; type = undefined; } type = type || "fx"; var defer = jQuery.Deferred(), elements = this, i = elements.length, count = 1, deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", tmp; function resolve() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } } while( i-- ) { if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && jQuery.data( elements[ i ], deferDataKey, jQuery._Deferred(), true ) )) { count++; tmp.done( resolve ); } } resolve(); return defer.promise(); } }); var rclass = /[\n\t\r]/g, rspace = /\s+/, 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, rinvalidChar = /\:/, formHook, boolHook; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.prop ); }, 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 ) { if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class") || "") ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspace ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var c = 0, cl = classNames.length; c < cl; c++ ) { className = className.replace(" " + classNames[c] + " ", " "); } elem.className = jQuery.trim( className ); } else { elem.className = ""; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), 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( rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space seperated 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 + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var self = jQuery(this), val; 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.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; // 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, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (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 ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } 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; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attrFix: { // Always normalize to ensure hook usage tabindex: "tabIndex" }, attr: function( elem, name, value, pass ) { var nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( !("getAttribute" in elem) ) { return jQuery.prop( elem, name, value ); } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Normalize the name if needed name = notxml && jQuery.attrFix[ name ] || name; hooks = jQuery.attrHooks[ name ]; if ( !hooks ) { // Use boolHook for boolean attributes if ( rboolean.test( name ) && (typeof value === "boolean" || value === undefined || value.toLowerCase() === name.toLowerCase()) ) { hooks = boolHook; // Use formHook for forms and if the name contains certain characters } else if ( formHook && (jQuery.nodeName( elem, "form" ) || rinvalidChar.test( name )) ) { hooks = formHook; } } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return undefined; } 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 ) { return hooks.get( elem, name ); } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, name ) { var propName; if ( elem.nodeType === 1 ) { name = jQuery.attrFix[ name ] || name; if ( jQuery.support.getSetAttribute ) { // Use removeAttribute in browsers that support it elem.removeAttribute( name ); } else { jQuery.attr( elem, name, "" ); elem.removeAttributeNode( elem.getAttributeNode( name ) ); } // Set corresponding property to false for boolean attributes if ( rboolean.test( name ) && (propName = jQuery.propFix[ name ] || name) 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; } } }, 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; } } }, 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 nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return undefined; } var ret, hooks, notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // Try to normalize/fix the name name = notxml && 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 )) !== undefined ) { return ret; } else { return elem[ name ]; } } }, propHooks: {} }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties return elem[ jQuery.propFix[ name ] || name ] ? 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 ] = value; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // Use the value property for back compat // Use the formHook for button elements in IE6/7 (#1954) jQuery.attrHooks.value = { get: function( elem, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.get( elem, name ); } return elem.value; }, set: function( elem, value, name ) { if ( formHook && jQuery.nodeName( elem, "button" ) ) { return formHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !jQuery.support.getSetAttribute ) { // propFix is more comprehensive and contains all fixes jQuery.attrFix = jQuery.propFix; // Use this for any attribute on a form in IE6/7 formHook = jQuery.attrHooks.name = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); // Return undefined if nodeValue is empty string return ret && ret.nodeValue !== "" ? ret.nodeValue : undefined; }, set: function( elem, value, name ) { // Check form objects in IE (multiple bugs related) // Only use nodeValue if the attribute node exists on the form var ret = elem.getAttributeNode( name ); if ( ret ) { ret.nodeValue = value; return 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; } } }); }); } // 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; } } } }); } // 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 hasOwn = Object.prototype.hasOwnProperty, rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspaces = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery._data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } var events = elemData.events, eventHandle = elemData.handle; if ( !events ) { elemData.events = events = {}; } 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.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // 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 the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have 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, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ), events = elemData && elemData.events; if ( !elemData || !events ) { return; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem, undefined, 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 ) { // Event object or event type var type = event.type || event, namespaces = [], exclusive; 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.exclusive = exclusive; event.namespace = namespaces.join("."); event.namespace_re = new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); // triggerHandler() and global events don't bubble or run the default action if ( onlyHandlers || !elem ) { event.preventDefault(); event.stopPropagation(); } // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document jQuery.each( jQuery.cache, function() { // internalKey variable is just used to make it easier to find // and potentially change this stuff later; currently it just // points to jQuery.expando var internalKey = jQuery.expando, internalCache = this[ internalKey ]; if ( internalCache && internalCache.events && internalCache.events[ type ] ) { jQuery.event.trigger( event, data, internalCache.handle.elem ); } }); return; } // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // Clean up the event in case it is being reused event.result = undefined; event.target = elem; // Clone any incoming data and prepend the event, creating the handler arg list data = data ? jQuery.makeArray( data ) : []; data.unshift( event ); var cur = elem, // IE doesn't like method names with a colon (#3533, #8272) ontype = type.indexOf(":") < 0 ? "on" + type : ""; // Fire event on the current element, then bubble up the DOM tree do { var handle = jQuery._data( cur, "handle" ); event.currentTarget = cur; if ( handle ) { handle.apply( cur, data ); } // Trigger an inline bound script if ( ontype && jQuery.acceptData( cur ) && cur[ ontype ] && cur[ ontype ].apply( cur, data ) === false ) { event.result = false; event.preventDefault(); } // Bubble up to document, then to window cur = cur.parentNode || cur.ownerDocument || cur === event.target.ownerDocument && window; } while ( cur && !event.isPropagationStopped() ); // If nobody prevented the default action, do it now if ( !event.isDefaultPrevented() ) { var old, special = jQuery.event.special[ type ] || {}; if ( (!special._default || special._default.call( elem.ownerDocument, event ) === 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. // IE<9 dies on focus to hidden element (#1486), may want to revisit a try/catch. try { if ( ontype && elem[ type ] ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } jQuery.event.triggered = type; elem[ type ](); } } catch ( ieError ) {} if ( old ) { elem[ ontype ] = old; } jQuery.event.triggered = undefined; } } return event.result; }, handle: function( event ) { event = jQuery.event.fix( event || window.event ); // Snapshot the handlers list since a called handler may add/remove events. var handlers = ((jQuery._data( this, "events" ) || {})[ event.type ] || []).slice(0), run_all = !event.exclusive && !event.namespace, args = Array.prototype.slice.call( arguments, 0 ); // Use the fix-ed Event rather than the (read-only) native event args[0] = event; event.currentTarget = this; for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Triggered event must 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event. if ( run_all || event.namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } return event.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( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var eventDocument = event.target.ownerDocument || document, doc = eventDocument.documentElement, body = eventDocument.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); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, 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; } } } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { 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 ); } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.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 }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // set the correct event type event.type = event.data; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Chrome does something similar, the parentNode property // can be accessed but is null. if ( parent && parent !== document && !parent.parentNode ) { return; } // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( !jQuery.nodeName( this, "form" ) ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( jQuery.nodeName( elem, "select" ) ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery._data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery._data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( type === "radio" || type === "checkbox" || jQuery.nodeName( elem, "select" ) ) { testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = jQuery.nodeName( elem, "input" ) ? elem.type : ""; if ( (e.keyCode === 13 && !jQuery.nodeName( elem, "textarea" ) ) || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery._data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { // 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. // Don't pass args or remember liveFired; they apply to the donor event. var event = jQuery.extend( {}, args[ 0 ] ); event.type = type; event.originalEvent = {}; event.liveFired = undefined; jQuery.event.handle.call( elem, event ); if ( event.isDefaultPrevented() ) { args[ 0 ].preventDefault(); } } // 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; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( donor ) { // Donor event is always a native one; fix it and switch its type. // Let focusin/out handler cancel the donor focus/blur event. var e = jQuery.event.fix( donor ); e.type = fix; e.originalEvent = {}; jQuery.event.trigger( e, null, e.target ); if ( e.isDefaultPrevented() ) { donor.preventDefault(); } } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { var handler; // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( arguments.length === 2 || data === false ) { fn = data; data = undefined; } if ( name === "one" ) { handler = function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }; handler.guid = fn.guid || jQuery.guid++; } else { handler = fn; } if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, 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 ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( name === "die" && !types && origSelector && origSelector.charAt(0) === "." ) { context.unbind( origSelector ); return this; } if ( data === false || jQuery.isFunction( data ) ) { fn = data || returnFalse; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( liveMap[ type ] ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery._data( this, "events" ); // Make sure we avoid non-left-click bubbling in Firefox (#3861) and disabled elements in IE (#6911) if ( event.liveFired === this || !events || !events.live || event.target.disabled || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) && !close.elem.disabled ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; // Make sure not to accidentally match a child element with the same selector if ( related && jQuery.contains( elem, related ) ) { related = elem; } } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspaces, "&"); } 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").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.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); /*! * Sizzle CSS Selector Engine * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rNonWord = /\W/; // Here we check if the JavaScript engine is using some sort of // optimization where it does not always call our comparision // function. If that is the case, discard the hasDuplicate value. // Thus far that includes Google Chrome. [0, 0].sort(function() { baseHasDuplicate = false; return 0; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var origContext = context; if ( context.nodeType !== 1 && context.nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } var m, set, checkSet, extra, ret, cur, pop, i, prune = true, contextXML = Sizzle.isXML( context ), parts = [], soFar = selector; // Reset the position of the chunker regexp (start from head) do { chunker.exec( "" ); m = chunker.exec( soFar ); if ( m ) { soFar = m[3]; parts.push( m[1] ); if ( m[2] ) { extra = m[3]; break; } } } while ( m ); if ( parts.length > 1 && origPOS.exec( selector ) ) { if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { set = posProcess( parts[0] + parts[1], context ); } else { set = Expr.relative[ parts[0] ] ? [ context ] : Sizzle( parts.shift(), context ); while ( parts.length ) { selector = parts.shift(); if ( Expr.relative[ selector ] ) { selector += parts.shift(); } set = posProcess( selector, set ); } } } else { // Take a shortcut and set the context if the root selector is an ID // (but not if it'll be faster if the inner selector is an ID) if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { ret = Sizzle.find( parts.shift(), context, contextXML ); context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; } if ( context ) { ret = seed ? { expr: parts.pop(), set: makeArray(seed) } : Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; if ( parts.length > 0 ) { checkSet = makeArray( set ); } else { prune = false; } while ( parts.length ) { cur = parts.pop(); pop = cur; if ( !Expr.relative[ cur ] ) { cur = ""; } else { pop = parts.pop(); } if ( pop == null ) { pop = context; } Expr.relative[ cur ]( checkSet, pop, contextXML ); } } else { checkSet = parts = []; } } if ( !checkSet ) { checkSet = set; } if ( !checkSet ) { Sizzle.error( cur || selector ); } if ( toString.call(checkSet) === "[object Array]" ) { if ( !prune ) { results.push.apply( results, checkSet ); } else if ( context && context.nodeType === 1 ) { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { results.push( set[i] ); } } } else { for ( i = 0; checkSet[i] != null; i++ ) { if ( checkSet[i] && checkSet[i].nodeType === 1 ) { results.push( set[i] ); } } } } else { makeArray( checkSet, results ); } if ( extra ) { Sizzle( extra, origContext, results, seed ); Sizzle.uniqueSort( results ); } return results; }; Sizzle.uniqueSort = function( results ) { if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( var i = 1; i < results.length; i++ ) { if ( results[i] === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; Sizzle.matches = function( expr, set ) { return Sizzle( expr, null, null, set ); }; Sizzle.matchesSelector = function( node, expr ) { return Sizzle( expr, null, null, [node] ).length > 0; }; Sizzle.find = function( expr, context, isXML ) { var set; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace( rBackslash, "" ); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( "*" ) : []; } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, filter = Expr.filter[ type ], left = match[1]; anyFound = false; match.splice(1,1); if ( left.substr( left.length - 1 ) === "\\" ) { continue; } if ( curLoop === result ) { result = []; } if ( Expr.preFilter[ type ] ) { match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); if ( !match ) { anyFound = found = true; } else if ( match === true ) { continue; } } if ( match ) { for ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var pass = not ^ !!found; if ( inplace && found != null ) { if ( pass ) { anyFound = true; } else { curLoop[i] = false; } } else if ( pass ) { result.push( item ); anyFound = true; } } } } if ( found !== undefined ) { if ( !inplace ) { curLoop = result; } expr = expr.replace( Expr.match[ type ], "" ); if ( !anyFound ) { return []; } break; } } } // Improper expression if ( expr === old ) { if ( anyFound == null ) { Sizzle.error( expr ); } else { break; } } old = expr; } return curLoop; }; Sizzle.error = function( msg ) { throw "Syntax error, unrecognized expression: " + msg; }; var Expr = Sizzle.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( elem ) { return elem.getAttribute( "href" ); }, type: function( elem ) { return elem.getAttribute( "type" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !rNonWord.test( part ), isPartStrNotTag = isPartStr && !isTag; if ( isTag ) { part = part.toLowerCase(); } for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { if ( (elem = checkSet[i]) ) { while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? elem || false : elem === part; } } if ( isPartStrNotTag ) { Sizzle.filter( part, checkSet, true ); } }, ">": function( checkSet, part ) { var elem, isPartStr = typeof part === "string", i = 0, l = checkSet.length; if ( isPartStr && !rNonWord.test( part ) ) { part = part.toLowerCase(); for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { var parent = elem.parentNode; checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; } } } else { for ( ; i < l; i++ ) { elem = checkSet[i]; if ( elem ) { checkSet[i] = isPartStr ? elem.parentNode : elem.parentNode === part; } } if ( isPartStr ) { Sizzle.filter( part, checkSet, true ); } } }, "": function(checkSet, part, isXML){ var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); }, "~": function( checkSet, part, isXML ) { var nodeCheck, doneName = done++, checkFn = dirCheck; if ( typeof part === "string" && !rNonWord.test( part ) ) { part = part.toLowerCase(); nodeCheck = part; checkFn = dirNodeCheck; } checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); } }, find: { ID: function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }, NAME: function( match, context ) { if ( typeof context.getElementsByName !== "undefined" ) { var ret = [], results = context.getElementsByName( match[1] ); for ( var i = 0, l = results.length; i < l; i++ ) { if ( results[i].getAttribute("name") === match[1] ) { ret.push( results[i] ); } } return ret.length === 0 ? null : ret; } }, TAG: function( match, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( match[1] ); } } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace( rBackslash, "" ) + " "; if ( isXML ) { return match; } for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { if ( elem ) { if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace( rBackslash, "" ); }, TAG: function( match, curLoop ) { return match[1].replace( rBackslash, "" ).toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { if ( !match[2] ) { Sizzle.error( match[0] ); } match[2] = match[2].replace(/^\+|\s*/g, ''); // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); // calculate the numbers (first)n+(last) including if they are negative match[2] = (test[1] + (test[2] || 1)) - 0; match[3] = test[3] - 0; } else if ( match[2] ) { Sizzle.error( match[0] ); } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1] = match[1].replace( rBackslash, "" ); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } // Handle if an un-quoted value was used match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); if ( match[2] === "~=" ) { match[4] = " " + match[4] + " "; } return match; }, PSEUDO: function( match, curLoop, inplace, result, not ) { if ( match[1] === "not" ) { // If we're dealing with a complex expression, or a simple one if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { match[3] = Sizzle(match[3], null, null, curLoop); } else { var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); if ( !inplace ) { result.push.apply( result, ret ); } return false; } } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { return true; } return match; }, POS: function( match ) { match.unshift( true ); return match; } }, filters: { enabled: function( elem ) { return elem.disabled === false && elem.type !== "hidden"; }, disabled: function( elem ) { return elem.disabled === true; }, checked: function( elem ) { return elem.checked === true; }, 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 !!elem.firstChild; }, empty: function( elem ) { return !elem.firstChild; }, has: function( elem, i, match ) { return !!Sizzle( match[3], elem ).length; }, header: function( elem ) { return (/h\d/i).test( elem.nodeName ); }, text: function( elem ) { var attr = elem.getAttribute( "type" ), type = elem.type; // 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" && "text" === type && ( attr === type || attr === null ); }, radio: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; }, checkbox: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; }, file: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; }, password: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; }, submit: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "submit" === elem.type; }, image: function( elem ) { return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; }, reset: function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && "reset" === elem.type; }, button: function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && "button" === elem.type || name === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); }, focus: function( elem ) { return elem === elem.ownerDocument.activeElement; } }, setFilters: { first: function( elem, i ) { return i === 0; }, last: function( elem, i, match, array ) { return i === array.length - 1; }, even: function( elem, i ) { return i % 2 === 0; }, odd: function( elem, i ) { return i % 2 === 1; }, lt: function( elem, i, match ) { return i < match[3] - 0; }, gt: function( elem, i, match ) { return i > match[3] - 0; }, nth: function( elem, i, match ) { return match[3] - 0 === i; }, eq: function( elem, i, match ) { return match[3] - 0 === i; } }, filter: { PSEUDO: function( elem, match, i, array ) { var name = match[1], filter = Expr.filters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } else if ( name === "contains" ) { return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0; } else if ( name === "not" ) { var not = match[3]; for ( var j = 0, l = not.length; j < l; j++ ) { if ( not[j] === elem ) { return false; } } return true; } else { Sizzle.error( name ); } }, CHILD: function( elem, match ) { var type = match[1], 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; case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var diff = elem.nodeIndex - last; if ( first === 0 ) { return diff === 0; } else { return ( diff % first === 0 && diff / first >= 0 ); } } }, ID: function( elem, match ) { return elem.nodeType === 1 && elem.getAttribute("id") === match; }, TAG: function( elem, match ) { return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = Expr.attrHandle[ name ] ? Expr.attrHandle[ name ]( elem ) : elem[ name ] != null ? elem[ name ] : elem.getAttribute( name ), value = result + "", type = match[2], check = match[4]; return result == null ? type === "!=" : type === "=" ? value === check : type === "*=" ? value.indexOf(check) >= 0 : type === "~=" ? (" " + value + " ").indexOf(check) >= 0 : !check ? value && result !== false : type === "!=" ? value !== check : type === "^=" ? value.indexOf(check) === 0 : type === "$=" ? value.substr(value.length - check.length) === check : type === "|=" ? value === check || value.substr(0, check.length + 1) === check + "-" : false; }, POS: function( elem, match, i, array ) { var name = match[2], filter = Expr.setFilters[ name ]; if ( filter ) { return filter( elem, i, match, array ); } } } }; var origPOS = Expr.match.POS, fescape = function(all, num){ return "\\" + (num - 0 + 1); }; for ( var type in Expr.match ) { Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); } var makeArray = function( array, results ) { array = Array.prototype.slice.call( array, 0 ); if ( results ) { results.push.apply( results, array ); return results; } return array; }; // Perform a simple check to determine if the browser is capable of // converting a NodeList to an array using builtin methods. // Also verifies that the returned array holds DOM nodes // (which is not the case in the Blackberry browser) try { Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; // Provide a fallback method if it does not work } catch( e ) { makeArray = function( array, results ) { var i = 0, ret = results || []; if ( toString.call(array) === "[object Array]" ) { Array.prototype.push.apply( ret, array ); } else { if ( typeof array.length === "number" ) { for ( var l = array.length; i < l; i++ ) { ret.push( array[i] ); } } else { for ( ; array[i]; i++ ) { ret.push( array[i] ); } } } return ret; }; } var sortOrder, siblingCheck; if ( document.documentElement.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { return a.compareDocumentPosition ? -1 : 1; } return a.compareDocumentPosition(b) & 4 ? -1 : 1; }; } else { sortOrder = 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 ); }; siblingCheck = function( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // Check to see if the browser returns elements by name when // querying by getElementById (and provide a workaround) (function(){ // We're going to inject a fake input element with a specified name var form = document.createElement("div"), id = "script" + (new Date()).getTime(), root = document.documentElement; form.innerHTML = "<a name='" + id + "'/>"; // Inject it into the root element, check its status, and remove it quickly root.insertBefore( form, root.firstChild ); // The workaround has to do additional checks after a getElementById // Which slows things down for other browsers (hence the branching) if ( document.getElementById( id ) ) { Expr.find.ID = function( match, context, isXML ) { if ( typeof context.getElementById !== "undefined" && !isXML ) { var m = context.getElementById(match[1]); return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; } }; Expr.filter.ID = function( elem, match ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return elem.nodeType === 1 && node && node.nodeValue === match; }; } root.removeChild( form ); // release memory in IE root = form = null; })(); (function(){ // Check to see if the browser returns only elements // when doing getElementsByTagName("*") // Create a fake element var div = document.createElement("div"); div.appendChild( document.createComment("") ); // Make sure no comments are found if ( div.getElementsByTagName("*").length > 0 ) { Expr.find.TAG = function( match, context ) { var results = context.getElementsByTagName( match[1] ); // Filter out possible comments if ( match[1] === "*" ) { var tmp = []; for ( var i = 0; results[i]; i++ ) { if ( results[i].nodeType === 1 ) { tmp.push( results[i] ); } } results = tmp; } return results; }; } // Check to see if an attribute returns normalized href attributes div.innerHTML = "<a href='#'></a>"; if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && div.firstChild.getAttribute("href") !== "#" ) { Expr.attrHandle.href = function( elem ) { return elem.getAttribute( "href", 2 ); }; } // release memory in IE div = null; })(); if ( document.querySelectorAll ) { (function(){ var oldSizzle = Sizzle, div = document.createElement("div"), id = "__sizzle__"; div.innerHTML = "<p class='TEST'></p>"; // Safari can't handle uppercase or unicode characters when // in quirks mode. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { return; } Sizzle = function( query, context, extra, seed ) { context = context || document; // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { // See if we find a selector to speed up var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { // Speed-up: Sizzle("TAG") if ( match[1] ) { return makeArray( context.getElementsByTagName( query ), extra ); // Speed-up: Sizzle(".CLASS") } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { return makeArray( context.getElementsByClassName( match[2] ), extra ); } } if ( context.nodeType === 9 ) { // Speed-up: Sizzle("body") // The body element only exists once, optimize finding it if ( query === "body" && context.body ) { return makeArray( [ context.body ], extra ); // Speed-up: Sizzle("#ID") } else if ( match && match[3] ) { var elem = context.getElementById( match[3] ); // 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[3] ) { return makeArray( [ elem ], extra ); } } else { return makeArray( [], extra ); } } try { return makeArray( context.querySelectorAll(query), extra ); } catch(qsaError) {} // 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 } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { var oldContext = context, old = context.getAttribute( "id" ), nid = old || id, hasParent = context.parentNode, relativeHierarchySelector = /^\s*[+~]/.test( query ); if ( !old ) { context.setAttribute( "id", nid ); } else { nid = nid.replace( /'/g, "\\$&" ); } if ( relativeHierarchySelector && hasParent ) { context = context.parentNode; } try { if ( !relativeHierarchySelector || hasParent ) { return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); } } catch(pseudoError) { } finally { if ( !old ) { oldContext.removeAttribute( "id" ); } } } } return oldSizzle(query, context, extra, seed); }; for ( var prop in oldSizzle ) { Sizzle[ prop ] = oldSizzle[ prop ]; } // release memory in IE div = null; })(); } (function(){ var html = document.documentElement, matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; if ( matches ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9 fails this) var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), pseudoWorks = false; try { // This should fail with an exception // Gecko does not error, returns false instead matches.call( document.documentElement, "[test!='']:sizzle" ); } catch( pseudoError ) { pseudoWorks = true; } Sizzle.matchesSelector = function( node, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); if ( !Sizzle.isXML( node ) ) { try { if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { var ret = matches.call( node, 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, so check for that node.document && node.document.nodeType !== 11 ) { return ret; } } } catch(e) {} } return Sizzle(expr, null, null, [node]).length > 0; }; } })(); (function(){ var div = document.createElement("div"); div.innerHTML = "<div class='test e'></div><div class='test'></div>"; // Opera can't find a second classname (in 9.6) // Also, make sure that getElementsByClassName actually exists if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { return; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; if ( div.getElementsByClassName("e").length === 1 ) { return; } Expr.order.splice(1, 0, "CLASS"); Expr.find.CLASS = function( match, context, isXML ) { if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { return context.getElementsByClassName(match[1]); } }; // release memory in IE div = null; })(); function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = doneName; elem.sizset = i; } if ( elem.nodeName.toLowerCase() === cur ) { match = elem; break; } elem = elem[dir]; } checkSet[i] = match; } } } function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { for ( var i = 0, l = checkSet.length; i < l; i++ ) { var elem = checkSet[i]; if ( elem ) { var match = false; elem = elem[dir]; while ( elem ) { if ( elem.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = doneName; elem.sizset = i; } if ( typeof cur !== "string" ) { if ( elem === cur ) { match = true; break; } } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { match = elem; break; } } elem = elem[dir]; } checkSet[i] = match; } } } if ( document.documentElement.contains ) { Sizzle.contains = function( a, b ) { return a !== b && (a.contains ? a.contains(b) : true); }; } else if ( document.documentElement.compareDocumentPosition ) { Sizzle.contains = function( a, b ) { return !!(a.compareDocumentPosition(b) & 16); }; } else { Sizzle.contains = function() { return false; }; } 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 : 0).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; var posProcess = function( selector, context ) { var match, tmpSet = [], later = "", root = context.nodeType ? [context] : context; // Position selectors must be done after the filter // And so must :not(positional) so we move all PSEUDOs to the end while ( (match = Expr.match.PSEUDO.exec( selector )) ) { later += match[0]; selector = selector.replace( Expr.match.PSEUDO, "" ); } selector = Expr.relative[selector] ? selector + "*" : selector; for ( var i = 0, l = root.length; i < l; i++ ) { Sizzle( selector, root[i], tmpSet ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.filters; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })(); var runtil = /Until$/, rparentsprev = /^(?:parents|prevUntil|prevAll)/, // Note: This RegExp should be improved, or likely pulled from Sizzle rmultiselector = /,/, isSimple = /^.[^:#\[\.,]*$/, slice = Array.prototype.slice, POS = jQuery.expr.match.POS, // 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 self = this, i, l; 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; } } }); } var ret = this.pushStack( "", "find", selector ), length, n, r; 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 targets = jQuery( target ); return this.filter(function() { for ( var i = 0, l = targets.length; i < l; 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" ? jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; // Array if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[ selector ] ) { matches[ selector ] = POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[ selector ]; if ( match.jquery ? match.index( cur ) > -1 : jQuery( cur ).is( match ) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } // String var pos = POS.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( i = 0, l = this.length; i < l; i++ ) { cur = this[i]; while ( cur ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } else { cur = cur.parentNode; if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { break; } } } } 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 ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // 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 ) ); }, andSelf: function() { return this.add( this.prevObject ); } }); // 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; } 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 jQuery.nth( elem, 2, "nextSibling" ); }, prev: function( elem ) { return jQuery.nth( elem, 2, "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.makeArray( elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ), // The variable 'args' was introduced in // https://github.com/jquery/jquery/commit/52a0238 // to work around a bug in Chrome 10 (Dev) and should be removed when the bug is fixed. // http://code.google.com/p/v8/issues/detail?id=1050 args = slice.call(arguments); 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 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, args.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; }, nth: function( cur, result, dir, elem ) { result = result || 1; var num = 0; for ( ; cur; cur = cur[dir] ) { if ( cur.nodeType === 1 && ++num === result ) { break; } } return cur; }, 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; }); } var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/, 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, "", "" ] }; wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE can't serialize <link> and <script> tags normally if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "div<div>", "</div>" ]; } jQuery.fn.extend({ text: function( text ) { if ( jQuery.isFunction(text) ) { return this.each(function(i) { var self = jQuery( this ); self.text( text.call(this, i, self.text()) ); }); } if ( typeof text !== "object" && text !== undefined ) { return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) ); } return jQuery.text( this ); }, 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 ) { return this.each(function() { jQuery( this ).wrapAll( 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.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } else if ( arguments.length ) { var set = jQuery(arguments[0]); set.push.apply( set, this.toArray() ); return this.pushStack( set, "before", arguments ); } }, after: function() { if ( this[0] && this[0].parentNode ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } else if ( arguments.length ) { var set = this.pushStack( this, "after", arguments ); set.push.apply( set, jQuery(arguments[0]).toArray() ); return set; } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { for ( var i = 0, elem; (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() { for ( var i = 0, elem; (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 ) { if ( value === undefined ) { return this[0] && this[0].nodeType === 1 ? this[0].innerHTML.replace(rinlinejQuery, "") : null; // See if we can take a shortcut and just use innerHTML } else if ( typeof value === "string" && !rnocache.test( value ) && (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) && !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) { value = value.replace(rxhtmlTag, "<$1></$2>"); try { for ( var i = 0, l = this.length; i < l; i++ ) { // Remove element nodes and prevent memory leaks if ( this[i].nodeType === 1 ) { jQuery.cleanData( this[i].getElementsByTagName("*") ); this[i].innerHTML = value; } } // If using innerHTML throws an exception, use the fallback method } catch(e) { this.empty().append( value ); } } else if ( jQuery.isFunction( value ) ) { this.each(function(i){ var self = jQuery( this ); self.html( value.call(this, i, self.html()) ); }); } else { this.empty().append( value ); } return this; }, replaceWith: function( value ) { if ( this[0] && this[0].parentNode ) { // 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 ); } }); } else { 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 ) { var results, first, fragment, parent, value = args[0], scripts = []; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback, true ); }); } 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] ) { parent = value && value.parentNode; // If we're in a fragment, just use that instead of building a new one if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) { results = { fragment: parent }; } else { results = jQuery.buildFragment( args, this, scripts ); } fragment = results.fragment; if ( fragment.childNodes.length === 1 ) { first = fragment = fragment.firstChild; } else { first = fragment.firstChild; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], // Make sure that we do not leak memory by inadvertently discarding // the original fragment (which might have attached data) instead of // using it; in addition, use the original fragment object for the last // item instead of first because it can end up being emptied incorrectly // in certain situations (Bug #8070). // Fragments from the fragment cache must always be cloned and never used // in place. results.cacheable || (l > 1 && i < lastIndex) ? jQuery.clone( fragment, true, true ) : fragment ); } } if ( scripts.length ) { jQuery.each( scripts, evalScript ); } } return this; } }); function root( elem, cur ) { return jQuery.nodeName(elem, "table") ? (elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody"))) : elem; } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var internalKey = jQuery.expando, oldData = jQuery.data( src ), curData = jQuery.data( dest, oldData ); // Switch to use the internal data object, if it exists, for the next // stage of data copying if ( (oldData = oldData[ internalKey ]) ) { var events = oldData.events; curData = curData[ internalKey ] = jQuery.extend({}, oldData); if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].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(); // IE6-8 fail to clone children inside object elements that use // the proprietary classid attribute value (rather than the type // attribute) to identify the type of content to display if ( nodeName === "object" ) { dest.outerHTML = src.outerHTML; } else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) { // 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 if ( src.checked ) { 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; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // 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 if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && args[0].charAt(0) === "<" && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1; } 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 ret = [], insert = jQuery( selector ), parent = this.length === 1 && this[0].parentNode; if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( var i = 0, l = insert.length; i < l; i++ ) { var 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 ( "getElementsByTagName" in elem ) { return elem.getElementsByTagName( "*" ); } else if ( "querySelectorAll" in elem ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( elem.getElementsByTagName ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var clone = elem.cloneNode(true), srcElements, destElements, i; 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 ) { 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] ); } } } // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var checkScriptType; context = context || document; // !context.createElement fails in IE with an error but returns typeof 'object' if ( typeof context.createElement === "undefined" ) { context = context.ownerDocument || context[0] && context[0].ownerDocument || document; } var ret = [], j; for ( var i = 0, elem; (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 { // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Trim whitespace, otherwise indexOf won't work as expected var tag = (rtagName.exec( elem ) || ["", ""])[1].toLowerCase(), wrap = wrapMap[ tag ] || wrapMap._default, depth = wrap[0], div = context.createElement("div"); // Go to html and back, then peel off extra wrappers 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> var 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; } } // Resets defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) var len; if ( !jQuery.support.appendChecked ) { if ( elem[0] && typeof (len = elem.length) === "number" ) { for ( j = 0; j < len; j++ ) { findInputs( elem[j] ); } } else { findInputs( elem ); } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { checkScriptType = function( elem ) { return !elem.type || rscriptType.test( elem.type ); }; for ( i = 0; ret[i]; i++ ) { if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) { scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] ); } else { if ( ret[i].nodeType === 1 ) { var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( ret[i] ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, internalKey = jQuery.expando, special = jQuery.event.special, deleteExpando = jQuery.support.deleteExpando; for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) { continue; } id = elem[ jQuery.expando ]; if ( id ) { data = cache[ id ] && cache[ id ][ internalKey ]; if ( data && data.events ) { for ( var 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 ); } } // Null the DOM reference to avoid IE6/7/8 leak (#7054) if ( data.handle ) { data.handle.elem = null; } } if ( deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); } delete cache[ id ]; } } } }); function evalScript( i, elem ) { if ( elem.src ) { jQuery.ajax({ url: elem.src, async: false, dataType: "script" }); } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, rrelNum = /^[+\-]=/, rrelNumFilter = /[^+\-\.\de]+/g, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn.css = function( name, value ) { // Setting 'undefined' is a no-op if ( arguments.length === 2 && value === undefined ) { return this; } return jQuery.access( this, name, value, true, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }); }; 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", "opacity" ); return ret === "" ? "1" : ret; } else { return elem.style.opacity; } } } }, // Exclude the following css properties to add px cssNumber: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": true, "widows": true, "orphans": 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, origName = jQuery.camelCase( name ), style = elem.style, hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Make sure that NaN and null values aren't set. See: #7116 if ( type === "number" && isNaN( value ) || value == null ) { return; } // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && rrelNum.test( value ) ) { value = +value.replace( rrelNumFilter, "" ) + parseFloat( jQuery.css( elem, name ) ); } // 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 )) !== 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 ) { var ret, hooks; // Make sure that we're working with the right name name = jQuery.camelCase( name ); hooks = jQuery.cssHooks[ name ]; name = jQuery.cssProps[ name ] || name; // cssFloat needs a special treatment if ( name === "cssFloat" ) { name = "float"; } // If a hook was provided get the computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) { return ret; // Otherwise, if a way to get the computed value exists, use that } else if ( curCSS ) { return curCSS( elem, name ); } }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var old = {}; // Remember the old values, and insert the new ones for ( var name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // DEPRECATED, Use jQuery.css() instead jQuery.curCSS = jQuery.css; jQuery.each(["height", "width"], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { var val; if ( computed ) { if ( elem.offsetWidth !== 0 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, set: function( elem, value ) { if ( rnumpx.test( value ) ) { // ignore negative width and height values #1599 value = parseFloat(value); if ( value >= 0 ) { return value + "px"; } } else { return value; } } }; }); 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) || "" ) ? ( parseFloat( RegExp.$1 ) / 100 ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN( value ) ? "" : "alpha(opacity=" + value * 100 + ")", filter = currentStyle && currentStyle.filter || style.filter || ""; style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery(function() { // This hook cannot be added until DOM ready because the support test // for it is not run until after DOM ready 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 var ret; jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { ret = curCSS( elem, "margin-right", "marginRight" ); } else { ret = elem.style.marginRight; } }); return ret; } }; } }); if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, ret = elem.currentStyle && elem.currentStyle[ name ], rsLeft = elem.runtimeStyle && elem.runtimeStyle[ name ], style = elem.style; // 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 if ( !rnumpx.test( ret ) && rnum.test( ret ) ) { // Remember the original values left = style.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 || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { var width = elem.offsetWidth, height = elem.offsetHeight; return (width === 0 && height === 0) || (!jQuery.support.reliableHiddenOffsets && (elem.style.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rspacesAjax = /\s+/, 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 = {}, // Document location ajaxLocation, // Document location segments ajaxLocParts; // #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 = "*"; } if ( jQuery.isFunction( func ) ) { var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ), i = 0, length = dataTypes.length, dataType, list, placeBefore; // 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 list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ), selection; 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; } jQuery.fn.extend({ 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 } else if ( !this.length ) { return this; } var off = url.indexOf( " " ); if ( off >= 0 ) { var selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // 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 ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, // Complete callback (responseText is used internally) complete: function( jqXHR, status, responseText ) { // Store the response as specified by the jqXHR object responseText = jqXHR.responseText; // If successful, inject the HTML into all the matched elements if ( jqXHR.isResolved() ) { // #4825: Get the actual response in case // a dataFilter is present in ajaxSettings jqXHR.done(function( r ) { responseText = r; }); // 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 ); } if ( callback ) { self.each( callback, [ responseText, status, jqXHR ] ); } } }); return this; }, 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(); } }); // 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.bind( 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 ) { // Only one parameter, we extend ajaxSettings settings = target; target = jQuery.extend( true, jQuery.ajaxSettings, settings ); } else { // target was provided, we extend into it jQuery.extend( true, target, jQuery.ajaxSettings, settings ); } // Flatten fields we don't want deep extended for( var field in { context: 1, url: 1 } ) { if ( field in settings ) { target[ field ] = settings[ field ]; } else if( field in jQuery.ajaxSettings ) { target[ field ] = jQuery.ajaxSettings[ field ]; } } return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, traditional: false, headers: {}, */ 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" }, // 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 } }, 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 // 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._Deferred(), // Status-dependent callbacks statusCode = s.statusCode || {}, // ifModified key ifModifiedKey, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // The jqXHR state state = 0, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // 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 || "abort"; 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, statusText, responses, headers ) { // 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 ? 4 : 0; var isSuccess, success, error, response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined, lastModified, etag; // 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 ) { if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) { jQuery.lastModified[ ifModifiedKey ] = lastModified; } if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) { jQuery.etag[ ifModifiedKey ] = etag; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { try { success = ajaxConvert( s, response ); statusText = "success"; isSuccess = true; } catch(e) { // We have a parsererror statusText = "parsererror"; error = e; } } } 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 = 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.resolveWith( 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.done; // 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.then( tmp, 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( rspacesAjax ); // Determine if a cross-domain request is in order 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 prefiler, stop there if ( state === 2 ) { return false; } // 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; } // 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 ] !== "*" ? ", */*; 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 jqXHR.abort(); return false; } // 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 ( status < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { jQuery.error( e ); } } } return jqXHR; }, // Serialize an array of form elements or a set of // key/values into a query string param: function( a, traditional ) { var s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : value; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = 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 ( var prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); } }); function buildParams( prefix, obj, traditional, add ) { 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" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && obj != null && typeof obj === "object" ) { // Serialize object item. for ( var name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // This is still on the jQuery object... for now // Want to move this to jQuery.ajax some day jQuery.extend({ // 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 contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields, ct, type, finalDataType, firstDataType; // 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 ) { // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } var dataTypes = s.dataTypes, converters = {}, i, key, length = dataTypes.length, tmp, // Current and previous dataTypes current = dataTypes[ 0 ], prev, // Conversion expression conversion, // Conversion function conv, // Conversion functions (transitive conversion) conv1, conv2; // For each dataType in the chain for( i = 1; i < length; i++ ) { // Create converters map // with lowercased keys if ( i === 1 ) { for( key in s.converters ) { if( typeof key === "string" ) { converters[ key.toLowerCase() ] = s.converters[ key ]; } } } // Get the dataTypes prev = current; current = dataTypes[ i ]; // If current is auto dataType, update it to prev if( current === "*" ) { current = prev; // If no auto and dataTypes are actually different } else if ( prev !== "*" && prev !== current ) { // Get the converter conversion = prev + " " + current; conv = converters[ conversion ] || converters[ "* " + current ]; // If there is no direct converter, search transitively if ( !conv ) { conv2 = undefined; for( conv1 in converters ) { tmp = conv1.split( " " ); if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) { conv2 = converters[ tmp[1] + " " + current ]; if ( conv2 ) { conv1 = converters[ conv1 ]; if ( conv1 === true ) { conv = conv2; } else if ( conv2 === true ) { conv = conv1; } break; } } } } // If we found no converter, dispatch an error if ( !( conv || conv2 ) ) { jQuery.error( "No conversion from " + conversion.replace(" "," to ") ); } // If found converter is not an equivalence if ( conv !== true ) { // Convert with 1 or 2 converters accordingly response = conv ? conv( response ) : conv2( conv1(response) ); } } } return response; } var jsc = jQuery.now(), jsre = /(\=)\?(&|$)|\?\?/i; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { return jQuery.expando + "_" + ( jsc++ ); } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var inspectData = s.contentType === "application/x-www-form-urlencoded" && ( typeof s.data === "string" ); if ( s.dataTypes[ 0 ] === "jsonp" || s.jsonp !== false && ( jsre.test( s.url ) || inspectData && jsre.test( s.data ) ) ) { var responseContainer, jsonpCallback = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback, previous = window[ jsonpCallback ], url = s.url, data = s.data, replace = "$1" + jsonpCallback + "$2"; if ( s.jsonp !== false ) { url = url.replace( jsre, replace ); if ( s.url === url ) { if ( inspectData ) { data = data.replace( jsre, replace ); } if ( s.data === data ) { // Add callback manually url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback; } } } s.url = url; s.data = data; // Install callback window[ jsonpCallback ] = function( response ) { responseContainer = [ response ]; }; // Clean-up function jqXHR.always(function() { // Set callback back to previous value window[ jsonpCallback ] = previous; // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( previous ) ) { window[ jsonpCallback ]( responseContainer[ 0 ] ); } }); // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( jsonpCallback + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // 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 // #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, xhrCallbacks; // 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 xhr = s.xhr(), handle, i; // 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 occured // 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; } 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 we're in sync mode or it's in cache // and has been retrieved directly (IE6 & IE7) // we need to manually fire the callback if ( !s.async || xhr.readyState === 4 ) { 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(0,1); } } }; } }); } var elemdisplay = {}, iframe, iframeDoc, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ], fxNow, requestAnimationFrame = window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame; jQuery.fn.extend({ show: function( speed, easing, callback ) { var elem, display; if ( speed || speed === 0 ) { return this.animate( genFx("show", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !jQuery._data(elem, "olddisplay") && display === "none" ) { display = 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 ( display === "" && jQuery.css( elem, "display" ) === "none" ) { jQuery._data(elem, "olddisplay", defaultDisplay(elem.nodeName)); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = elem.style.display; if ( display === "" || display === "none" ) { elem.style.display = jQuery._data(elem, "olddisplay") || ""; } } } return this; } }, hide: function( speed, easing, callback ) { if ( speed || speed === 0 ) { return this.animate( genFx("hide", 3), speed, easing, callback); } else { for ( var i = 0, j = this.length; i < j; i++ ) { if ( this[i].style ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" && !jQuery._data( this[i], "olddisplay" ) ) { jQuery._data( this[i], "olddisplay", display ); } } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { if ( this[i].style ) { this[i].style.display = "none"; } } return this; } }, // Save the old toggle function _toggle: jQuery.fn.toggle, toggle: function( fn, fn2, callback ) { var bool = typeof fn === "boolean"; if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) { this._toggle.apply( this, arguments ); } else if ( fn == null || bool ) { this.each(function() { var state = bool ? fn : jQuery(this).is(":hidden"); jQuery(this)[ state ? "show" : "hide" ](); }); } else { this.animate(genFx("toggle", 3), fn, fn2, callback); } return this; }, fadeTo: function( speed, to, easing, callback ) { return this.filter(":hidden").css("opacity", 0).show().end() .animate({opacity: to}, speed, easing, callback); }, animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); if ( jQuery.isEmptyObject( prop ) ) { return this.each( optall.complete, [ false ] ); } // Do not change referenced properties as per-property easing will be lost prop = jQuery.extend( {}, prop ); return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite if ( optall.queue === false ) { jQuery._mark( this ); } var opt = jQuery.extend( {}, optall ), isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), name, val, p, display, e, parts, start, end, unit; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; for ( p in prop ) { // property name normalization name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } val = prop[ name ]; // easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default) if ( jQuery.isArray( val ) ) { opt.animatedProperties[ name ] = val[ 1 ]; val = prop[ name ] = val[ 0 ]; } else { opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing'; } if ( val === "hide" && hidden || val === "show" && !hidden ) { return opt.complete.call( this ); } if ( isElement && ( name === "height" || name === "width" ) ) { // 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 opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height // animated if ( jQuery.css( this, "display" ) === "inline" && jQuery.css( this, "float" ) === "none" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { display = defaultDisplay( this.nodeName ); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } for ( p in prop ) { e = new jQuery.fx( this, opt, p ); val = prop[ p ]; if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ](); } else { parts = rfxnum.exec( val ); start = e.cur(); if ( parts ) { end = parseFloat( parts[2] ); unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" ) { jQuery.style( this, p, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( this, p, start + unit); } // If a +=/-= token was provided, we're doing a relative animation if ( parts[1] ) { end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start; } e.custom( start, end, unit ); } else { e.custom( start, val, "" ); } } } // For JS strict compliance return true; }); }, stop: function( clearQueue, gotoEnd ) { if ( clearQueue ) { this.queue([]); } this.each(function() { var timers = jQuery.timers, i = timers.length; // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } while ( i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); // Animations created synchronously will run synchronously function createFxNow() { setTimeout( clearFxNow, 0 ); return ( fxNow = jQuery.now() ); } function clearFxNow() { fxNow = undefined; } // Generate parameters to create a standard animation function genFx( type, num ) { var obj = {}; jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() { obj[ this ] = type; }); return obj; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show", 1), slideUp: genFx("hide", 1), slideToggle: genFx("toggle", 1), 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.extend({ 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; // Queueing opt.old = opt.complete; opt.complete = function( noUnmark ) { if ( opt.queue !== false ) { jQuery.dequeue( this ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } }; return opt; }, easing: { linear: function( p, n, firstNum, diff ) { return firstNum + diff * p; }, swing: function( p, n, firstNum, diff ) { return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum; } }, timers: [], fx: function( elem, options, prop ) { this.options = options; this.elem = elem; this.prop = prop; options.orig = options.orig || {}; } }); jQuery.fx.prototype = { // Simple function for setting a style value update: function() { if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this ); }, // Get the current size cur: function() { if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) { return this.elem[ this.prop ]; } var parsed, r = jQuery.css( this.elem, this.prop ); // Empty strings, null, undefined and "auto" are converted to 0, // complex values such as "rotate(1rad)" are returned as is, // simple values such as "10px" are parsed to Float. return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx, raf; this.startTime = fxNow || createFxNow(); this.start = from; this.end = to; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { // Use requestAnimationFrame instead of setInterval if available if ( requestAnimationFrame ) { timerId = 1; raf = function() { // When timerId gets set to null at any point, this stops if ( timerId ) { requestAnimationFrame( raf ); fx.tick(); } }; requestAnimationFrame( raf ); } else { timerId = setInterval( fx.tick, fx.interval ); } } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.show = true; // Begin the animation // Make sure that we start at a small width/height to avoid any // flash of content this.custom(this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur()); // Start by showing the element jQuery( this.elem ).show(); }, // Simple 'hide' function hide: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = jQuery.style( this.elem, this.prop ); this.options.hide = true; // Begin the animation this.custom(this.cur(), 0); }, // Each step of an animation step: function( gotoEnd ) { var t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options, i, n; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( i in options.animatedProperties ) { if ( options.animatedProperties[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; }); } // Hide the element if the "hide" operation was done if ( options.hide ) { jQuery(elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( options.hide || options.show ) { for ( var p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[p] ); } } // Execute the complete function options.complete.call( elem ); } return false; } else { // classical easing cannot be used with an Infinity duration if ( options.duration == Infinity ) { this.now = t; } else { n = t - this.startTime; this.state = n / options.duration; // Perform the easing function, defaults to swing this.pos = jQuery.easing[ options.animatedProperties[ this.prop ] ]( this.state, n, 0, 1, options.duration ); this.now = this.start + ((this.end - this.start) * this.pos); } // Perform the next step of the animation this.update(); } return true; } }; jQuery.extend( jQuery.fx, { tick: function() { for ( var timers = jQuery.timers, i = 0 ; i < timers.length ; ++i ) { if ( !timers[i]() ) { timers.splice(i--, 1); } } if ( !timers.length ) { jQuery.fx.stop(); } }, interval: 13, stop: function() { clearInterval( timerId ); timerId = null; }, speeds: { slow: 600, fast: 200, // Default speed _default: 400 }, step: { opacity: function( fx ) { jQuery.style( fx.elem, "opacity", fx.now ); }, _default: function( fx ) { if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) { fx.elem.style[ fx.prop ] = (fx.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } // Try to restore the default display value of an element function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery( "<" + nodeName + ">" ).appendTo( "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 === "" ) { // No iframe to use yet, so create it if ( !iframe ) { iframe = document.createElement( "iframe" ); iframe.frameBorder = iframe.width = iframe.height = 0; } document.body.appendChild( iframe ); // 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><body></body></html>" ); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { jQuery.fn.offset = function( options ) { var elem = this[0], box; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } try { box = elem.getBoundingClientRect(); } catch(e) {} var doc = elem.ownerDocument, docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !box || !jQuery.contains( docElem, elem ) ) { return box ? { top: box.top, left: box.left } : { top: 0, left: 0 }; } var body = doc.body, win = getWindow(doc), clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop, scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft, top = box.top + scrollTop - clientTop, left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; } else { jQuery.fn.offset = function( options ) { var elem = this[0]; if ( options ) { return this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } if ( !elem || !elem.ownerDocument ) { return null; } if ( elem === elem.ownerDocument.body ) { return jQuery.offset.bodyOffset( elem ); } jQuery.offset.initialize(); var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, doc = elem.ownerDocument, docElem = doc.documentElement, body = doc.body, defaultView = doc.defaultView, prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle, top = elem.offsetTop, left = elem.offsetLeft; while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) { if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { break; } computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle; top -= elem.scrollTop; left -= elem.scrollLeft; if ( elem === offsetParent ) { top += elem.offsetTop; left += elem.offsetLeft; if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevComputedStyle = computedStyle; } if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) { top += body.offsetTop; left += body.offsetLeft; } if ( jQuery.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<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>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.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 null; } 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; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( ["Left", "Top"], function( i, name ) { var method = "scroll" + name; jQuery.fn[ method ] = function( val ) { var elem, win; if ( val === undefined ) { elem = this[ 0 ]; if ( !elem ) { return null; } win = getWindow( elem ); // Return the scroll offset return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ method ] : elem[ method ]; } // Set the scroll offset return this.each(function() { win = getWindow( this ); if ( win ) { win.scrollTo( !i ? val : jQuery( win ).scrollLeft(), i ? val : jQuery( win ).scrollTop() ); } else { this[ method ] = val; } }); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each([ "Height", "Width" ], function( i, name ) { var type = name.toLowerCase(); // innerHeight and innerWidth jQuery.fn["inner" + name] = function() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : null; }; jQuery.fn[ type ] = function( size ) { // Get window width or height var elem = this[0]; if ( !elem ) { return size == null ? null : this; } if ( jQuery.isFunction( size ) ) { return this.each(function( i ) { var self = jQuery( this ); self[ type ]( size.call( this, i, self[ type ]() ) ); }); } if ( jQuery.isWindow( elem ) ) { // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat var docElemProp = elem.document.documentElement[ "client" + name ]; return elem.document.compatMode === "CSS1Compat" && docElemProp || elem.document.body[ "client" + name ] || docElemProp; // Get document width or height } else if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater return Math.max( elem.documentElement["client" + name], elem.body["scroll" + name], elem.documentElement["scroll" + name], elem.body["offset" + name], elem.documentElement["offset" + name] ); // Get or set width or height on the element } else if ( size === undefined ) { var orig = jQuery.css( elem, type ), ret = parseFloat( orig ); return jQuery.isNaN( ret ) ? orig : ret; // Set the width or height on the element (default to pixels if value is unitless) } else { return this.css( type, typeof size === "string" ? size : size + "px" ); } }; }); window.jQuery = window.$ = jQuery; })(window);
src/icons/FavoriteIcon.js
kiloe/ui
import React from 'react'; import Icon from '../Icon'; export default class FavoriteIcon extends Icon { getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M24 42.7l-2.9-2.63C10.8 30.72 4 24.55 4 17 4 10.83 8.83 6 15 6c3.48 0 6.82 1.62 9 4.17C26.18 7.62 29.52 6 33 6c6.17 0 11 4.83 11 11 0 7.55-6.8 13.72-17.1 23.07L24 42.7z"/></svg>;} };
src/components/patches/index.js
ziagrosvenor/sound-machine
import React from 'react' import {map, keys, values} from 'ramda' import {GridList, GridTile} from 'material-ui/GridList'; import {ParamHeader} from '../param' import { Grid } from '../shared/grid' import { NavItem } from '../navigation/nav-item' const styles = { root: { display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around', }, gridList: { height: '80vh', overflowY: 'auto' } }; function getGridData(patchData, i) { return { title: patchData.patchName, author: patchData.username, img: `./img/waveform${i.toString().slice(-1)}.png` } } export class Patches extends React.Component { constructor(props) { super(props) this.state = {} } componentDidMount() { fetch(`${API_URL}/patches`, { headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, method: 'GET' }) .then(function(res){ return res.json() }) .then((json) => this.setState({ patchData: map(JSON.parse, values(json)) })) .catch(function(res){ console.log(res) }) } render() { if (!this.state.patchData) return ( <div>Loading..</div> ) const gridData = this.state.patchData.map(getGridData) const getLoadPatchActionEl = (id) => { return ( <NavItem onTouchTap={() => this.props.onPatchChange(this.state.patchData[id].patch)} linkStyle={{padding: '1rem 1rem'}} path='/oscillators/0'>LOAD</NavItem> ) } const els = ( <div> <ParamHeader>Load a sound from the sound bank</ParamHeader> <div style={styles.root} > <GridList cellHeight={180} className="touch-scroll" style={styles.gridList} > {gridData.map((tile, i) => ( <GridTile key={i} title={tile.title} actionIcon={getLoadPatchActionEl(i)} subtitle={<span>by <b>{tile.author}</b></span>} > <img src={tile.img} /> </GridTile> ))} </GridList> </div> </div> ) return ( <Grid isScrollable={true} els={[els]} cols={1} /> ) } }
packages/docs/pages/plugin/video/index.js
nikgraf/draft-js-plugin-editor
import React, { Component } from 'react'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import simpleExampleCode from '!!raw-loader!../../../components/Examples/video/SimpleVideoEditor'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import customExampleCode from '!!raw-loader!../../../components/Examples/video/CustomVideoEditor'; // eslint-disable-next-line import/no-unresolved // eslint-disable-next-line import/no-duplicates import addVideoEditorExampleCode from '!!raw-loader!../../../components/Examples/video/CustomAddVideoVideoEditor'; // eslint-disable-next-line import/no-unresolved import gettingStarted from '!!raw-loader!../../../components/Examples/video/gettingStarted'; import Container from '../../../components/Container/Container'; import AlternateContainer from '../../../components/AlternateContainer/AlternateContainer'; import Heading from '../../../components/Heading/Heading'; import styles from './styles.module.css'; import Code from '../../../components/Code/Code'; // eslint-disable-next-line import/no-duplicates import SimpleVideoEditor from '../../../components/Examples/video/SimpleVideoEditor'; // eslint-disable-next-line import/no-duplicates import CustomVideoEditor from '../../../components/Examples/video/CustomVideoEditor'; // eslint-disable-next-line import/no-duplicates import CustomAddVideoVideoEditor from '../../../components/Examples/video/CustomAddVideoVideoEditor'; import PluginPageFrame from '../../../components/PluginPageFrame/PluginPageFrame'; export default class App extends Component { render() { return ( <PluginPageFrame> <Container> <Heading level={2}>Video</Heading> <Heading level={3}>Supported Environment</Heading> <ul className={styles.list}> <li className={styles.listEntry}>Desktop: Yes</li> <li className={styles.listEntry}>Mobile: No</li> <li className={styles.listEntry}>Screen-reader: No</li> </ul> </Container> <AlternateContainer> <Heading level={2}>Getting Started</Heading> <Code code="npm install @draft-js-plugins/editor" /> <Code code="npm install @draft-js-plugins/video --save" /> <Code code={gettingStarted} name="gettingStarted.js" /> </AlternateContainer> <Container> <Heading level={2}>Configuration Parameters</Heading> <div className={styles.param}> <span className={styles.paramName}>theme</span> <span>Object of CSS classes with the following keys.</span> <div className={styles.subParams}> <div className={styles.subParam}> <span className={styles.subParamName}>link:</span> CSS class to be applied to link text </div> </div> </div> <div className={styles.param}> <span className={styles.paramName}>target</span> <span> String value for the target attribute. (Default value is _self) </span> </div> <div className={styles.param}> <span className={styles.paramName}>component</span> <span> If provided this component will be rendered instead of the default Anchor tag. It receives the following props: target, href & className </span> </div> </Container> <Container> <Heading level={2}>Simple Example</Heading> <SimpleVideoEditor /> <Code code={simpleExampleCode} name="SimpleVideoEditor.js" /> </Container> <Container> <Heading level={2}>Advanced Video Example</Heading> <CustomVideoEditor /> <Code code={customExampleCode} name="CustomVideoEditor.js" /> </Container> <Container> <Heading level={2}>Add Video Button Example</Heading> <CustomAddVideoVideoEditor /> <Code code={addVideoEditorExampleCode} name="CustomAddVideoVideoEditor.js" /> </Container> </PluginPageFrame> ); } }
src/svg-icons/editor/format-indent-increase.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatIndentIncrease = (props) => ( <SvgIcon {...props}> <path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/> </SvgIcon> ); EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease); EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease'; EditorFormatIndentIncrease.muiName = 'SvgIcon'; export default EditorFormatIndentIncrease;
ajax/libs/jquery/1.8.3/jquery.js
adatapost/cdnjs
/*! * jQuery JavaScript Library v1.8.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) */ (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 );
ajax/libs/primereact/6.2.0/components/card/Card.js
cdnjs/cdnjs
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Card = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _ClassNames = require("../utils/ClassNames"); var _ObjectUtils = _interopRequireDefault(require("../utils/ObjectUtils")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var Card = /*#__PURE__*/function (_Component) { _inherits(Card, _Component); var _super = _createSuper(Card); function Card() { _classCallCheck(this, Card); return _super.apply(this, arguments); } _createClass(Card, [{ key: "renderHeader", value: function renderHeader() { if (this.props.header) { return /*#__PURE__*/_react.default.createElement("div", { className: "p-card-header" }, _ObjectUtils.default.getJSXElement(this.props.header, this.props)); } return null; } }, { key: "renderBody", value: function renderBody() { var title = this.props.title && /*#__PURE__*/_react.default.createElement("div", { className: "p-card-title" }, _ObjectUtils.default.getJSXElement(this.props.title, this.props)); var subTitle = this.props.subTitle && /*#__PURE__*/_react.default.createElement("div", { className: "p-card-subtitle" }, _ObjectUtils.default.getJSXElement(this.props.subTitle, this.props)); var children = this.props.children && /*#__PURE__*/_react.default.createElement("div", { className: "p-card-content" }, this.props.children); var footer = this.props.footer && /*#__PURE__*/_react.default.createElement("div", { className: "p-card-footer" }, _ObjectUtils.default.getJSXElement(this.props.footer, this.props)); return /*#__PURE__*/_react.default.createElement("div", { className: "p-card-body" }, title, subTitle, children, footer); } }, { key: "render", value: function render() { var header = this.renderHeader(); var body = this.renderBody(); var className = (0, _ClassNames.classNames)('p-card p-component', this.props.className); return /*#__PURE__*/_react.default.createElement("div", { className: className, style: this.props.style }, header, body); } }]); return Card; }(_react.Component); exports.Card = Card; _defineProperty(Card, "defaultProps", { id: null, header: null, footer: null, title: null, subTitle: null, style: null, className: null }); _defineProperty(Card, "propTypes", { id: _propTypes.default.string, header: _propTypes.default.any, footer: _propTypes.default.any, title: _propTypes.default.any, subTitle: _propTypes.default.any, style: _propTypes.default.object, className: _propTypes.default.string });
packages/react-server-test-pages/pages/navigation/common.js
lidawang/react-server
import _ from "lodash"; import {Component} from "react"; import {ReactServerAgent} from "react-server"; // Each row listens to `navigateStart'. // Give ourselves some buffer. require('events').EventEmitter.defaultMaxListeners = 128; export const ROWS = _.range(32); export function GET(row) { const ms = row*16; const val = JSON.stringify({row, ms}); return ReactServerAgent .get('/data/delay', {ms, val}) .then(res => _.assign({}, this, res.body)); } export class ClientRenderIndicator extends Component { constructor(props){ super(props); this.state = {ready: false}; } _handleNavEvent(evt) { if (!this._mounted) return; this.setState({ready: evt === 'loadComplete'}); } componentDidMount() { this._mounted = true; this.setState({ready: true}); const nav = window.__reactServerClientController.context.navigator; this._navListeners = ['navigateStart', 'loadComplete'] .reduce((m,e) => (nav.on(e, m[e] = this._handleNavEvent.bind(this, e)), m), {}); } componentWillUnmount() { this._mounted = false; const nav = window.__reactServerClientController.context.navigator; _.forEach(this._navListeners, (v,k) => nav.removeListener(k, v)); } componentWillReceiveProps() { this.setState({ready: true}); } render() { return <div className="render-indicator"> {this.state.ready?"✓":"⌛️"} </div> } } export const PagePointer = ({page, row}) => <div className="page-pointer"> {+page === +row ? "➟" : ""} </div>; export const RowIndex = ({row}) => <div className="row-index">Row {row}</div>; export const RowMS = ({ms}) => <div className="row-ms">{ms}ms</div>;
packages/material-ui-icons/src/AllInbox.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19 3H5c-1.1 0-2 .9-2 2v7c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 6h-4c0 1.62-1.38 3-3 3s-3-1.38-3-3H5V5h14v4zm-4 7h6v3c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2v-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3z" /></React.Fragment> , 'AllInbox');
components/markers/index.js
ElemeFE/react-amap
// @flow import React from 'react'; import { render } from 'react-dom'; import isFun from '../utils/isFun'; import log from '../utils/log'; import { MarkerAllProps, getPropValue, renderMarkerComponent } from '../utils/markerUtils'; if (typeof window !== 'undefined') { const styleText = `.amap_markers_pop_window{ padding: 10px; border: 1px solid #ddd; border-radius: 8px; background: #fff; position: relative; display: flex; flex-wrap: wrap; justify-content: flex-start; } .amap_markers_pop_window::before{ content: ' '; display: block; position: absolute; bottom: -12px; left: 50%; margin-left: -7px; width: 0; height: 0; border-top: 12px solid #ddd; border-left: 7px solid transparent; border-right: 7px solid transparent; } .amap_markers_pop_window::after{ content: ' '; display: block; position: absolute; bottom: -11px; left: 50%; margin-left: -6px; width: 0; height: 0; border-top: 11px solid #fff; border-left: 6px solid transparent; border-right: 6px solid transparent; } .amap_markers_pop_window_item{ cursor:pointer; width: 40px; height: 50px; display: flex; align-items: flex-end; justify-content: center; } .amap_markers_pop_window_item span{ pointer-events: none; } .amap_markers_window_overflow_warning{ text-align: center; width: 100%; margin: 5px 0; color: #666; }`; const headEl = document.head || document.getElementsByTagName('head')[0]; const styleEl = document.createElement('style'); styleEl.type = 'text/css'; styleEl.textContent = styleText; headEl.appendChild(styleEl); } const Component = React.Component; const SCALE = 0.8; const SIZE_WIDTH = 32 * SCALE; const SIZE_HEIGHT = 46 * SCALE - 2; const SIZE_HOVER_WIDTH = 46 * SCALE; const SIZE_HOVER_HEIGHT = 66 * SCALE - 2; const MAX_INFO_MARKERS = 42; const defaultOpts = { useCluster: false, markersCache: [], markerIDCache: [] }; const ClusterProps = [ 'gridSize', 'minClusterSize', 'maxZoom', 'averageCenter', 'styles', 'zoomOnClick', 'renderCluserMarker' ]; const IdKey = '__react_amap__'; type MarkerDOM = HTMLDivElement & { markerRef: Object }; /* * props * { * useCluster(boolean)是否使用聚合点 * markers(array<>)坐标列表 * __map__ 父级组件传过来的地图实例 * __ele__ 父级组件传过来的地图容器 * } */ class Markers extends Component<MarkerProps, {}> { map: Object; element: HTMLDivElement & {markerRef: Object}; markersCache: Array<Object>; markerIDCache: Array<number>; useCluster: ?boolean; resetOffset: Object; hoverOffset: Object; markersWindow: Object; mapCluster: Object; markersDOM: MarkerDOM; markerReactChildDOM: any; constructor(props: MarkerProps) { super(props); if (typeof window !== 'undefined') { if (!props.__map__) { log.warning('MAP_INSTANCE_REQUIRED'); } else { this.map = props.__map__; this.element = this.map.getContainer(); this.markersCache = defaultOpts.markersCache; this.useCluster = null; this.markerIDCache = defaultOpts.markerIDCache; this.resetOffset = new window.AMap.Pixel(-SIZE_WIDTH / 2, -SIZE_HEIGHT); this.hoverOffset = new window.AMap.Pixel(-SIZE_HOVER_WIDTH / 2, -SIZE_HOVER_HEIGHT); this.createMarkers(props); } } } shouldComponentUpdate() { return false; } createMarkers(props: MarkerProps) { const markers = props.markers || []; const mapMarkers = []; const markerReactChildDOM = {}; markers.length && markers.forEach((raw, idx) => { const options = this.buildCreateOptions(props, raw, idx); options.map = this.map; let markerContent = null; if (isFun(props.render)) { // $FlowFixMe let markerChild = props.render(raw); if (markerChild !== false) { const div = document.createElement('div'); div.setAttribute(IdKey, '1'); markerContent = div; markerReactChildDOM[idx] = markerChild; } } if (!markerContent) { markerContent = document.createElement('div'); const img = document.createElement('img'); img.src = '//webapi.amap.com/theme/v1.3/markers/n/mark_bs.png'; markerContent.appendChild(img); } options.content = markerContent; const marker = new window.AMap.Marker(options); marker.on('click', (e) => { this.onMarkerClick(e); }); marker.on('mouseover', (e) => { this.onMarkerHover(e); }); marker.on('mouseout', (e) => { this.onMarkerHoverOut(e); }); marker.render = (function(marker) { return function(component) { return renderMarkerComponent(component, marker); }; }(marker)); this.bindMarkerEvents(marker); mapMarkers.push(marker); }); this.markersCache = mapMarkers; this.markerReactChildDOM = markerReactChildDOM; this.exposeMarkerInstance(); this.checkClusterSettings(props); } checkClusterSettings(props: MarkerProps) { if (props.useCluster) { this.loadClusterPlugin(props.useCluster).then((cluster) => { cluster.setMarkers(this.markersCache); }); } else { if (this.mapCluster) { const markers = this.mapCluster.getMarkers(); this.mapCluster.clearMarkers(); markers.forEach((marker) => { marker.setMap(this.map); }); } } } componentDidMount() { if (this.map) { this.setMarkerChild(); } } setMarkerChild() { Object.keys(this.markerReactChildDOM).forEach((idx) => { const dom = this.markersCache[idx].getContent(); const child = this.markerReactChildDOM[idx]; this.renderMarkerChild(dom, child); }); } renderMarkerChild(dom: HTMLElement, child: any) { render(<div>{child}</div>, dom); } buildCreateOptions(props: MarkerProps, raw: any, idx: number) { const result = {}; // 强制用户通过 render 函数来定义外观 // const disabledKeys = ['label', 'icon', 'content']; // 还是不强制好,通过覆盖的方式来(如果有 render,覆盖 content/icon); const disabledKeys = ['extData']; MarkerAllProps.forEach((key) => { if ((key in raw) && (disabledKeys.indexOf(key) === -1)) { result[key] = getPropValue(key, raw[key]); } else if (key in props) { if (isFun(props[key])) { const tmpValue = props[key].call(null, raw, idx); result[key] = getPropValue(key, tmpValue); } else { result[key] = getPropValue(key, props[key]); } } }); result.extData = raw; return result; } componentWillReceiveProps(nextProps: MarkerProps) { if (this.map) { this.refreshMarkersLayout(nextProps); } } refreshMarkersLayout(nextProps: MarkerProps) { const markerChanged = (nextProps.markers !== this.props.markers); const clusterChanged = ((!!this.props.useCluster) !== (!!nextProps.useCluster)); if (markerChanged) { this.markersCache.length && this.markersCache.forEach((marker) => { if (marker) { marker.setMap(null); marker = null; } }); this.markersCache = defaultOpts.markersCache; this.createMarkers(nextProps); this.setMarkerChild(); } if (markerChanged || (clusterChanged)) { if (this.markersWindow) { this.markersWindow.close(); } } if (clusterChanged) { this.checkClusterSettings(nextProps); } } loadClusterPlugin(clusterConfig: Object | boolean): Promise<Object> { if (this.mapCluster) { return Promise.resolve(this.mapCluster); } const config = (typeof clusterConfig === 'boolean') ? {} : clusterConfig; return new Promise((resolve) => { this.map.plugin(['AMap.MarkerClusterer'], () => { resolve(this.createClusterPlugin(config)); }); }); } createClusterPlugin(config: Object) { let options = {}; // const style = { // url: clusterIcon, // size: new window.AMap.Size(56, 56), // offset: new window.AMap.Pixel(-28, -28) // }; const defalutOptions: Object = { minClusterSize: 2, zoomOnClick: false, maxZoom: 18, gridSize: 60, // styles: [style, style, style], averageCenter: true }; ClusterProps.forEach((key) => { if (key in config) { options[key] = config[key]; } else { options[key] = defalutOptions[key]; } }); this.mapCluster = new window.AMap.MarkerClusterer(this.map, [], options); let events = {}; if ('events' in config) { events = config.events; if ('created' in events) { events.created(this.mapCluster); } } this.initClusterMarkerWindow(); this.bindClusterEvent(events); return this.mapCluster; } onMarkerClick(e: MapEvent) { const marker = e.target; this.triggerMarkerClick(e, marker); } onMarkerHover(e: MapEvent) { e.target.setTop(true); this.setMarkerHovered(e, e.target); } onMarkerHoverOut(e: MapEvent) { e.target.setTop(false); this.setMarkerHoverOut(e, e.target); } onWindowMarkerClick(element: MarkerDOM) { const marker = element.markerRef; this.triggerMarkerClick(null, marker); } onWindowMarkerHover(element: MarkerDOM) { const marker = element.markerRef; this.setMarkerHovered(null, marker); } onWindowMarkerHoverOut(element: MarkerDOM) { const marker = element.markerRef; this.setMarkerHoverOut(null, marker); } setMarkerHovered(e: MapEvent | null, marker: Object) { this.triggerMarkerHover(e, marker); } setMarkerHoverOut(e: MapEvent | null, marker: Object) { this.triggerMarkerHoverOut(e, marker); } triggerMarkerClick(e: MapEvent | null, marker: Object) { // const raw = marker.getExtData(); const events = this.props.events || {}; if (isFun(events.click)) { events.click(e, marker); } } triggerMarkerHover(e: MapEvent | null, marker: Object) { // const raw = marker.getExtData(); const events = this.props.events || {}; if (isFun(events.mouseover)) { events.mouseover(e, marker); } } triggerMarkerHoverOut(e: MapEvent | null, marker: Object) { // const raw = marker.getExtData(); const events = this.props.events || {}; if (isFun(events.mouseout)) { events.mouseout(e, marker); } } initClusterMarkerWindow() { this.markersWindow = new window.AMap.InfoWindow({ isCustom: true, autoMove: true, closeWhenClickMap: true, content: '<span>loading...</span>', showShadow: false, offset: new window.AMap.Pixel(0, -20) }); this.markersDOM = document.createElement('div'); this.markersDOM.className = 'amap_markers_pop_window'; this.markersWindow.setContent(this.markersDOM); } bindClusterEvent(events: Object) { this.mapCluster.on('click', (e) => { if (this.props.useCluster && this.props.useCluster.zoomOnClick) { // } else { let returnValue = true; if (isFun(events.click)) { returnValue = events.click(e); } if (returnValue !== false) { this.showMarkersInfoWindow(e); } } }); } showMarkersInfoWindow(e: MapEvent) { const pos = e.lnglat; let markers = e.markers; this.markersDOM.innerHTML = ''; if (markers && markers.length) { const length = markers.length; if (length > MAX_INFO_MARKERS) { markers = markers.slice(0, MAX_INFO_MARKERS); } markers.forEach((m) => { const contentDOM = m.getContent(); const itemDOM: MarkerDOM = document.createElement('div'); itemDOM.className = 'window_marker_item'; itemDOM.appendChild(contentDOM); itemDOM.markerRef = m; itemDOM.addEventListener('click', this.onWindowMarkerClick.bind(this, itemDOM), true); itemDOM.addEventListener('mouseover', this.onWindowMarkerHover.bind(this, itemDOM), true); itemDOM.addEventListener('mouseout', this.onWindowMarkerHoverOut.bind(this, itemDOM), true); this.markersDOM.appendChild(itemDOM); }); if (length > MAX_INFO_MARKERS) { const warning = document.createElement('div'); warning.className = 'amap_markers_window_overflow_warning'; warning.innerText = '更多坐标请放大地图查看'; this.markersDOM.appendChild(warning); } } this.markersWindow.open(this.map, pos); } exposeMarkerInstance() { if ('events' in this.props) { const events = this.props.events || {}; if (isFun(events.created)) { events.created(this.markersCache); } } } bindMarkerEvents(marker: Object) { const events = this.props.events || {}; const list = Object.keys(events); const preserveEv = ['click', 'mouseover', 'mouseout', 'created']; list.length && list.forEach((evName) => { if (preserveEv.indexOf(evName) === -1) { marker.on(evName, events[evName]); } }); } render() { return (null); } } export default Markers;
ImageCameraAlt.js
nodule/react-material-ui
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/image/camera-alt": require('material-ui/svg-icons/image/camera-alt') } }, name: "ImageCameraAlt", ports: { input: {}, output: { component: { title: "ImageCameraAlt", type: "Component" } } } }
src/App/Main/index.js
ruudthissen/CarSys-Solutions-Tool
import React from "react"; import { Header, Grid } from "semantic-ui-react"; export default class ListContainer extends React.Component { render() { return ( <div> <Grid > <Grid.Row> Menu </Grid.Row> <Grid.Row> Content </Grid.Row> </Grid> </div> ); } }
src/svg-icons/device/gps-not-fixed.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceGpsNotFixed = (props) => ( <SvgIcon {...props}> <path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </SvgIcon> ); DeviceGpsNotFixed = pure(DeviceGpsNotFixed); DeviceGpsNotFixed.displayName = 'DeviceGpsNotFixed'; export default DeviceGpsNotFixed;
src/components/emptyTest.spec.js
kpuno/survey-app
import React from 'react'; import {shallow} from 'enzyme'; import HomePage from './HomePage'; describe('<HomePage />', () => { it('should have a header called \'Home Page\'', () => { const wrapper = shallow(<HomePage />); const actual = wrapper.find('h2').text(); const expected = 'Home Page'; expect(actual).toEqual(expected); }); });
src/client/tooltipPopup/tooltipPopup.react.js
sljuka/portfulio
import Component from '../components/component.react' import React from 'react' import {toggle} from './actions' import {FormattedHTMLMessage} from 'react-intl'; export default class TooltipPopup extends Component { handleClick() { toggle(this.props.name) } render() { const className = `tooltip-circle tooltip-${this.props.name}` const popupClassName = `tooltip-popup tooltip-popup-${this.props.name}` const tooltip = ( <span className={popupClassName}> <FormattedHTMLMessage message={this.props.text} /> </span> ) return ( <div className={className} onClick={this.handleClick.bind(this)}> {this.props.opened && tooltip} </div> ) } }
CompositeUi/src/views/layout/NotificationLayout.js
kreta/kreta
/* * This file is part of the Kreta package. * * (c) Beñat Espiña <benatespina@gmail.com> * (c) Gorka Laucirica <gorka.lauzirika@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import './../../scss/layout/_notification.scss'; import React from 'react'; import {connect} from 'react-redux'; import Notification from './../component/Notification'; import NotificationActions from './../../actions/Notification'; @connect(state => ({notifications: state.notification.notifications})) class NotificationLayout extends React.Component { removeNotification(id) { this.props.dispatch(NotificationActions.removeNotification(id)); } render() { const notifications = this.props.notifications.map((notification, index) => <Notification key={index} notification={notification} onCloseRequest={this.removeNotification.bind(this, notification.id)} />, ); return ( <div className="notification-layout"> {notifications} </div> ); } } export default NotificationLayout;
app/javascript/mastodon/features/ui/components/column_subheading.js
dwango/mastodon
import React from 'react'; import PropTypes from 'prop-types'; const ColumnSubheading = ({ text }) => { return ( <div className='column-subheading'> {text} </div> ); }; ColumnSubheading.propTypes = { text: PropTypes.string.isRequired, }; export default ColumnSubheading;
web/static/js/app.js
maxdec/cellar
// import { Socket } from "phoenix"; // let socket = new Socket("/ws") // socket.connect() // let chan = socket.chan("topic:subtopic", {}) // chan.join().receive("ok", chan => { // console.log("Success!") // }) import 'babel-polyfill'; import 'bootstrap-loader'; import '../css/app.scss'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router, Route, IndexRoute, browserHistory } from 'react-router'; import { App, BottleEdit, BottleNew, Bottles, Cellar, Container, WineEdit, WineNew, Wines } from './containers'; import './config'; ReactDOM.render( <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={Cellar} /> <Route path="wines" component={Container}> <IndexRoute component={Wines} /> <Route path="new" component={WineNew} /> <Route path=":id" component={WineEdit} /> </Route> <Route path="bottles" component={Container}> <IndexRoute component={Bottles}/> <Route path="new" component={BottleNew}/> <Route path=":id" component={BottleEdit}/> </Route> </Route> </Router>, document.getElementById('app') );
packages/react-scripts/fixtures/kitchensink/src/index.js
reedsa/create-react-app
/** * Copyright (c) 2015-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. */ import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
app/javascript/mastodon/features/ui/components/columns_area.js
Toootim/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ReactSwipeable from 'react-swipeable'; import HomeTimeline from '../../home_timeline'; import Notifications from '../../notifications'; import PublicTimeline from '../../public_timeline'; import CommunityTimeline from '../../community_timeline'; import HashtagTimeline from '../../hashtag_timeline'; import Compose from '../../compose'; import { getPreviousLink, getNextLink } from './tabs_bar'; const componentMap = { 'COMPOSE': Compose, 'HOME': HomeTimeline, 'NOTIFICATIONS': Notifications, 'PUBLIC': PublicTimeline, 'COMMUNITY': CommunityTimeline, 'HASHTAG': HashtagTimeline, }; export default class ColumnsArea extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object.isRequired, }; static propTypes = { columns: ImmutablePropTypes.list.isRequired, singleColumn: PropTypes.bool, children: PropTypes.node, }; handleRightSwipe = () => { const previousLink = getPreviousLink(this.context.router.history.location.pathname); if (previousLink) { this.context.router.history.push(previousLink); } } handleLeftSwipe = () => { const previousLink = getNextLink(this.context.router.history.location.pathname); if (previousLink) { this.context.router.history.push(previousLink); } }; render () { const { columns, children, singleColumn } = this.props; if (singleColumn) { return ( <ReactSwipeable onSwipedLeft={this.handleLeftSwipe} onSwipedRight={this.handleRightSwipe} className='columns-area'> {children} </ReactSwipeable> ); } return ( <div className='columns-area'> {columns.map(column => { const SpecificComponent = componentMap[column.get('id')]; const params = column.get('params', null) === null ? null : column.get('params').toJS(); return <SpecificComponent key={column.get('uuid')} columnId={column.get('uuid')} params={params} multiColumn />; })} {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))} </div> ); } }
src/client/viewer.components/Viewer.Extensions/Viewing.Extension.PlantFactory/PropertyPieChart.js
jeremytammik/forgefader
import Toolkit from 'Viewer.Toolkit' import PieChart from 'PieChart' import React from 'react' class PropertyPieChart extends React.Component { ///////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////// constructor () { super () } ///////////////////////////////////////////////////////// // // ///////////////////////////////////////////////////////// render () { const { guid, title, data, viewer, style } = this.props return ( <div className="property-pie-chart" style={style}> <div className="title controls"> <label> { title } </label> </div> <PieChart onGroupClicked={(e) => { const dbIds = e.expanded ? [] : e.data.dbIds Toolkit.isolateFull( viewer, dbIds) viewer.fitToView() }} guid={guid} data={data} /> </div> ) } } export default PropertyPieChart
ajax/libs/react-textarea-autosize/5.0.3/react-textarea-autosize.min.js
hare1039/cdnjs
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react"),require("prop-types")):"function"==typeof define&&define.amd?define(["react","prop-types"],t):e.TextareaAutosize=t(e.React,e.PropTypes)}(this,function(e,t){"use strict";function n(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2],i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;null===a.parentNode&&document.body.appendChild(a);var h=o(e,n);if(null===h)return null;var u=h.paddingSize,l=h.borderSize,p=h.boxSizing,d=h.sizingStyle;Object.keys(d).forEach(function(e){a.style[e]=d[e]}),Object.keys(s).forEach(function(e){a.style.setProperty(e,s[e],"important")}),a.value=e.value||e.placeholder||"x";var c=-1/0,f=1/0,g=a.scrollHeight;"border-box"===p?g+=l:"content-box"===p&&(g-=u),a.value="x";var m=a.scrollHeight-u;return null===i&&null===r||(null!==i&&(c=m*i,"border-box"===p&&(c=c+u+l),g=Math.max(c,g)),null!==r&&(f=m*r,"border-box"===p&&(f=f+u+l),g=Math.min(f,g))),{height:g,minHeight:c,maxHeight:f,rowCount:Math.floor(g/m)}}function o(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(n&&u[t])return u[t];var o=window.getComputedStyle(e);if(null===o)return null;var i=h.reduce(function(e,t){return e[t]=o.getPropertyValue(t),e},{}),a=i["box-sizing"];r&&"border-box"===a&&(i.width=parseFloat(i.width)+parseFloat(o["border-right-width"])+parseFloat(o["border-left-width"])+parseFloat(o["padding-right"])+parseFloat(o["padding-left"])+"px");var s=parseFloat(i["padding-bottom"])+parseFloat(i["padding-top"]),l=parseFloat(i["border-bottom-width"])+parseFloat(i["border-top-width"]),p={sizingStyle:i,paddingSize:s,borderSize:l,boxSizing:a};return n&&(u[t]=p),p}e="default"in e?e.default:e,t="default"in t?t.default:t;var i="undefined"!=typeof window&&"undefined"!=typeof document,r=!!i&&!!document.documentElement.currentStyle,a=i&&document.createElement("textarea"),s={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0"},h=["letter-spacing","line-height","font-family","font-weight","font-size","text-rendering","text-transform","width","text-indent","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","box-sizing"],u={},l=function(e){return delete u[e]},p=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;return function(){return++e}}(),d=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},c=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},f=function(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)},g=function(e,t){var n={};for(var o in e)0>t.indexOf(o)&&Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n},m=function(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},b=function(){},y=window.requestAnimationFrame?[window.requestAnimationFrame,window.cancelAnimationFrame]:[setTimeout,clearTimeout],w=y[0],v=y[1],x=function(t){function o(e){d(this,o);var i=m(this,t.call(this,e));return i._resizeLock=!1,i._onRootDOMNode=function(e){i._rootDOMNode=e,i.props.inputRef&&i.props.inputRef(e)},i._onChange=function(e){i._controlled||i._resizeComponent(),i.props.onChange(e)},i._resizeComponent=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:b;if(void 0!==i._rootDOMNode){var t=n(i._rootDOMNode,i._uid,i.props.useCacheForDOMMeasurements,i.props.minRows,i.props.maxRows);if(null!==t){var o=t.height,r=t.minHeight,a=t.maxHeight;i.rowCount=t.rowCount,i.state.height===o&&i.state.minHeight===r&&i.state.maxHeight===a||i.setState({height:o,minHeight:r,maxHeight:a},e)}}},i.state={height:e.style&&e.style.height||0,minHeight:-1/0,maxHeight:1/0},i._uid=p(),i._controlled="string"==typeof e.value,i}return f(o,t),o.prototype.render=function(){var t=this.props,n=g(t,["minRows","maxRows","onHeightChange","useCacheForDOMMeasurements","inputRef"]);return n.style=c({},n.style,{height:this.state.height}),this.state.height>Math.max(n.style.maxHeight||1/0,this.state.maxHeight)&&(n.style.overflow="hidden"),e.createElement("textarea",c({},n,{onChange:this._onChange,ref:this._onRootDOMNode}))},o.prototype.componentDidMount=function(){var e=this;this._resizeComponent(),this._resizeListener=function(){e._resizeLock||(e._resizeLock=!0,e._resizeComponent(function(){return e._resizeLock=!1}))},window.addEventListener("resize",this._resizeListener)},o.prototype.componentWillReceiveProps=function(){var e=this;this._clearNextFrame(),this._onNextFrameActionId=w(function(){return e._resizeComponent()})},o.prototype.componentDidUpdate=function(e,t){this.state.height!==t.height&&this.props.onHeightChange(this.state.height,this)},o.prototype.componentWillUnmount=function(){this._clearNextFrame(),window.removeEventListener("resize",this._resizeListener),l(this._uid)},o.prototype._clearNextFrame=function(){v(this._onNextFrameActionId)},o}(e.Component);return x.propTypes={value:t.string,onChange:t.func,onHeightChange:t.func,useCacheForDOMMeasurements:t.bool,minRows:t.number,maxRows:t.number,inputRef:t.func},x.defaultProps={onChange:b,onHeightChange:b,useCacheForDOMMeasurements:!1},x});
node_modules/react-bootstrap/es/Glyphicon.js
newphew92/newphew92.github.io
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, prefix, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { /** * An icon name. See e.g. http://getbootstrap.com/components/#glyphicons */ glyph: React.PropTypes.string.isRequired }; var Glyphicon = function (_React$Component) { _inherits(Glyphicon, _React$Component); function Glyphicon() { _classCallCheck(this, Glyphicon); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Glyphicon.prototype.render = function render() { var _extends2; var _props = this.props; var glyph = _props.glyph; var className = _props.className; var props = _objectWithoutProperties(_props, ['glyph', 'className']); var _splitBsProps = splitBsProps(props); var bsProps = _splitBsProps[0]; var elementProps = _splitBsProps[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, glyph)] = true, _extends2)); return React.createElement('span', _extends({}, elementProps, { className: classNames(className, classes) })); }; return Glyphicon; }(React.Component); Glyphicon.propTypes = propTypes; export default bsClass('glyphicon', Glyphicon);
client/src/components/modal/index.js
AlTavares/babos.ios-server
import React from 'react'; class ModalView extends React.Component { render() { return ( <div className="modal fade" id={this.props.id} tabIndex="-1" role="dialog" aria-labelledby="modalLabel"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <button type="button" className="close" data-dismiss="modal" aria-label="Fechar"><span aria-hidden="true">&times;</span></button> <h4 className="modal-title" id="modalLabel">{this.props.title}</h4> </div> <div className="modal-body"> {this.props.body} </div> <div className="modal-footer"> {this.props.footer} </div> </div> </div> </div> ); } } ModalView.displayName = 'ModalView'; export default ModalView
dac/ui/src/index.js
dremio/dremio-oss
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-unused-vars */ /* * Copyright (C) 2017-2019 Dremio Corporation * * 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. */ import React from 'react'; import { render } from 'react-dom'; import $ from 'jquery'; import Immutable from 'immutable'; import sentryUtil from 'utils/sentryUtil'; import startup from 'dyn-load/startup'; import setupMetrics from '@inject/setupMetrics'; import '@inject/vendor/segment'; import './vendor/chat'; import 'imports-loader?this=>window!script-loader!jsplumb/dist/js/jsPlumb-2.1.4-min.js'; import 'dremio-ui-lib/dist/index.css'; import './main.less'; // add css here to be sure that its content will appear after compiled main.less content. // when import .css file inside of .less file than .css content appears at the top of the file // no matter of @import ordering // the reason why typography.css import is here because it conflicts with reset.less imported inside // of main.less file import './uiTheme/css/typography.css'; import 'font-awesome/css/font-awesome.css'; import Root from './containers/Root'; import configureStore from './store/configureStore'; // enable using mock data //import MirageServer from './MirageServer'; // useful debugging leaks... window.React = React; window.$ = $; window.Immutable = Immutable; setupMetrics(); window.la = (key) => { // (config.environment !== 'PRODUCTION') && console.warn('using unsupported localization function for:', key); return key; }; sentryUtil.install(); const store = configureStore(); // useful debugging link for looking at stores // to use in the console window of devTools type: // window.store.getState() // This will display all the stores // once you find the store you want type something like // (this is an example) // window.store.getState().resources.entities.toJS() window.store = store; startup.run(); render( <Root store={store} />, document.getElementById('root') );
test/lib/convertToReact.js
yummies/core
import React from 'react'; import { expect } from 'chai'; import convertToReact from '../../lib/convertToReact'; describe('convertToReact', () => { it('exist', () => { expect(convertToReact).to.exist; }); it('be a function', () => { expect(convertToReact).to.be.a('function'); }); it('pass non-BEMJSON through', () => { expect(convertToReact( React.createElement('span') )).to.have.property('type', 'span').and .to.not.have.deep.property('props.className'); }); it('no block + invalid tag', () => { expect(convertToReact.bind(convertToReact, { tag: 123 })).to.throw( 'tag should be string' ); }); it('no block + default tag', () => { expect(convertToReact( {} )).to.have.property('type', 'div').and .to.not.have.deep.property('props.className'); }); it('no block + custom tag', () => { expect(convertToReact({ tag: 'span' })).to.have.property('type', 'span').and .to.not.have.deep.property('props.className'); }); it('invalid block', () => { expect(convertToReact.bind(convertToReact, { block: 123 })).to.throw( 'block should be string' ); }); it('block', () => { expect(convertToReact({ block: 'block' })).to.have.deep.property('props.className'); }); it('no block + elem', () => { expect(convertToReact.bind(convertToReact, { elem: 'elem' })).to.throw( 'you should provide block along with elem' ); }); it('block + invalid elem', () => { expect(convertToReact.bind(convertToReact, { block: 'block', elem: 123 })).to.throw( 'elem should be string' ); }); it('no block + mods', () => { expect(convertToReact.bind(convertToReact, { mods: { mod: 'val' } })).to.throw( 'you should provide block/elem along with mods' ); }); it('block + invalid mods', () => { expect(convertToReact.bind(convertToReact, { block: 'block', mods: 'mod' })).to.throw( 'mods should be a plain object' ); }); it('block + mods', () => { expect(convertToReact({ block: 'block', mods: { mod: 'val' } })).to.have.deep.property('props.className'); }); it('block + mix', () => { expect(convertToReact({ block: 'block', mix: { block: 'block2' } })).to.have.deep.property('props.className'); }); it('block + invalid mix', () => { expect(convertToReact.bind(convertToReact, { block: 'block', mix: 'mix' })).to.throw( 'mix should be a plain object or array' ); }); it('no block + invalid props', () => { expect(convertToReact.bind(convertToReact, { props: 'props' })).to.throw( 'props should be a plain object' ); }); it('block + simple content', () => { expect(convertToReact({ block: 'block', content: 123 })).to.have.deep.property('props.children', 123); }); it('block + multiple simple content', () => { expect(convertToReact({ block: 'block', content: [ 123, 456 ] })).to.have.deep.property('props.children') .that.is.an('array') .which.have.members([ 123, 456 ]); }); it('block + content with elem with context', () => { expect(convertToReact({ block: 'block', content: { elem: 'elem' } })).to.have.deep.property('props.children.props.className', 'block__elem'); }); it('block + raw content + elem with context', () => { const children = convertToReact({ block: 'block', content: { tag: 'span', content: { elem: 'elem' } } }).props.children; expect(children).to.have.property('type', 'span'); expect(children.props.children.props).to.have.property('className', 'block__elem'); }); it('block + complex content', () => { const children = convertToReact({ block: 'block', content: [ { elem: 'elem', props: { key: 'elem1' } }, React.createElement('span', { key: 'elem2' }) ] }).props.children; expect(children).to.have.deep.property('[0].props.className', 'block__elem'); expect(children).to.have.deep.property('[1].type', 'span'); }); });
packages/cp-frontend/src/components/messaging/warning.js
yldio/copilot
import React from 'react'; import PropTypes from 'prop-types'; import { Message } from 'joyent-ui-toolkit'; const WarningMessage = ({ title, message }) => ( <Message title={title} message={message} type="WARNING" /> ); WarningMessage.propTypes = { title: PropTypes.string, message: PropTypes.string.isRequired }; export default WarningMessage;
local-cli/templates/HelloNavigation/views/chat/ChatScreen.js
kesha-antonov/react-native
import React, { Component } from 'react'; import { ActivityIndicator, Button, FlatList, StyleSheet, Text, TextInput, View, } from 'react-native'; import KeyboardSpacer from '../../components/KeyboardSpacer'; import Backend from '../../lib/Backend'; export default class ChatScreen extends Component { static navigationOptions = ({ navigation }) => ({ title: `Chat with ${navigation.state.params.name}`, }); constructor(props) { super(props); this.state = { messages: [], myMessage: '', isLoading: true, }; } async componentDidMount() { let chat; try { chat = await Backend.fetchChat(this.props.navigation.state.params.name); } catch (err) { // Here we would handle the fact the request failed, e.g. // set state to display "Messages could not be loaded". // We should also check network connection first before making any // network requests - maybe we're offline? See React Native's NetInfo // module. this.setState({ isLoading: false, }); return; } this.setState((prevState) => ({ messages: chat.messages, isLoading: false, })); } onAddMessage = async () => { // Optimistically update the UI this.addMessageLocal(); // Send the request try { await Backend.sendMessage({ name: this.props.navigation.state.params.name, // TODO Is reading state like this outside of setState OK? // Can it contain a stale value? message: this.state.myMessage, }); } catch (err) { // Here we would handle the request failure, e.g. call setState // to display a visual hint showing the message could not be sent. } } addMessageLocal = () => { this.setState((prevState) => { if (!prevState.myMessage) { return prevState; } const messages = [ ...prevState.messages, { name: 'Me', text: prevState.myMessage, } ]; return { messages: messages, myMessage: '', }; }); this.textInput.clear(); } onMyMessageChange = (event) => { this.setState({myMessage: event.nativeEvent.text}); } renderItem = ({ item }) => ( <View style={styles.bubble}> <Text style={styles.name}>{item.name}</Text> <Text>{item.text}</Text> </View> ) render() { if (this.state.isLoading) { return ( <View style={styles.container}> <ActivityIndicator /> </View> ); } return ( <View style={styles.container}> <FlatList data={this.state.messages} renderItem={this.renderItem} keyExtractor={(item, index) => index} style={styles.listView} /> <View style={styles.composer}> <TextInput ref={(textInput) => { this.textInput = textInput; }} style={styles.textInput} placeholder="Type a message..." text={this.state.myMessage} onSubmitEditing={this.onAddMessage} onChange={this.onMyMessageChange} /> {this.state.myMessage !== '' && ( <Button title="Send" onPress={this.onAddMessage} /> )} </View> <KeyboardSpacer /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, padding: 8, backgroundColor: 'white', }, listView: { flex: 1, alignSelf: 'stretch', }, bubble: { alignSelf: 'flex-end', backgroundColor: '#d6f3fc', padding: 12, borderRadius: 4, marginBottom: 4, }, name: { fontWeight: 'bold', }, composer: { flexDirection: 'row', alignItems: 'center', height: 36, }, textInput: { flex: 1, borderColor: '#ddd', borderWidth: 1, padding: 4, height: 30, fontSize: 13, marginRight: 8, } });
src/svg-icons/image/camera-front.js
igorbt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCameraFront = (props) => ( <SvgIcon {...props}> <path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zM12 8c1.1 0 2-.9 2-2s-.9-2-2-2-1.99.9-1.99 2S10.9 8 12 8zm5-8H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zM7 2h10v10.5c0-1.67-3.33-2.5-5-2.5s-5 .83-5 2.5V2z"/> </SvgIcon> ); ImageCameraFront = pure(ImageCameraFront); ImageCameraFront.displayName = 'ImageCameraFront'; ImageCameraFront.muiName = 'SvgIcon'; export default ImageCameraFront;
packages/components/src/Enumeration/Items/Item/Item.component.js
Talend/ui
import React from 'react'; import classNames from 'classnames'; import { Button } from 'react-bootstrap'; import { withTranslation } from 'react-i18next'; import { removeDuplicates, allIndexOf } from './utils'; import Action from '../../../Actions/Action'; import theme from './Item.scss'; import Checkbox from '../../../Checkbox'; import ItemPropTypes from './Item.propTypes'; import I18N_DOMAIN_COMPONENTS from '../../../constants'; import Icon from '../../../Icon'; import TooltipTrigger from '../../../TooltipTrigger'; function itemClasses(isSelected) { return classNames({ [theme['tc-enumeration-item']]: true, [theme['selected-item']]: isSelected, 'tc-enumeration-item': true, 'selected-item': isSelected, }); } function itemLabelClasses(className) { return classNames({ [theme['tc-enumeration-item-label']]: true, 'tc-enumeration-item-label': true, [className]: className, }); } function itemDefaultActionsClasses() { return classNames({ [theme['tc-enumeration-item-actions']]: true, 'tc-enumeration-item-actions': true, [theme.editable]: true, }); } function Item({ id, item, searchCriteria, showCheckboxes, style, t }) { const { key, actions, onSelectItem, persistentActions } = item.itemProps; const actualLabel = item[key] instanceof Array ? item[key].join(',') : item[key]; function getAction(action, index) { function onClick(event) { if (action.onClick) { action.onClick(event, { value: event.target.value, index: item.index, }); } } return ( <Action {...action} key={index} onClick={onClick} tooltipPlacement="bottom" hideLabel link /> ); } /** * This function allow to get component rendering based on searchCriteria * @param label the current label to parse & to render */ function getSearchedLabel(label) { let indexes = allIndexOf(label.toLowerCase(), searchCriteria.toLowerCase()); indexes = removeDuplicates(indexes, searchCriteria); return ( <span> {/* Set the label to go on the first index if the index is not 0 */} {indexes[0] !== 0 ? label.substring(0, indexes[0]) : null} {indexes.map((matchIndex, index, matchIndexes) => ( <span key={index}> {/* get the string from label with indexes ( to keep words case ) */} <strong>{label.substring(matchIndex, matchIndex + searchCriteria.length)}</strong> {/* get the string before next index if there is */} {index === matchIndex.length + 1 ? null : label.substring(matchIndex + searchCriteria.length, matchIndexes[index + 1])} </span> ))} </span> ); } function getActionLabel() { if (searchCriteria) { return ( <button role="gridcell" className={itemLabelClasses(item.className)} disabled="disabled"> {getSearchedLabel(actualLabel)} </button> ); } return ( <Button className={itemLabelClasses(item.className)} role="gridcell" onClick={event => onSelectItem(item, event)} key={item.index} aria-label={t('TC_ENUMERATION_SELECT', { defaultValue: 'Select item "{{label}}"', label: actualLabel, })} bsStyle="link" > {showCheckboxes && ( <Checkbox aria-label={t('TC_ENUMERATION_CHECK', { defaultValue: 'Check item "{{label}}"', label: actualLabel, })} className={classNames(theme['tc-enumeration-checkbox'], 'tc-enumeration-checkbox')} checked={item.isSelected} /> )} <span>{actualLabel}</span> {item.icon && ( <TooltipTrigger label={item.icon.title} tooltipPlacement="bottom"> <span> <Icon {...item.icon} aria-hidden="false" /> </span> </TooltipTrigger> )} </Button> ); } return ( <div role="row" className={itemClasses(item.isSelected)} id={id} style={style}> {getActionLabel()} <div className={itemDefaultActionsClasses()} role="gridcell"> {persistentActions && ( <div className="persistent"> {persistentActions .filter(action => !action.disabled) .map((action, index) => getAction(action, index))} </div> )} {actions .filter(action => !action.disabled) .map((action, index) => getAction(action, index))} </div> </div> ); } Item.propTypes = ItemPropTypes; export default withTranslation(I18N_DOMAIN_COMPONENTS)(Item);
src/components/images/Upload.js
rokka-io/rokka-dashboard
import PropTypes from 'prop-types' import React, { PureComponent } from 'react' import Dropzone from 'react-dropzone' import Promise from 'bluebird' import rokka from '../../rokka' import { updateUploadedImages } from '../../state' import uploadIcon from '../../img/upload-icon.svg' const UPLOAD_DEFAULT = 0 const UPLOAD_PENDING = 1 const UPLOAD_SUCCESSFUL = 2 const UPLOAD_ERROR = 3 const FILE_MAX_SIZE = 400000000 class UploadImage extends PureComponent { constructor(props) { super(props) this.state = { upload: UPLOAD_DEFAULT, message: null, images: [] } } componentDidCatch(error, info) { this.setState({ upload: UPLOAD_ERROR }) console.error(error, info) } onDrop(files) { this.setState({ upload: UPLOAD_PENDING }) const hasTooBigFiles = files.find(file => file.size >= FILE_MAX_SIZE) if (hasTooBigFiles) { this.setState({ upload: UPLOAD_ERROR, message: 'File max size is 400 MB for the dashboard. Consider using a CLI API client instead' }) return } const invalidFileType = files.find(file => { return file.type === '' }) if (invalidFileType) { this.setState({ upload: UPLOAD_ERROR, message: 'Invalid file type uploaded. Maybe a folder? Folder upload is not possible yet. Try selecting all files within a folder instead.' }) } const mapFile = file => { const fileReader = new window.FileReader() let idx = -1 fileReader.onload = e => { const images = [ ...this.state.images, { url: e.target.result, name: file.name, uploaded: false } ] idx = images.length - 1 this.setState({ images: images }) } fileReader.readAsDataURL(file) return rokka() .sourceimages.create(this.props.organization, file.name, file) .then(({ body }) => { const images = [...this.state.images] const item = body.items[0] images[idx] = Object.assign(item, { uploaded: true, url: rokka().render.getUrl( this.props.organization, item.hash, item.format, 'dynamic/noop' ) }) this.setState({ images: images }) setTimeout(() => updateUploadedImages(images), 100) }) } Promise.map(files, mapFile, { concurrency: 5 }) .then(() => { this.setState({ upload: UPLOAD_SUCCESSFUL }) }) .catch(err => { this.setState({ upload: UPLOAD_ERROR, message: 'Upload failed due to the API returning an error. For example plain text files are not supported.' }) console.error(err) }) } onClick(e) { e.preventDefault() this.refs.dropzone.open() } render() { const { upload, message } = this.state let $banner = null if (upload === UPLOAD_PENDING) { $banner = <div className="rka-alert txt-c mt-md is-pending">Uploading...</div> } else if (upload === UPLOAD_SUCCESSFUL) { $banner = <div className="rka-alert txt-c mt-md is-success">Upload successful</div> } else if (upload === UPLOAD_ERROR) { $banner = ( <div className="rka-alert txt-c mt-md is-error"> Upload failed {message ? <p>{message}</p> : ''} </div> ) } return ( <div> <Dropzone onDrop={files => this.onDrop(files)} className="rka-uploader" activeClassName="rka-uploader is-active" ref="dropzone" disableClick > <div className="rka-uploader-hd"> <svg className="rka-uploader-icon"> <use xlinkHref={uploadIcon + '#upload'} /> </svg> <div className="visible-md-block"> <p className="mt-sm">Drop your images</p> <p className="mt-sm">or</p> </div> </div> <button className="rka-button rka-button-brand" onClick={e => this.onClick(e)}> Browse images </button> </Dropzone> {$banner} </div> ) } } UploadImage.propTypes = { organization: PropTypes.string.isRequired } export default UploadImage
ajax/libs/es6-shim/0.25.2/es6-shim.js
dhowe/cdnjs
/*! * https://github.com/paulmillr/es6-shim * @license es6-shim Copyright 2013-2014 by Paul Miller (http://paulmillr.com) * and contributors, MIT License * es6-shim: v0.25.2 * see https://github.com/paulmillr/es6-shim/blob/0.25.2/LICENSE * Details and documentation: * https://github.com/paulmillr/es6-shim/ */ // UMD (Universal Module Definition) // see https://github.com/umdjs/umd/blob/master/returnExports.js (function (root, factory) { /*global define, module, exports */ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.returnExports = factory(); } }(this, function () { 'use strict'; var isCallableWithoutNew = function (func) { try { func(); } catch (e) { return false; } return true; }; var supportsSubclassing = function (C, f) { /* jshint proto:true */ try { var Sub = function () { C.apply(this, arguments); }; if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ } Object.setPrototypeOf(Sub, C); Sub.prototype = Object.create(C.prototype, { constructor: { value: C } }); return f(Sub); } catch (e) { return false; } }; var arePropertyDescriptorsSupported = function () { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is IE 8. */ return false; } }; var startsWithRejectsRegex = function () { var rejectsRegex = false; if (String.prototype.startsWith) { try { '/a/'.startsWith(/a/); } catch (e) { /* this is spec compliant */ rejectsRegex = true; } } return rejectsRegex; }; /*jshint evil: true */ var getGlobal = new Function('return this;'); /*jshint evil: false */ var globals = getGlobal(); var global_isFinite = globals.isFinite; var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported(); var startsWithIsCompliant = startsWithRejectsRegex(); var _indexOf = Function.call.bind(String.prototype.indexOf); var _toString = Function.call.bind(Object.prototype.toString); var _hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); var ArrayIterator; // make our implementation private var noop = function () {}; var Symbol = globals.Symbol || {}; var symbolSpecies = Symbol.species || '@@species'; var Type = { string: function (x) { return _toString(x) === '[object String]'; }, regex: function (x) { return _toString(x) === '[object RegExp]'; }, symbol: function (x) { /*jshint notypeof: true */ return typeof globals.Symbol === 'function' && typeof x === 'symbol'; /*jshint notypeof: false */ } }; var defineProperty = function (object, name, value, force) { if (!force && name in object) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var Value = { getter: function (object, name, getter) { if (!supportsDescriptors) { throw new TypeError('getters require true ES5 support'); } Object.defineProperty(object, name, { configurable: true, enumerable: false, get: getter }); }, proxy: function (originalObject, key, targetObject) { if (!supportsDescriptors) { throw new TypeError('getters require true ES5 support'); } var originalDescriptor = Object.getOwnPropertyDescriptor(originalObject, key); Object.defineProperty(targetObject, key, { configurable: originalDescriptor.configurable, enumerable: originalDescriptor.enumerable, get: function getKey() { return originalObject[key]; }, set: function setKey(value) { originalObject[key] = value; } }); }, redefine: function (object, property, newValue) { if (supportsDescriptors) { var descriptor = Object.getOwnPropertyDescriptor(object, property); descriptor.value = newValue; Object.defineProperty(object, property, descriptor); } else { object[property] = newValue; } } }; // Define configurable, writable and non-enumerable props // if they don’t exist. var defineProperties = function (object, map) { Object.keys(map).forEach(function (name) { var method = map[name]; defineProperty(object, name, method, false); }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function (prototype, properties) { function Prototype() {} Prototype.prototype = prototype; var object = new Prototype(); if (typeof properties !== 'undefined') { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = Type.symbol(Symbol.iterator) ? Symbol.iterator : '_es6-shim iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function (prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); if (!prototype[$iterator$] && Type.symbol($iterator$)) { // implementations are buggy when $iterator$ is a Symbol prototype[$iterator$] = impl; } }; // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js // can be replaced with require('is-arguments') if we ever use a build process instead var isArguments = function isArguments(value) { var str = _toString(value); var result = str === '[object Arguments]'; if (!result) { result = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && _toString(value.callee) === '[object Function]'; } return result; }; var safeApply = Function.call.bind(Function.apply); var ES = { // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args Call: function Call(F, V) { var args = arguments.length > 2 ? arguments[2] : []; if (!ES.IsCallable(F)) { throw new TypeError(F + ' is not a function'); } return safeApply(F, V, args); }, RequireObjectCoercible: function (x, optMessage) { /* jshint eqnull:true */ if (x == null) { throw new TypeError(optMessage || 'Cannot call method on ' + x); } }, TypeIsObject: function (x) { /* jshint eqnull:true */ // this is expensive when it returns false; use this function // when you expect it to return true in the common case. return x != null && Object(x) === x; }, ToObject: function (o, optMessage) { ES.RequireObjectCoercible(o, optMessage); return Object(o); }, IsCallable: function (x) { // some versions of IE say that typeof /abc/ === 'function' return typeof x === 'function' && _toString(x) === '[object Function]'; }, ToInt32: function (x) { return ES.ToNumber(x) >> 0; }, ToUint32: function (x) { return ES.ToNumber(x) >>> 0; }, ToNumber: function (value) { if (_toString(value) === '[object Symbol]') { throw new TypeError('Cannot convert a Symbol value to a number'); } return +value; }, ToInteger: function (value) { var number = ES.ToNumber(value); if (Number.isNaN(number)) { return 0; } if (number === 0 || !Number.isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }, ToLength: function (value) { var len = ES.ToInteger(value); if (len <= 0) { return 0; } // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) { return Number.MAX_SAFE_INTEGER; } return len; }, SameValue: function (a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) { return 1 / a === 1 / b; } return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function (a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function (o) { return ES.TypeIsObject(o) && (typeof o[$iterator$] !== 'undefined' || isArguments(o)); }, GetIterator: function (o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, 'value'); } var itFn = o[$iterator$]; if (!ES.IsCallable(itFn)) { throw new TypeError('value is not an iterable'); } var it = itFn.call(o); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function (it) { var result = arguments.length > 1 ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function (C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C[symbolSpecies])) { obj = C[symbolSpecies](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = ES.Call(C, obj, args); return ES.TypeIsObject(result) ? result : obj; }, CreateHTML: function (string, tag, attribute, value) { var S = String(string); var p1 = '<' + tag; if (attribute !== '') { var V = String(value); var escapedV = V.replace(/"/g, '&quot;'); p1 += ' ' + attribute + '="' + escapedV + '"'; } var p2 = p1 + '>'; var p3 = p2 + S; return p3 + '</' + tag + '>'; } }; var emulateES6construct = function (o) { if (!ES.TypeIsObject(o)) { throw new TypeError('bad object'); } // es5 approximation to es6 subclass semantics: in es6, 'new Foo' // would invoke Foo.@@species to allocation/initialize the new object. // In es5 we just get the plain object. So if we detect an // uninitialized object, invoke o.constructor.@@species if (!o._es6construct) { if (o.constructor && ES.IsCallable(o.constructor[symbolSpecies])) { o = o.constructor[symbolSpecies](o); } defineProperties(o, { _es6construct: true }); } return o; }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.slice(0, 8), 2)); str = str.slice(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.slice(0, 1), 2) ? -1 : 1; e = parseInt(str.slice(1, 1 + ebits), 2); f = parseInt(str.slice(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function fromCodePoint(codePoints) { var result = []; var next; for (var i = 0, length = arguments.length; i < length; i++) { next = Number(arguments[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function raw(callSite) { var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var rawString = ES.ToObject(rawValue, 'bad raw value'); var len = rawString.length; var literalsegments = ES.ToLength(len); if (literalsegments <= 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = rawString[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = nextIndex + 1 < arguments.length ? arguments[nextIndex + 1] : ''; nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); // Firefox 31 reports this function's length as 0 // https://bugzilla.mozilla.org/show_bug.cgi?id=1062484 if (String.fromCodePoint.length !== 1) { var originalFromCodePoint = Function.apply.bind(String.fromCodePoint); defineProperty(String, 'fromCodePoint', function fromCodePoint(codePoints) { return originalFromCodePoint(this, arguments); }, true); } // Fast repeat, uses the `Exponentiation by squaring` algorithm. // Perf: http://jsperf.com/string-repeat2/2 var stringRepeat = function repeat(s, times) { if (times < 1) { return ''; } if (times % 2) { return repeat(s, times - 1) + s; } var half = repeat(s, times / 2); return half + half; }; var stringMaxLength = Infinity; var StringShims = { repeat: function repeat(times) { ES.RequireObjectCoercible(this); var thisStr = String(this); times = ES.ToInteger(times); if (times < 0 || times >= stringMaxLength) { throw new RangeError('repeat count must be less than infinity and not overflow maximum string size'); } return stringRepeat(thisStr, times); }, startsWith: function (searchStr) { ES.RequireObjectCoercible(this); var thisStr = String(this); if (Type.regex(searchStr)) { throw new TypeError('Cannot call method "startsWith" with a regex'); } searchStr = String(searchStr); var startArg = arguments.length > 1 ? arguments[1] : void 0; var start = Math.max(ES.ToInteger(startArg), 0); return thisStr.slice(start, start + searchStr.length) === searchStr; }, endsWith: function (searchStr) { ES.RequireObjectCoercible(this); var thisStr = String(this); if (Type.regex(searchStr)) { throw new TypeError('Cannot call method "endsWith" with a regex'); } searchStr = String(searchStr); var thisLen = thisStr.length; var posArg = arguments.length > 1 ? arguments[1] : void 0; var pos = typeof posArg === 'undefined' ? thisLen : ES.ToInteger(posArg); var end = Math.min(Math.max(pos, 0), thisLen); return thisStr.slice(end - searchStr.length, end) === searchStr; }, includes: function includes(searchString) { var position = arguments.length > 1 ? arguments[1] : void 0; // Somehow this trick makes method 100% compat with the spec. return _indexOf(this, searchString, position) !== -1; }, codePointAt: function (pos) { ES.RequireObjectCoercible(this); var thisStr = String(this); var position = ES.ToInteger(pos); var length = thisStr.length; if (position >= 0 && position < length) { var first = thisStr.charCodeAt(position); var isEnd = (position + 1 === length); if (first < 0xD800 || first > 0xDBFF || isEnd) { return first; } var second = thisStr.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) { return first; } return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000; } } }; defineProperties(String.prototype, StringShims); var hasStringTrimBug = '\u0085'.trim().length !== 1; if (hasStringTrimBug) { delete String.prototype.trim; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimRegexp = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); defineProperties(String.prototype, { trim: function () { if (typeof this === 'undefined' || this === null) { throw new TypeError("can't convert " + this + ' to object'); } return String(this).replace(trimRegexp, ''); } }); } // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator var StringIterator = function (s) { ES.RequireObjectCoercible(s); this._s = String(s); this._i = 0; }; StringIterator.prototype.next = function () { var s = this._s, i = this._i; if (typeof s === 'undefined' || i >= s.length) { this._s = void 0; return { value: void 0, done: true }; } var first = s.charCodeAt(i), second, len; if (first < 0xD800 || first > 0xDBFF || (i + 1) === s.length) { len = 1; } else { second = s.charCodeAt(i + 1); len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2; } this._i = i + len; return { value: s.substr(i, len), done: false }; }; addIterator(StringIterator.prototype); addIterator(String.prototype, function () { return new StringIterator(this); }); if (!startsWithIsCompliant) { // Firefox has a noncompliant startsWith implementation defineProperty(String.prototype, 'startsWith', StringShims.startsWith, true); defineProperty(String.prototype, 'endsWith', StringShims.endsWith, true); } var ArrayShims = { from: function (iterable) { var mapFn = arguments.length > 1 ? arguments[1] : void 0; var list = ES.ToObject(iterable, 'bad iterable'); if (typeof mapFn !== 'undefined' && !ES.IsCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } var hasThisArg = arguments.length > 2; var thisArg = hasThisArg ? arguments[2] : void 0; var usingIterator = ES.IsIterable(list); // does the spec really mean that Arrays should use ArrayIterator? // https://bugs.ecmascript.org/show_bug.cgi?id=2416 //if (Array.isArray(list)) { usingIterator=false; } var length; var result, i, value; if (usingIterator) { i = 0; result = ES.IsCallable(this) ? Object(new this()) : []; var it = usingIterator ? ES.GetIterator(list) : null; var iterationValue; do { iterationValue = ES.IteratorNext(it); if (!iterationValue.done) { value = iterationValue.value; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } i += 1; } } while (!iterationValue.done); length = i; } else { length = ES.ToLength(list.length); result = ES.IsCallable(this) ? Object(new this(length)) : new Array(length); for (i = 0; i < length; ++i) { value = list[i]; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } } result.length = length; return result; }, of: function () { return Array.from(arguments); } }; defineProperties(Array, ArrayShims); var arrayFromSwallowsNegativeLengths = function () { try { return Array.from({ length: -1 }).length === 0; } catch (e) { return false; } }; // Fixes a Firefox bug in v32 // https://bugzilla.mozilla.org/show_bug.cgi?id=1063993 if (!arrayFromSwallowsNegativeLengths()) { defineProperty(Array, 'from', ArrayShims.from, true); } // Given an argument x, it will return an IteratorResult object, // with value set to x and done to false. // Given no arguments, it will return an iterator completion object. var iterator_result = function (x) { return { value: x, done: arguments.length === 0 }; }; // Our ArrayIterator is private; see // https://github.com/paulmillr/es6-shim/issues/252 ArrayIterator = function (array, kind) { this.i = 0; this.array = array; this.kind = kind; }; defineProperties(ArrayIterator.prototype, { next: function () { var i = this.i, array = this.array; if (!(this instanceof ArrayIterator)) { throw new TypeError('Not an ArrayIterator'); } if (typeof array !== 'undefined') { var len = ES.ToLength(array.length); for (; i < len; i++) { var kind = this.kind; var retval; if (kind === 'key') { retval = i; } else if (kind === 'value') { retval = array[i]; } else if (kind === 'entry') { retval = [i, array[i]]; } this.i = i + 1; return { value: retval, done: false }; } } this.array = void 0; return { value: void 0, done: true }; } }); addIterator(ArrayIterator.prototype); var ObjectIterator = function (object, kind) { this.object = object; // Don't generate keys yet. this.array = null; this.kind = kind; }; function getAllKeys(object) { var keys = []; for (var key in object) { keys.push(key); } return keys; } defineProperties(ObjectIterator.prototype, { next: function () { var key, array = this.array; if (!(this instanceof ObjectIterator)) { throw new TypeError('Not an ObjectIterator'); } // Keys not generated if (array === null) { array = this.array = getAllKeys(this.object); } // Find next key in the object while (ES.ToLength(array.length) > 0) { key = array.shift(); // The candidate key isn't defined on object. // Must have been deleted, or object[[Prototype]] // has been modified. if (!(key in this.object)) { continue; } if (this.kind === 'key') { return iterator_result(key); } else if (this.kind === 'value') { return iterator_result(this.object[key]); } else { return iterator_result([key, this.object[key]]); } } return iterator_result(); } }); addIterator(ObjectIterator.prototype); var ArrayPrototypeShims = { copyWithin: function (target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = typeof end === 'undefined' ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function (value) { var start = arguments.length > 1 ? arguments[1] : void 0; var end = arguments.length > 2 ? arguments[2] : void 0; var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(typeof start === 'undefined' ? 0 : start); end = ES.ToInteger(typeof end === 'undefined' ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); var relativeEnd = end < 0 ? len + end : end; for (var i = relativeStart; i < len && i < relativeEnd; ++i) { O[i] = value; } return O; }, find: function find(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } var thisArg = arguments.length > 1 ? arguments[1] : null; for (var i = 0, value; i < length; i++) { value = list[i]; if (thisArg) { if (predicate.call(thisArg, value, i, list)) { return value; } } else if (predicate(value, i, list)) { return value; } } }, findIndex: function findIndex(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments.length > 1 ? arguments[1] : null; for (var i = 0; i < length; i++) { if (thisArg) { if (predicate.call(thisArg, list[i], i, list)) { return i; } } else if (predicate(list[i], i, list)) { return i; } } return -1; }, keys: function () { return new ArrayIterator(this, 'key'); }, values: function () { return new ArrayIterator(this, 'value'); }, entries: function () { return new ArrayIterator(this, 'entry'); } }; // Safari 7.1 defines Array#keys and Array#entries natively, // but the resulting ArrayIterator objects don't have a "next" method. if (Array.prototype.keys && !ES.IsCallable([1].keys().next)) { delete Array.prototype.keys; } if (Array.prototype.entries && !ES.IsCallable([1].entries().next)) { delete Array.prototype.entries; } // Chrome 38 defines Array#keys and Array#entries, and Array#@@iterator, but not Array#values if (Array.prototype.keys && Array.prototype.entries && !Array.prototype.values && Array.prototype[$iterator$]) { defineProperties(Array.prototype, { values: Array.prototype[$iterator$] }); if (Type.symbol(Symbol.unscopables)) { Array.prototype[Symbol.unscopables].values = true; } } defineProperties(Array.prototype, ArrayPrototypeShims); addIterator(Array.prototype, function () { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function (value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function (value) { return Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function (value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function (value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); // Work around bugs in Array#find and Array#findIndex -- early // implementations skipped holes in sparse arrays. (Note that the // implementations of find/findIndex indirectly use shimmed // methods of Number, so this test has to happen down here.) /*jshint elision: true */ if (![, 1].find(function (item, idx) { return idx === 0; })) { defineProperty(Array.prototype, 'find', ArrayPrototypeShims.find, true); } if ([, 1].findIndex(function (item, idx) { return idx === 0; }) !== 0) { defineProperty(Array.prototype, 'findIndex', ArrayPrototypeShims.findIndex, true); } /*jshint elision: false */ if (supportsDescriptors) { defineProperties(Object, { // 19.1.3.1 assign: function (target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function (target, source) { return Object.keys(Object(source)).reduce(function (target, key) { target[key] = source[key]; return target; }, target); }); }, is: function (a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function (Object, magic) { var set; var checkArgs = function (O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto === null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null' + proto); } }; var setPrototypeOf = function (O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function (proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; }(Object, '__proto__')) }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function () { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function (o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function (o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; }()); } var objectKeysAcceptsPrimitives = (function () { try { Object.keys('foo'); return true; } catch (e) { return false; } }()); if (!objectKeysAcceptsPrimitives) { var originalObjectKeys = Object.keys; defineProperty(Object, 'keys', function keys(value) { return originalObjectKeys(ES.ToObject(value)); }, true); } if (Object.getOwnPropertyNames) { var objectGOPNAcceptsPrimitives = (function () { try { Object.getOwnPropertyNames('foo'); return true; } catch (e) { return false; } }()); if (!objectGOPNAcceptsPrimitives) { var originalObjectGetOwnPropertyNames = Object.getOwnPropertyNames; defineProperty(Object, 'getOwnPropertyNames', function getOwnPropertyNames(value) { return originalObjectGetOwnPropertyNames(ES.ToObject(value)); }, true); } } if (!RegExp.prototype.flags && supportsDescriptors) { var regExpFlagsGetter = function flags() { if (!ES.TypeIsObject(this)) { throw new TypeError('Method called on incompatible type: must be an object.'); } var result = ''; if (this.global) { result += 'g'; } if (this.ignoreCase) { result += 'i'; } if (this.multiline) { result += 'm'; } if (this.unicode) { result += 'u'; } if (this.sticky) { result += 'y'; } return result; }; Value.getter(RegExp.prototype, 'flags', regExpFlagsGetter); } var regExpSupportsFlagsWithRegex = (function () { try { return String(new RegExp(/a/g, 'i')) === '/a/i'; } catch (e) { return false; } }()); if (!regExpSupportsFlagsWithRegex && supportsDescriptors) { var OrigRegExp = RegExp; var RegExpShim = function RegExp(pattern, flags) { if (Type.regex(pattern) && Type.string(flags)) { return new RegExp(pattern.source, flags); } return new OrigRegExp(pattern, flags); }; defineProperty(RegExpShim, 'toString', OrigRegExp.toString.bind(OrigRegExp), true); if (Object.setPrototypeOf) { // sets up proper prototype chain where possible Object.setPrototypeOf(OrigRegExp, RegExpShim); } Object.getOwnPropertyNames(OrigRegExp).forEach(function (key) { if (key === '$input') { return; } // Chrome < v39 & Opera < 26 have a nonstandard "$input" property if (key in noop) { return; } Value.proxy(OrigRegExp, key, RegExpShim); }); RegExpShim.prototype = OrigRegExp.prototype; Value.redefine(OrigRegExp.prototype, 'constructor', RegExpShim); /*globals RegExp: true */ RegExp = RegExpShim; Value.redefine(globals, 'RegExp', RegExpShim); /*globals RegExp: false */ } var MathShims = { acosh: function (value) { var x = Number(value); if (Number.isNaN(x) || value < 1) { return NaN; } if (x === 1) { return 0; } if (x === Infinity) { return x; } return Math.log(x / Math.E + Math.sqrt(x + 1) * Math.sqrt(x - 1) / Math.E) + 1; }, asinh: function (value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function (value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) { return -Infinity; } if (value === 1) { return Infinity; } if (value === 0) { return value; } return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function (value) { value = Number(value); if (value === 0) { return value; } var negate = value < 0, result; if (negate) { value = -value; } result = Math.pow(value, 1 / 3); return negate ? -result : result; }, clz32: function (value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function (value) { value = Number(value); if (value === 0) { return 1; } // +0 or -0 if (Number.isNaN(value)) { return NaN; } if (!global_isFinite(value)) { return Infinity; } if (value < 0) { value = -value; } if (value > 21) { return Math.exp(value) / 2; } return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function (value) { var x = Number(value); if (x === -Infinity) { return -1; } if (!global_isFinite(x) || value === 0) { return x; } if (Math.abs(x) > 0.5) { return Math.exp(x) - 1; } // A more precise approximation using Taylor series expansion // from https://github.com/paulmillr/es6-shim/issues/314#issuecomment-70293986 var t = x; var sum = 0; var n = 1; while (sum + t !== sum) { sum += t; n += 1; t *= x / n; } return sum; }, hypot: function (x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function (arg) { var num = Number(arg); if (Number.isNaN(num)) { anyNaN = true; } else if (num === Infinity || num === -Infinity) { anyInfinity = true; } else if (num !== 0) { allZero = false; } if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) { return Infinity; } if (anyNaN) { return NaN; } if (allZero) { return 0; } numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum + (number * number); }, 0); return largest * Math.sqrt(sum); }, log2: function (value) { return Math.log(value) * Math.LOG2E; }, log10: function (value) { return Math.log(value) * Math.LOG10E; }, log1p: function (value) { var x = Number(value); if (x < -1 || Number.isNaN(x)) { return NaN; } if (x === 0 || x === Infinity) { return x; } if (x === -1) { return -Infinity; } return (1 + x) - 1 === 0 ? x : x * (Math.log(1 + x) / ((1 + x) - 1)); }, sign: function (value) { var number = +value; if (number === 0) { return number; } if (Number.isNaN(number)) { return number; } return number < 0 ? -1 : 1; }, sinh: function (value) { var x = Number(value); if (!global_isFinite(value) || value === 0) { return value; } if (Math.abs(x) < 1) { return (Math.expm1(x) - Math.expm1(-x)) / 2; } return (Math.exp(x - 1) - Math.exp(-x - 1)) * Math.E / 2; }, tanh: function (value) { var x = Number(value); if (Number.isNaN(value) || x === 0) { return x; } if (x === Infinity) { return 1; } if (x === -Infinity) { return -1; } var a = Math.expm1(x); var b = Math.expm1(-x); if (a === Infinity) { return 1; } if (b === Infinity) { return -1; } return (a - b) / (Math.exp(x) + Math.exp(-x)); }, trunc: function (value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function (x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul x = ES.ToUint32(x); y = ES.ToUint32(y); var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0); }, fround: function (x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); // Chrome 40 has an imprecise Math.tanh with very small numbers defineProperty(Math, 'tanh', MathShims.tanh, Math.tanh(-2e-17) !== -2e-17); // Chrome 40 loses Math.acosh precision with high numbers defineProperty(Math, 'acosh', MathShims.acosh, Math.acosh(Number.MAX_VALUE) === Infinity); // node 0.11 has an imprecise Math.sinh with very small numbers defineProperty(Math, 'sinh', MathShims.sinh, Math.sinh(-2e-17) !== -2e-17); // FF 35 on Linux reports 22025.465794806725 for Math.expm1(10) var expm1OfTen = Math.expm1(10); defineProperty(Math, 'expm1', MathShims.expm1, expm1OfTen > 22025.465794806719 || expm1OfTen < 22025.4657948067165168); var roundHandlesBoundaryConditions = Math.round(0.5 - Number.EPSILON / 4) === 0 && Math.round(-0.5 + Number.EPSILON / 3.99) === 1; var origMathRound = Math.round; defineProperty(Math, 'round', function round(x) { if (-0.5 <= x && x < 0.5 && x !== 0) { return Math.sign(x * 0); } return origMathRound(x); }, !roundHandlesBoundaryConditions); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function () { var Promise, Promise$prototype; ES.IsPromise = function (promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (typeof promise._status === 'undefined') { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function (C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; /*global window */ if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function () { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = 'zero-timeout-message'; var setZeroTimeout = function (fn) { timeouts.push(fn); window.postMessage(messageName, '*'); }; var handleMessage = function (event) { if (event.source === window && event.data === messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener('message', handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function () { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function (task) { return P.resolve().then(task); }; }; /*global process */ var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function (task) { setTimeout(task, 0); }); // fallback var updatePromiseFromPotentialThenable = function (x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch (e) { reject(e); } return true; }; var triggerPromiseReactions = function (reactions, x) { reactions.forEach(function (reaction) { enqueue(function () { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var promiseResolutionHandler = function (promise, onFulfilled, onRejected) { return function (x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function (resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (typeof promise._status !== 'undefined') { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function (resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = void 0; promise._rejectReactions = void 0; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function (reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = void 0; promise._rejectReactions = void 0; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; var _promiseAllResolver = function (index, values, capability, remaining) { var done = false; return function (x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; defineProperty(Promise, symbolSpecies, function (obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: void 0, _result: void 0, _resolveReactions: void 0, _rejectReactions: void 0, _promiseConstructor: void 0 }); obj._promiseConstructor = constructor; return obj; }); defineProperties(Promise, { all: function all(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }, race: function race(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }, reject: function reject(reason) { var C = this; var capability = new PromiseCapability(C); var rejectPromise = capability.reject; rejectPromise(reason); // call with this===undefined return capability.promise; }, resolve: function resolve(v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolvePromise = capability.resolve; resolvePromise(v); // call with this===undefined return capability.promise; } }); defineProperties(Promise$prototype, { 'catch': function (onRejected) { return this.then(void 0, onRejected); }, then: function then(onFulfilled, onRejected) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function (e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function (x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; } }); return Promise; }()); // Chrome's native Promise has extra methods that it shouldn't have. Let's remove them. if (globals.Promise) { delete globals.Promise.accept; delete globals.Promise.defer; delete globals.Promise.prototype.chain; } // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function (S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, noop); return true; } catch (ex) { return false; } }()); var promiseRequiresObjectContext = (function () { /*global Promise */ try { Promise.call(3, noop); } catch (e) { return true; } return false; }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks || !promiseRequiresObjectContext) { /*globals Promise: true */ Promise = PromiseShim; /*globals Promise: false */ defineProperty(globals, 'Promise', PromiseShim, true); } // Map and Set require a true ES5 environment // Their fast path also requires that the environment preserve // property insertion order, which is not guaranteed by the spec. var testOrder = function (a) { var b = Object.keys(a.reduce(function (o, k) { o[k] = true; return o; }, {})); return a.join(':') === b.join(':'); }; var preservesInsertionOrder = testOrder(['z', 'a', 'bb']); // some engines (eg, Chrome) only preserve insertion order for string keys var preservesNumericInsertionOrder = testOrder(['z', 1, 'a', '3', 2]); if (supportsDescriptors) { var fastkey = function fastkey(key) { if (!preservesInsertionOrder) { return null; } var type = typeof key; if (type === 'string') { return '$' + key; } else if (type === 'number') { // note that -0 will get coerced to "0" when used as a property key if (!preservesNumericInsertionOrder) { return 'n' + key; } return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function () { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function () { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function () { var i = this.i, kind = this.kind, head = this.head, result; if (typeof this.i === 'undefined') { return { value: void 0, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === 'key') { result = i.key; } else if (kind === 'value') { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = void 0; return { value: void 0, done: true }; } }; addIterator(MapIterator.prototype); function Map(iterable) { var map = this; if (!ES.TypeIsObject(map)) { throw new TypeError('Map does not accept arguments when called as a function'); } map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { _head: head, _storage: emptyObject(), _size: 0 }); // Optionally initialize map from iterable if (typeof iterable !== 'undefined' && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperty(Map, symbolSpecies, function (obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; }); Value.getter(Map.prototype, 'size', function () { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; }); defineProperties(Map.prototype, { get: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; if (entry) { return entry.value; } else { return; } } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } }, has: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function (key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return this; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return this; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; return this; }, 'delete': function (key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function () { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function () { return new MapIterator(this, 'key'); }, values: function () { return new MapIterator(this, 'value'); }, entries: function () { return new MapIterator(this, 'key+value'); }, forEach: function (callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { if (context) { callback.call(context, entry.value[1], entry.value[0], this); } else { callback(entry.value[1], entry.value[0], this); } } } }); addIterator(Map.prototype, function () { return this.entries(); }); return Map; }()), Set: (function () { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set(iterable) { var set = this; if (!ES.TypeIsObject(set)) { throw new TypeError('Set does not accept arguments when called as a function'); } set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, _storage: emptyObject() }); // Optionally initialize map from iterable if (typeof iterable !== 'undefined' && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperty(SetShim, symbolSpecies, function (obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function (k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.slice(1); } else if (k.charAt(0) === 'n') { k = +k.slice(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Value.getter(SetShim.prototype, 'size', function () { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; }); defineProperties(SetShim.prototype, { has: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey] = true; return this; } ensureMap(this); this['[[SetData]]'].set(key, key); return this; }, 'delete': function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { var hasFKey = _hasOwnProperty(this._storage, fkey); return (delete this._storage[fkey]) && hasFKey; } ensureMap(this); return this['[[SetData]]']['delete'](key); }, clear: function () { if (this._storage) { this._storage = emptyObject(); } else { this['[[SetData]]'].clear(); } }, values: function () { ensureMap(this); return this['[[SetData]]'].values(); }, entries: function () { ensureMap(this); return this['[[SetData]]'].entries(); }, forEach: function (callback) { var context = arguments.length > 1 ? arguments[1] : null; var entireSet = this; ensureMap(entireSet); this['[[SetData]]'].forEach(function (value, key) { if (context) { callback.call(context, key, key, entireSet); } else { callback(key, key, entireSet); } }); } }); defineProperty(SetShim, 'keys', SetShim.values, true); addIterator(SetShim.prototype, function () { return this.values(); }); return SetShim; }()) }; defineProperties(globals, collectionShims); if (globals.Map || globals.Set) { /* - In Firefox < 23, Map#size is a function. - In all current Firefox, Set#entries/keys/values & Map#clear do not exist - https://bugzilla.mozilla.org/show_bug.cgi?id=869996 - In Firefox 24, Map and Set do not implement forEach - In Firefox 25 at least, Map and Set are callable without "new" */ if ( typeof globals.Map.prototype.clear !== 'function' || new globals.Set().size !== 0 || new globals.Map().size !== 0 || typeof globals.Map.prototype.keys !== 'function' || typeof globals.Set.prototype.keys !== 'function' || typeof globals.Map.prototype.forEach !== 'function' || typeof globals.Set.prototype.forEach !== 'function' || isCallableWithoutNew(globals.Map) || isCallableWithoutNew(globals.Set) || !supportsSubclassing(globals.Map, function (M) { var m = new M([]); // Firefox 32 is ok with the instantiating the subclass but will // throw when the map is used. m.set(42, 42); return m instanceof M; }) ) { globals.Map = collectionShims.Map; globals.Set = collectionShims.Set; } } if (globals.Set.prototype.keys !== globals.Set.prototype.values) { defineProperty(globals.Set.prototype, 'keys', globals.Set.prototype.values, true); } // Shim incomplete iterator implementations. addIterator(Object.getPrototypeOf((new globals.Map()).keys())); addIterator(Object.getPrototypeOf((new globals.Set()).keys())); } // Reflect if (!globals.Reflect) { defineProperty(globals, 'Reflect', {}); } var Reflect = globals.Reflect; var throwUnlessTargetIsObject = function throwUnlessTargetIsObject(target) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } }; // Some Reflect methods are basically the same as // those on the Object global, except that a TypeError is thrown if // target isn't an object. As well as returning a boolean indicating // the success of the operation. defineProperties(globals.Reflect, { // Apply method in a functional form. apply: function apply() { return ES.Call.apply(null, arguments); }, // New operator in a functional form. construct: function construct(constructor, args) { if (!ES.IsCallable(constructor)) { throw new TypeError('First argument must be callable.'); } return ES.Construct(constructor, args); }, // When deleting a non-existent or configurable property, // true is returned. // When attempting to delete a non-configurable property, // it will return false. deleteProperty: function deleteProperty(target, key) { throwUnlessTargetIsObject(target); if (supportsDescriptors) { var desc = Object.getOwnPropertyDescriptor(target, key); if (desc && !desc.configurable) { return false; } } // Will return true. return delete target[key]; }, enumerate: function enumerate(target) { throwUnlessTargetIsObject(target); return new ObjectIterator(target, 'key'); }, has: function has(target, key) { throwUnlessTargetIsObject(target); return key in target; } }); if (Object.getOwnPropertyNames) { defineProperties(globals.Reflect, { // Basically the result of calling the internal [[OwnPropertyKeys]]. // Concatenating propertyNames and propertySymbols should do the trick. // This should continue to work together with a Symbol shim // which overrides Object.getOwnPropertyNames and implements // Object.getOwnPropertySymbols. ownKeys: function ownKeys(target) { throwUnlessTargetIsObject(target); var keys = Object.getOwnPropertyNames(target); if (ES.IsCallable(Object.getOwnPropertySymbols)) { keys.push.apply(keys, Object.getOwnPropertySymbols(target)); } return keys; } }); } if (Object.preventExtensions) { defineProperties(globals.Reflect, { isExtensible: function isExtensible(target) { throwUnlessTargetIsObject(target); return Object.isExtensible(target); }, preventExtensions: function preventExtensions(target) { throwUnlessTargetIsObject(target); return callAndCatchException(function () { Object.preventExtensions(target); }); } }); } if (supportsDescriptors) { var internal_get = function get(target, key, receiver) { var desc = Object.getOwnPropertyDescriptor(target, key); if (!desc) { var parent = Object.getPrototypeOf(target); if (parent === null) { return undefined; } return internal_get(parent, key, receiver); } if ('value' in desc) { return desc.value; } if (desc.get) { return desc.get.call(receiver); } return undefined; }; var internal_set = function set(target, key, value, receiver) { var desc = Object.getOwnPropertyDescriptor(target, key); if (!desc) { var parent = Object.getPrototypeOf(target); if (parent !== null) { return internal_set(parent, key, value, receiver); } desc = { value: void 0, writable: true, enumerable: true, configurable: true }; } if ('value' in desc) { if (!desc.writable) { return false; } if (!ES.TypeIsObject(receiver)) { return false; } var existingDesc = Object.getOwnPropertyDescriptor(receiver, key); if (existingDesc) { return Reflect.defineProperty(receiver, key, { value: value }); } else { return Reflect.defineProperty(receiver, key, { value: value, writable: true, enumerable: true, configurable: true }); } } if (desc.set) { desc.set.call(receiver, value); return true; } return false; }; var callAndCatchException = function ConvertExceptionToBoolean(func) { try { func(); } catch (_) { return false; } return true; }; defineProperties(globals.Reflect, { defineProperty: function defineProperty(target, propertyKey, attributes) { throwUnlessTargetIsObject(target); return callAndCatchException(function () { Object.defineProperty(target, propertyKey, attributes); }); }, getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { throwUnlessTargetIsObject(target); return Object.getOwnPropertyDescriptor(target, propertyKey); }, // Syntax in a functional form. get: function get(target, key) { throwUnlessTargetIsObject(target); var receiver = arguments.length > 2 ? arguments[2] : target; return internal_get(target, key, receiver); }, set: function set(target, key, value) { throwUnlessTargetIsObject(target); var receiver = arguments.length > 3 ? arguments[3] : target; return internal_set(target, key, value, receiver); } }); } if (Object.getPrototypeOf) { var objectDotGetPrototypeOf = Object.getPrototypeOf; defineProperties(globals.Reflect, { getPrototypeOf: function getPrototypeOf(target) { throwUnlessTargetIsObject(target); return objectDotGetPrototypeOf(target); } }); } if (Object.setPrototypeOf) { var willCreateCircularPrototype = function (object, proto) { while (proto) { if (object === proto) { return true; } proto = Reflect.getPrototypeOf(proto); } return false; }; defineProperties(globals.Reflect, { // Sets the prototype of the given object. // Returns true on success, otherwise false. setPrototypeOf: function setPrototypeOf(object, proto) { throwUnlessTargetIsObject(object); if (proto !== null && !ES.TypeIsObject(proto)) { throw new TypeError('proto must be an object or null'); } // If they already are the same, we're done. if (proto === Reflect.getPrototypeOf(object)) { return true; } // Cannot alter prototype if object not extensible. if (Reflect.isExtensible && !Reflect.isExtensible(object)) { return false; } // Ensure that we do not create a circular prototype chain. if (willCreateCircularPrototype(object, proto)) { return false; } Object.setPrototypeOf(object, proto); return true; } }); } if (String(new Date(NaN)) !== 'Invalid Date') { var dateToString = Date.prototype.toString; var shimmedDateToString = function toString() { var valueOf = +this; if (valueOf !== valueOf) { return 'Invalid Date'; } return dateToString.call(this); }; defineProperty(shimmedDateToString, 'toString', dateToString.toString, true); defineProperty(Date.prototype, 'toString', shimmedDateToString, true); } // Annex B HTML methods // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-additional-properties-of-the-string.prototype-object var stringHTMLshims = { anchor: function anchor(name) { return ES.CreateHTML(this, 'a', 'name', name); }, big: function big() { return ES.CreateHTML(this, 'big', '', ''); }, blink: function blink() { return ES.CreateHTML(this, 'blink', '', ''); }, bold: function bold() { return ES.CreateHTML(this, 'b', '', ''); }, fixed: function fixed() { return ES.CreateHTML(this, 'tt', '', ''); }, fontcolor: function fontcolor(color) { return ES.CreateHTML(this, 'font', 'color', color); }, fontsize: function fontsize(size) { return ES.CreateHTML(this, 'font', 'size', size); }, italics: function italics() { return ES.CreateHTML(this, 'i', '', ''); }, link: function link(url) { return ES.CreateHTML(this, 'a', 'href', url); }, small: function small(url) { return ES.CreateHTML(this, 'small', '', ''); }, strike: function strike(url) { return ES.CreateHTML(this, 'strike', '', ''); }, sub: function sub(url) { return ES.CreateHTML(this, 'sub', '', ''); }, sup: function sub(url) { return ES.CreateHTML(this, 'sup', '', ''); } }; defineProperties(String.prototype, stringHTMLshims); Object.keys(stringHTMLshims).forEach(function (key) { var method = String.prototype[key]; var shouldOverwrite = false; if (ES.IsCallable(method)) { var output = method.call('', ' " '); var quotesCount = [].concat(output.match(/"/g)).length; shouldOverwrite = output !== output.toLowerCase() || quotesCount > 2; } else { shouldOverwrite = true; } if (shouldOverwrite) { defineProperty(String.prototype, key, stringHTMLshims[key], true); } }); return globals; }));
src/components/checkbox.js
LINKIWI/react-elemental
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { withForwardedRef } from '@linkiwi/hoc'; import Spacing from 'components/spacing'; import Text from 'components/text'; import Check from 'icons/check'; import { colors } from 'styles/color'; import { transitionStyle } from 'styles/transition'; import noop from 'util/noop'; /** * Styled checkbox element. */ class Checkbox extends Component { static propTypes = { checked: PropTypes.bool, label: PropTypes.string, style: PropTypes.object, disabled: PropTypes.bool, onChange: PropTypes.func, children: PropTypes.node, forwardedRef: PropTypes.oneOfType([ PropTypes.shape({ current: PropTypes.instanceOf(Element) }), PropTypes.func, ]), }; static defaultProps = { checked: false, label: null, style: {}, disabled: false, onChange: noop, children: null, forwardedRef: null, }; state = { isHover: false, isFocus: false }; handleClick = () => { const { checked, onChange, disabled } = this.props; return !disabled && onChange(!checked); }; handleHoverChange = (isHover) => () => this.setState({ isHover }); handleFocusChange = (isFocus) => () => this.setState({ isFocus }); render() { const { checked, label, style: overrides, disabled, children, forwardedRef, ...proxyProps } = this.props; const { isHover, isFocus } = this.state; const isActive = isHover || isFocus; const backgroundColor = (() => { if (checked) { return colors.primary; } return disabled ? colors.gray5 : 'rgb(250, 250, 250)'; })(); const borderColor = (() => { if (checked) { return colors.primary; } return isActive ? colors.gray20 : colors.gray10; })(); const containerStyle = { alignItems: 'center', background: 'inherit', border: 0, cursor: disabled ? 'inherit' : 'pointer', display: 'inline-flex', ...overrides, }; const checkboxStyle = { alignItems: 'center', backgroundColor, border: `1px solid ${borderColor}`, display: 'flex', height: '14px', justifyContent: 'center', opacity: disabled ? 0.5 : 1, width: '14px', ...transitionStyle(), }; const checkStyle = { fill: colors.gray5, height: '12px', opacity: checked ? 1 : 0, ...transitionStyle(), }; return ( <button ref={forwardedRef} role="checkbox" aria-checked={checked} style={containerStyle} onClick={this.handleClick} onMouseEnter={this.handleHoverChange(true)} onMouseLeave={this.handleHoverChange(false)} onFocus={this.handleFocusChange(true)} onBlur={this.handleFocusChange(false)} {...proxyProps} > <div style={checkboxStyle}> <Check style={checkStyle} /> </div> {label && ( <Spacing size="small" left inline> <Text size="iota" color="gray80" inline> {label} </Text> </Spacing> )} {children} </button> ); } } export default withForwardedRef(Checkbox);
ajax/libs/x-editable/1.4.5/bootstrap-editable/js/bootstrap-editable.js
brix/cdnjs
/*! X-editable - v1.4.5 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ /** Form with single input element, two buttons and two states: normal/loading. Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown. Editableform is linked with one of input types, e.g. 'text', 'select' etc. @class editableform @uses text @uses textarea **/ (function ($) { "use strict"; var EditableForm = function (div, options) { this.options = $.extend({}, $.fn.editableform.defaults, options); this.$div = $(div); //div, containing form. Not form tag. Not editable-element. if(!this.options.scope) { this.options.scope = this; } //nothing shown after init }; EditableForm.prototype = { constructor: EditableForm, initInput: function() { //called once //take input from options (as it is created in editable-element) this.input = this.options.input; //set initial value //todo: may be add check: typeof str === 'string' ? this.value = this.input.str2value(this.options.value); }, initTemplate: function() { this.$form = $($.fn.editableform.template); }, initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } }, /** Renders editableform @method render **/ render: function() { //init loader this.$loading = $($.fn.editableform.loading); this.$div.empty().append(this.$loading); //init form template and buttons this.initTemplate(); if(this.options.showbuttons) { this.initButtons(); } else { this.$form.find('.editable-buttons').remove(); } //show loading state this.showLoading(); //flag showing is form now saving value to server. //It is needed to wait when closing form. this.isSaving = false; /** Fired when rendering starts @event rendering @param {Object} event event object **/ this.$div.triggerHandler('rendering'); //init input this.initInput(); //append input to form this.input.prerender(); this.$form.find('div.editable-input').append(this.input.$tpl); //append form to container this.$div.append(this.$form); //render input $.when(this.input.render()) .then($.proxy(function () { //setup input to submit automatically when no buttons shown if(!this.options.showbuttons) { this.input.autosubmit(); } //attach 'cancel' handler this.$form.find('.editable-cancel').click($.proxy(this.cancel, this)); if(this.input.error) { this.error(this.input.error); this.$form.find('.editable-submit').attr('disabled', true); this.input.$input.attr('disabled', true); //prevent form from submitting this.$form.submit(function(e){ e.preventDefault(); }); } else { this.error(false); this.input.$input.removeAttr('disabled'); this.$form.find('.editable-submit').removeAttr('disabled'); this.input.value2input(this.value); //attach submit handler this.$form.submit($.proxy(this.submit, this)); } /** Fired when form is rendered @event rendered @param {Object} event event object **/ this.$div.triggerHandler('rendered'); this.showForm(); //call postrender method to perform actions required visibility of form if(this.input.postrender) { this.input.postrender(); } }, this)); }, cancel: function() { /** Fired when form was cancelled by user @event cancel @param {Object} event event object **/ this.$div.triggerHandler('cancel'); }, showLoading: function() { var w, h; if(this.$form) { //set loading size equal to form w = this.$form.outerWidth(); h = this.$form.outerHeight(); if(w) { this.$loading.width(w); } if(h) { this.$loading.height(h); } this.$form.hide(); } else { //stretch loading to fill container width w = this.$loading.parent().width(); if(w) { this.$loading.width(w); } } this.$loading.show(); }, showForm: function(activate) { this.$loading.hide(); this.$form.show(); if(activate !== false) { this.input.activate(); } /** Fired when form is shown @event show @param {Object} event event object **/ this.$div.triggerHandler('show'); }, error: function(msg) { var $group = this.$form.find('.control-group'), $block = this.$form.find('.editable-error-block'), lines; if(msg === false) { $group.removeClass($.fn.editableform.errorGroupClass); $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); } else { //convert newline to <br> for more pretty error display if(msg) { lines = msg.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } msg = lines.join('<br>'); } $group.addClass($.fn.editableform.errorGroupClass); $block.addClass($.fn.editableform.errorBlockClass).html(msg).show(); } }, submit: function(e) { e.stopPropagation(); e.preventDefault(); var error, newValue = this.input.input2value(); //get new value from input //validation if (error = this.validate(newValue)) { this.error(error); this.showForm(); return; } //if value not changed --> trigger 'nochange' event and return /*jslint eqeq: true*/ if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) { /*jslint eqeq: false*/ /** Fired when value not changed but form is submitted. Requires savenochange = false. @event nochange @param {Object} event event object **/ this.$div.triggerHandler('nochange'); return; } //convert value for submitting to server var submitValue = this.input.value2submit(newValue); this.isSaving = true; //sending data to server $.when(this.save(submitValue)) .done($.proxy(function(response) { this.isSaving = false; //run success callback var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null; //if success callback returns false --> keep form open and do not activate input if(res === false) { this.error(false); this.showForm(false); return; } //if success callback returns string --> keep form open, show error and activate input if(typeof res === 'string') { this.error(res); this.showForm(); return; } //if success callback returns object like {newValue: <something>} --> use that value instead of submitted //it is usefull if you want to chnage value in url-function if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) { newValue = res.newValue; } //clear error message this.error(false); this.value = newValue; /** Fired when form is submitted @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue raw new value @param {mixed} params.submitValue submitted value as string @param {Object} params.response ajax response @example $('#form-div').on('save'), function(e, params){ if(params.newValue === 'username') {...} }); **/ this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response}); }, this)) .fail($.proxy(function(xhr) { this.isSaving = false; var msg; if(typeof this.options.error === 'function') { msg = this.options.error.call(this.options.scope, xhr, newValue); } else { msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!'; } this.error(msg); this.showForm(); }, this)); }, save: function(submitValue) { //try parse composite pk defined as json string in data-pk this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk, /* send on server in following cases: 1. url is function 2. url is string AND (pk defined OR send option = always) */ send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))), params; if (send) { //send to server this.showLoading(); //standard params params = { name: this.options.name || '', value: submitValue, pk: pk }; //additional params if(typeof this.options.params === 'function') { params = this.options.params.call(this.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true); $.extend(params, this.options.params); } if(typeof this.options.url === 'function') { //user's function return this.options.url.call(this.options.scope, params); } else { //send ajax to server and return deferred object return $.ajax($.extend({ url : this.options.url, data : params, type : 'POST' }, this.options.ajaxOptions)); } } }, validate: function (value) { if (value === undefined) { value = this.value; } if (typeof this.options.validate === 'function') { return this.options.validate.call(this.options.scope, value); } }, option: function(key, value) { if(key in this.options) { this.options[key] = value; } if(key === 'value') { this.setValue(value); } //do not pass option to input as it is passed in editable-element }, setValue: function(value, convertStr) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } //if form is visible, update input if(this.$form && this.$form.is(':visible')) { this.input.value2input(this.value); } } }; /* Initialize editableform. Applied to jQuery object. @method $().editableform(options) @params {Object} options @example var $form = $('&lt;div&gt;').editableform({ type: 'text', name: 'username', url: '/post', value: 'vitaliy' }); //to display form you should call 'render' method $form.editableform('render'); */ $.fn.editableform = function (option) { var args = arguments; return this.each(function () { var $this = $(this), data = $this.data('editableform'), options = typeof option === 'object' && option; if (!data) { $this.data('editableform', (data = new EditableForm(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //keep link to constructor to allow inheritance $.fn.editableform.Constructor = EditableForm; //defaults $.fn.editableform.defaults = { /* see also defaults for input */ /** Type of input. Can be <code>text|textarea|select|date|checklist</code> @property type @type string @default 'text' **/ type: 'text', /** Url for submit, e.g. <code>'/post'</code> If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks. @property url @type string|function @default null @example url: function(params) { var d = new $.Deferred; if(params.value === 'abc') { return d.reject('error message'); //returning error via deferred object } else { //async saving data in js model someModel.asyncSaveMethod({ ..., success: function(){ d.resolve(); } }); return d.promise(); } } **/ url:null, /** Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value). If defined as <code>function</code> - returned object **overwrites** original ajax data. @example params: function(params) { //originally params contain pk, name and value params.a = 1; return params; } @property params @type object|function @default null **/ params:null, /** Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute @property name @type string @default null **/ name: null, /** Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>. Can be calculated dynamically via function. @property pk @type string|object|function @default null **/ pk: null, /** Initial value. If not defined - will be taken from element's content. For __select__ type should be defined (as it is ID of shown text). @property value @type string|object @default null **/ value: null, /** Strategy for sending data on server. Can be <code>auto|always|never</code>. When 'auto' data will be sent on server only if pk defined, otherwise new value will be stored in element. @property send @type string @default 'auto' **/ send: 'auto', /** Function for client-side validation. If returns string - means validation not passed and string showed as error. @property validate @type function @default null @example validate: function(value) { if($.trim(value) == '') { return 'This field is required'; } } **/ validate: null, /** Success callback. Called when value successfully sent on server and **response status = 200**. Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code> or <code>{success: false, msg: "server error"}</code> you can check it inside this callback. If it returns **string** - means error occured and string is shown as error message. If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user. Otherwise newValue simply rendered into element. @property success @type function @default null @example success: function(response, newValue) { if(!response.success) return response.msg; } **/ success: null, /** Error callback. Called when request failed (response status != 200). Usefull when you want to parse error response and display a custom message. Must return **string** - the message to be displayed in the error block. @property error @type function @default null @since 1.4.4 @example error: function(response, newValue) { if(response.status === 500) { return 'Service unavailable. Please try later.'; } else { return response.responseText; } } **/ error: null, /** Additional options for submit ajax request. List of values: http://api.jquery.com/jQuery.ajax @property ajaxOptions @type object @default null @since 1.1.1 @example ajaxOptions: { type: 'put', dataType: 'json' } **/ ajaxOptions: null, /** Where to show buttons: left(true)|bottom|false Form without buttons is auto-submitted. @property showbuttons @type boolean|string @default true @since 1.1.1 **/ showbuttons: true, /** Scope for callback methods (success, validate). If <code>null</code> means editableform instance itself. @property scope @type DOMElement|object @default null @since 1.2.0 @private **/ scope: null, /** Whether to save or cancel value when it was not changed but form was submitted @property savenochange @type boolean @default false @since 1.2.0 **/ savenochange: false }; /* Note: following params could redefined in engine: bootstrap or jqueryui: Classes 'control-group' and 'editable-error-block' must always present! */ $.fn.editableform.template = '<form class="form-inline editableform">'+ '<div class="control-group">' + '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+ '<div class="editable-error-block"></div>' + '</div>' + '</form>'; //loading div $.fn.editableform.loading = '<div class="editableform-loading"></div>'; //buttons $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+ '<button type="button" class="editable-cancel">cancel</button>'; //error class attached to control-group $.fn.editableform.errorGroupClass = null; //error class attached to editable-error-block $.fn.editableform.errorBlockClass = 'editable-error'; }(window.jQuery)); /** * EditableForm utilites */ (function ($) { "use strict"; //utils $.fn.editableutils = { /** * classic JS inheritance function */ inherit: function (Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }, /** * set caret position in input * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */ setCursorPosition: function(elem, pos) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, /** * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes) * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}"> * safe = true --> means no exception will be thrown * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery */ tryParseJson: function(s, safe) { if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) { if (safe) { try { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } catch (e) {} finally { return s; } } else { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } } return s; }, /** * slice object by specified keys */ sliceObj: function(obj, keys, caseSensitive /* default: false */) { var key, keyLower, newObj = {}; if (!$.isArray(keys) || !keys.length) { return newObj; } for (var i = 0; i < keys.length; i++) { key = keys[i]; if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } if(caseSensitive === true) { continue; } //when getting data-* attributes via $.data() it's converted to lowercase. //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery //workaround is code below. keyLower = key.toLowerCase(); if (obj.hasOwnProperty(keyLower)) { newObj[key] = obj[keyLower]; } } return newObj; }, /* exclude complex objects from $.data() before pass to config */ getConfigData: function($element) { var data = {}; $.each($element.data(), function(k, v) { if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) { data[k] = v; } }); return data; }, /* returns keys of object */ objectKeys: function(o) { if (Object.keys) { return Object.keys(o); } else { if (o !== Object(o)) { throw new TypeError('Object.keys called on a non-object'); } var k=[], p; for (p in o) { if (Object.prototype.hasOwnProperty.call(o,p)) { k.push(p); } } return k; } }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /* returns array items from sourceData having value property equal or inArray of 'value' */ itemsByValue: function(value, sourceData, valueProp) { if(!sourceData || value === null) { return []; } valueProp = valueProp || 'value'; var isValArray = $.isArray(value), result = [], that = this; $.each(sourceData, function(i, o) { if(o.children) { result = result.concat(that.itemsByValue(value, o.children, valueProp)); } else { /*jslint eqeq: true*/ if(isValArray) { if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? o[valueProp] : o); }).length) { result.push(o); } } else { if(value == (o && typeof o === 'object' ? o[valueProp] : o)) { result.push(o); } } /*jslint eqeq: false*/ } }); return result; }, /* Returns input by options: type, mode. */ createInput: function(options) { var TypeConstructor, typeOptions, input, type = options.type; //`date` is some kind of virtual type that is transformed to one of exact types //depending on mode and core lib if(type === 'date') { //inline if(options.mode === 'inline') { if($.fn.editabletypes.datefield) { type = 'datefield'; } else if($.fn.editabletypes.dateuifield) { type = 'dateuifield'; } //popup } else { if($.fn.editabletypes.date) { type = 'date'; } else if($.fn.editabletypes.dateui) { type = 'dateui'; } } //if type still `date` and not exist in types, replace with `combodate` that is base input if(type === 'date' && !$.fn.editabletypes.date) { type = 'combodate'; } } //`datetime` should be datetimefield in 'inline' mode if(type === 'datetime' && options.mode === 'inline') { type = 'datetimefield'; } //change wysihtml5 to textarea for jquery UI and plain versions if(type === 'wysihtml5' && !$.fn.editabletypes[type]) { type = 'textarea'; } //create input of specified type. Input will be used for converting value, not in form if(typeof $.fn.editabletypes[type] === 'function') { TypeConstructor = $.fn.editabletypes[type]; typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults)); input = new TypeConstructor(typeOptions); return input; } else { $.error('Unknown type: '+ type); return false; } }, //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions: function () { var b = document.body || document.documentElement, s = b.style, p = 'transition', v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms']; if(typeof s[p] === 'string') { return true; } // Tests for vendor specific prop p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] === 'string') { return true; } } return false; } }; }(window.jQuery)); /** Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br> This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br> Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br> Applied as jQuery method. @class editableContainer @uses editableform **/ (function ($) { "use strict"; var Popup = function (element, options) { this.init(element, options); }; var Inline = function (element, options) { this.init(element, options); }; //methods Popup.prototype = { containerName: null, //tbd in child class innerCss: null, //tbd in child class containerClass: 'editable-container editable-popup', //css class applied to container element init: function(element, options) { this.$element = $(element); //since 1.4.1 container do not use data-* directly as they already merged into options. this.options = $.extend({}, $.fn.editableContainer.defaults, options); this.splitOptions(); //set scope of form callbacks to element this.formOptions.scope = this.$element[0]; this.initContainer(); //flag to hide container, when saving value will finish this.delayedHide = false; //bind 'destroyed' listener to destroy container when element is removed from dom this.$element.on('destroyed', $.proxy(function(){ this.destroy(); }, this)); //attach document handler to close containers on click / escape if(!$(document).data('editable-handlers-attached')) { //close all on escape $(document).on('keyup.editable', function (e) { if (e.which === 27) { $('.editable-open').editableContainer('hide'); //todo: return focus on element } }); //close containers when click outside //(mousedown could be better than click, it closes everything also on drag drop) $(document).on('click.editable', function(e) { var $target = $(e.target), i, exclude_classes = ['.editable-container', '.ui-datepicker-header', '.datepicker', //in inline mode datepicker is rendered into body '.modal-backdrop', '.bootstrap-wysihtml5-insert-image-modal', '.bootstrap-wysihtml5-insert-link-modal' ]; //check if element is detached. It occurs when clicking in bootstrap datepicker if (!$.contains(document.documentElement, e.target)) { return; } //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199 //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec if($target.is(document)) { return; } //if click inside one of exclude classes --> no nothing for(i=0; i<exclude_classes.length; i++) { if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) { return; } } //close all open containers (except one - target) Popup.prototype.closeOthers(e.target); }); $(document).data('editable-handlers-attached', true); } }, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; if(!$.fn[this.containerName]) { throw new Error(this.containerName + ' not found. Have you included corresponding js file?'); } var cDef = $.fn[this.containerName].defaults; //keys defined in container defaults go to container, others go to form for(var k in this.options) { if(k in cDef) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, /* Returns jquery object of container @method tip() */ tip: function() { return this.container() ? this.container().$tip : null; }, /* returns container object */ container: function() { return this.$element.data(this.containerDataName || this.containerName); }, /* call native method of underlying container, e.g. this.$element.popover('method') */ call: function() { this.$element[this.containerName].apply(this.$element, arguments); }, initContainer: function(){ this.call(this.containerOptions); }, renderForm: function() { this.$form .editableform(this.formOptions) .on({ save: $.proxy(this.save, this), //click on submit button (value changed) nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed) cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button show: $.proxy(function() { if(this.delayedHide) { this.hide(this.delayedHide.reason); this.delayedHide = false; } else { this.setPosition(); } }, this), //re-position container every time form is shown (occurs each time after loading state) rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed rendered: $.proxy(function(){ /** Fired when container is shown and form is rendered (for select will wait for loading dropdown options). **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event shown @param {Object} event event object @example $('#username').on('shown', function(e, editable) { editable.input.$input.val('overwriting value of input..'); }); **/ /* TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events. */ this.$element.triggerHandler('shown', this); }, this) }) .editableform('render'); }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ /* Note: poshytip owerwrites this method totally! */ show: function (closeAll) { this.$element.addClass('editable-open'); if(closeAll !== false) { //close all open containers (except this) this.closeOthers(this.$element[0]); } //show container itself this.innerShow(); this.tip().addClass(this.containerClass); /* Currently, form is re-rendered on every show. The main reason is that we dont know, what will container do with content when closed: remove(), detach() or just hide() - it depends on container. Detaching form itself before hide and re-insert before show is good solution, but visually it looks ugly --> container changes size before hide. */ //if form already exist - delete previous data if(this.$form) { //todo: destroy prev data! //this.$form.destroy(); } this.$form = $('<div>'); //insert form into container body if(this.tip().is(this.innerCss)) { //for inline container this.tip().append(this.$form); } else { this.tip().find(this.innerCss).append(this.$form); } //render form this.renderForm(); }, /** Hides container with form @method hide() @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code> **/ hide: function(reason) { if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) { return; } //if form is saving value, schedule hide if(this.$form.data('editableform').isSaving) { this.delayedHide = {reason: reason}; return; } else { this.delayedHide = false; } this.$element.removeClass('editable-open'); this.innerHide(); /** Fired when container was hidden. It occurs on both save or cancel. **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event hidden @param {object} event event object @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code> @example $('#username').on('hidden', function(e, reason) { if(reason === 'save' || reason === 'cancel') { //auto-open next editable $(this).closest('tr').next().find('.editable').editable('show'); } }); **/ this.$element.triggerHandler('hidden', reason || 'manual'); }, /* internal show method. To be overwritten in child classes */ innerShow: function () { }, /* internal hide method. To be overwritten in child classes */ innerHide: function () { }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container() && this.tip() && this.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* Updates the position of container when content changed. @method setPosition() */ setPosition: function() { //tbd in child class }, save: function(e, params) { /** Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { //assuming server response: '{success: true}' var pk = $(this).data('editableContainer').options.pk; if(params.response && params.response.success) { alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!'); } else { alert('error!'); } }); **/ this.$element.triggerHandler('save', params); //hide must be after trigger, as saving value may require methods of plugin, applied to input this.hide('save'); }, /** Sets new option @method option(key, value) @param {string} key @param {mixed} value **/ option: function(key, value) { this.options[key] = value; if(key in this.containerOptions) { this.containerOptions[key] = value; this.setContainerOption(key, value); } else { this.formOptions[key] = value; if(this.$form) { this.$form.editableform('option', key, value); } } }, setContainerOption: function(key, value) { this.call('option', key, value); }, /** Destroys the container instance @method destroy() **/ destroy: function() { this.hide(); this.innerDestroy(); this.$element.off('destroyed'); this.$element.removeData('editableContainer'); }, /* to be overwritten in child classes */ innerDestroy: function() { }, /* Closes other containers except one related to passed element. Other containers can be cancelled or submitted (depends on onblur option) */ closeOthers: function(element) { $('.editable-open').each(function(i, el){ //do nothing with passed element and it's children if(el === element || $(el).find(element).length) { return; } //otherwise cancel or submit all open containers var $el = $(el), ec = $el.data('editableContainer'); if(!ec) { return; } if(ec.options.onblur === 'cancel') { $el.data('editableContainer').hide('onblur'); } else if(ec.options.onblur === 'submit') { $el.data('editableContainer').tip().find('form').submit(); } }); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.tip && this.tip().is(':visible') && this.$form) { this.$form.data('editableform').input.activate(); } } }; /** jQuery method to initialize editableContainer. @method $().editableContainer(options) @params {Object} options @example $('#edit').editableContainer({ type: 'text', url: '/post', pk: 1, value: 'hello' }); **/ $.fn.editableContainer = function (option) { var args = arguments; return this.each(function () { var $this = $(this), dataKey = 'editableContainer', data = $this.data(dataKey), options = typeof option === 'object' && option, Constructor = (options.mode === 'inline') ? Inline : Popup; if (!data) { $this.data(dataKey, (data = new Constructor(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //store constructors $.fn.editableContainer.Popup = Popup; $.fn.editableContainer.Inline = Inline; //defaults $.fn.editableContainer.defaults = { /** Initial value of form input @property value @type mixed @default null @private **/ value: null, /** Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container. @property placement @type string @default 'top' **/ placement: 'top', /** Whether to hide container on save/cancel. @property autohide @type boolean @default true @private **/ autohide: true, /** Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>. Setting <code>ignore</code> allows to have several containers open. @property onblur @type string @default 'cancel' @since 1.1.1 **/ onblur: 'cancel', /** Animation speed (inline mode only) @property anim @type string @default false **/ anim: false, /** Mode of editable, can be `popup` or `inline` @property mode @type string @default 'popup' @since 1.4.0 **/ mode: 'popup' }; /* * workaround to have 'destroyed' event to destroy popover when element is destroyed * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom */ jQuery.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; }(window.jQuery)); /** * Editable Inline * --------------------- */ (function ($) { "use strict"; //copy prototype from EditableContainer //extend methods $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, { containerName: 'editableform', innerCss: '.editable-inline', containerClass: 'editable-container editable-inline', //css class applied to container element initContainer: function(){ //container is <span> element this.$tip = $('<span></span>'); //convert anim to miliseconds (int) if(!this.options.anim) { this.options.anim = 0; } }, splitOptions: function() { //all options are passed to form this.containerOptions = {}; this.formOptions = this.options; }, tip: function() { return this.$tip; }, innerShow: function () { this.$element.hide(); this.tip().insertAfter(this.$element).show(); }, innerHide: function () { this.$tip.hide(this.options.anim, $.proxy(function() { this.$element.show(); this.innerDestroy(); }, this)); }, innerDestroy: function() { if(this.tip()) { this.tip().empty().remove(); } } }); }(window.jQuery)); /** Makes editable any HTML element on the page. Applied as jQuery method. @class editable @uses editableContainer **/ (function ($) { "use strict"; var Editable = function (element, options) { this.$element = $(element); //data-* has more priority over js options: because dynamically created elements may change data-* this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element)); if(this.options.selector) { this.initLive(); } else { this.init(); } //check for transition support if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) { this.options.highlight = false; } }; Editable.prototype = { constructor: Editable, init: function () { var isValueByText = false, doAutotext, finalize; //name this.options.name = this.options.name || this.$element.attr('id'); //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select) //also we set scope option to have access to element inside input specific callbacks (e. g. source as function) this.options.scope = this.$element[0]; this.input = $.fn.editableutils.createInput(this.options); if(!this.input) { return; } //set value from settings or by element's text if (this.options.value === undefined || this.options.value === null) { this.value = this.input.html2value($.trim(this.$element.html())); isValueByText = true; } else { /* value can be string when received from 'data-value' attribute for complext objects value can be set as json string in data-value attribute, e.g. data-value="{city: 'Moscow', street: 'Lenina'}" */ this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); if(typeof this.options.value === 'string') { this.value = this.input.str2value(this.options.value); } else { this.value = this.options.value; } } //add 'editable' class to every editable element this.$element.addClass('editable'); //attach handler activating editable. In disabled mode it just prevent default action (useful for links) if(this.options.toggle !== 'manual') { this.$element.addClass('editable-click'); this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){ //prevent following link if editable enabled if(!this.options.disabled) { e.preventDefault(); } //stop propagation not required because in document click handler it checks event target //e.stopPropagation(); if(this.options.toggle === 'mouseenter') { //for hover only show container this.show(); } else { //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener var closeAll = (this.options.toggle !== 'click'); this.toggle(closeAll); } }, this)); } else { this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually } //if display is function it's far more convinient to have autotext = always to render correctly on init //see https://github.com/vitalets/x-editable-yii/issues/34 if(typeof this.options.display === 'function') { this.options.autotext = 'always'; } //check conditions for autotext: switch(this.options.autotext) { case 'always': doAutotext = true; break; case 'auto': //if element text is empty and value is defined and value not generated by text --> run autotext doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText; break; default: doAutotext = false; } //depending on autotext run render() or just finilize init $.when(doAutotext ? this.render() : true).then($.proxy(function() { if(this.options.disabled) { this.disable(); } else { this.enable(); } /** Fired when element was initialized by `$().editable()` method. Please note that you should setup `init` handler **before** applying `editable`. @event init @param {Object} event event object @param {Object} editable editable instance (as here it cannot accessed via data('editable')) @since 1.2.0 @example $('#username').on('init', function(e, editable) { alert('initialized ' + editable.options.name); }); $('#username').editable(); **/ this.$element.triggerHandler('init', this); }, this)); }, /* Initializes parent element for live editables */ initLive: function() { //store selector var selector = this.options.selector; //modify options for child elements this.options.selector = false; this.options.autotext = 'never'; //listen toggle events this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){ var $target = $(e.target); if(!$target.data('editable')) { //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user) //see https://github.com/vitalets/x-editable/issues/137 if($target.hasClass(this.options.emptyclass)) { $target.empty(); } $target.editable(this.options).trigger(e); } }, this)); }, /* Renders value into element's text. Can call custom display method from options. Can return deferred object. @method render() @param {mixed} response server response (if exist) to pass into display function */ render: function(response) { //do not display anything if(this.options.display === false) { return; } //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded if(this.input.value2htmlFinal) { return this.input.value2html(this.value, this.$element[0], this.options.display, response); //if display method defined --> use it } else if(typeof this.options.display === 'function') { return this.options.display.call(this.$element[0], this.value, response); //else use input's original value2html() method } else { return this.input.value2html(this.value, this.$element[0]); } }, /** Enables editable @method enable() **/ enable: function() { this.options.disabled = false; this.$element.removeClass('editable-disabled'); this.handleEmpty(this.isEmpty); if(this.options.toggle !== 'manual') { if(this.$element.attr('tabindex') === '-1') { this.$element.removeAttr('tabindex'); } } }, /** Disables editable @method disable() **/ disable: function() { this.options.disabled = true; this.hide(); this.$element.addClass('editable-disabled'); this.handleEmpty(this.isEmpty); //do not stop focus on this element this.$element.attr('tabindex', -1); }, /** Toggles enabled / disabled state of editable element @method toggleDisabled() **/ toggleDisabled: function() { if(this.options.disabled) { this.enable(); } else { this.disable(); } }, /** Sets new option @method option(key, value) @param {string|object} key option name or object with several options @param {mixed} value option new value @example $('.editable').editable('option', 'pk', 2); **/ option: function(key, value) { //set option(s) by object if(key && typeof key === 'object') { $.each(key, $.proxy(function(k, v){ this.option($.trim(k), v); }, this)); return; } //set option by string this.options[key] = value; //disabled if(key === 'disabled') { return value ? this.disable() : this.enable(); } //value if(key === 'value') { this.setValue(value); } //transfer new option to container! if(this.container) { this.container.option(key, value); } //pass option to input directly (as it points to the same in form) if(this.input.option) { this.input.option(key, value); } }, /* * set emptytext if element is empty */ handleEmpty: function (isEmpty) { //do not handle empty if we do not display anything if(this.options.display === false) { return; } /* isEmpty may be set directly as param of method. It is required when we enable/disable field and can't rely on content as node content is text: "Empty" that is not empty %) */ if(isEmpty !== undefined) { this.isEmpty = isEmpty; } else { //detect empty if($.trim(this.$element.html()) === '') { this.isEmpty = true; } else if($.trim(this.$element.text()) !== '') { this.isEmpty = false; } else { //e.g. '<img>' this.isEmpty = !this.$element.height() || !this.$element.width(); } } //emptytext shown only for enabled if(!this.options.disabled) { if (this.isEmpty) { this.$element.html(this.options.emptytext); if(this.options.emptyclass) { this.$element.addClass(this.options.emptyclass); } } else if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } else { //below required if element disable property was changed if(this.isEmpty) { this.$element.empty(); if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } } }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ show: function (closeAll) { if(this.options.disabled) { return; } //init editableContainer: popover, tooltip, inline, etc.. if(!this.container) { var containerOptions = $.extend({}, this.options, { value: this.value, input: this.input //pass input to form (as it is already created) }); this.$element.editableContainer(containerOptions); //listen `save` event this.$element.on("save.internal", $.proxy(this.save, this)); this.container = this.$element.data('editableContainer'); } else if(this.container.tip().is(':visible')) { return; } //show container this.container.show(closeAll); }, /** Hides container with form @method hide() **/ hide: function () { if(this.container) { this.container.hide(); } }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container && this.container.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* * called when form was submitted */ save: function(e, params) { //mark element with unsaved class if needed if(this.options.unsavedclass) { /* Add unsaved css to element if: - url is not user's function - value was not sent to server - params.response === undefined, that means data was not sent - value changed */ var sent = false; sent = sent || typeof this.options.url === 'function'; sent = sent || this.options.display === false; sent = sent || params.response !== undefined; sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); if(sent) { this.$element.removeClass(this.options.unsavedclass); } else { this.$element.addClass(this.options.unsavedclass); } } //highlight when saving if(this.options.highlight) { var $e = this.$element, $bgColor = $e.css('background-color'); $e.css('background-color', this.options.highlight); setTimeout(function(){ $e.css('background-color', $bgColor); $e.addClass('editable-bg-transition'); setTimeout(function(){ $e.removeClass('editable-bg-transition'); }, 1700); }, 0); } //set new value this.setValue(params.newValue, false, params.response); /** Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { alert('Saved value: ' + params.newValue); }); **/ //event itself is triggered by editableContainer. Description here is only for documentation }, validate: function () { if (typeof this.options.validate === 'function') { return this.options.validate.call(this, this.value); } }, /** Sets new value of editable @method setValue(value, convertStr) @param {mixed} value new value @param {boolean} convertStr whether to convert value from string to internal format **/ setValue: function(value, convertStr, response) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } if(this.container) { this.container.option('value', this.value); } $.when(this.render(response)) .then($.proxy(function() { this.handleEmpty(); }, this)); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.container) { this.container.activate(); } }, /** Removes editable feature from element @method destroy() **/ destroy: function() { this.disable(); if(this.container) { this.container.destroy(); } this.input.destroy(); if(this.options.toggle !== 'manual') { this.$element.removeClass('editable-click'); this.$element.off(this.options.toggle + '.editable'); } this.$element.off("save.internal"); this.$element.removeClass('editable editable-open editable-disabled'); this.$element.removeData('editable'); } }; /* EDITABLE PLUGIN DEFINITION * ======================= */ /** jQuery method to initialize editable element. @method $().editable(options) @params {Object} options @example $('#username').editable({ type: 'text', url: '/post', pk: 1 }); **/ $.fn.editable = function (option) { //special API methods returning non-jquery object var result = {}, args = arguments, datakey = 'editable'; switch (option) { /** Runs client-side validation for all matched editables @method validate() @returns {Object} validation errors map @example $('#username, #fullname').editable('validate'); // possible result: { username: "username is required", fullname: "fullname should be minimum 3 letters length" } **/ case 'validate': this.each(function () { var $this = $(this), data = $this.data(datakey), error; if (data && (error = data.validate())) { result[data.options.name] = error; } }); return result; /** Returns current values of editable elements. Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements. If value of some editable is `null` or `undefined` it is excluded from result object. When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object. @method getValue() @param {bool} isSingle whether to return just value of single element @returns {Object} object of element names and values @example $('#username, #fullname').editable('getValue'); //result: { username: "superuser", fullname: "John" } //isSingle = true $('#username').editable('getValue', true); //result "superuser" **/ case 'getValue': if(arguments.length === 2 && arguments[1] === true) { //isSingle = true result = this.eq(0).data(datakey).value; } else { this.each(function () { var $this = $(this), data = $this.data(datakey); if (data && data.value !== undefined && data.value !== null) { result[data.options.name] = data.input.value2submit(data.value); } }); } return result; /** This method collects values from several editable elements and submit them all to server. Internally it runs client-side validation for all fields and submits only in case of success. See <a href="#newrecord">creating new records</a> for details. @method submit(options) @param {object} options @param {object} options.url url to submit data @param {object} options.data additional data to submit @param {object} options.ajaxOptions additional ajax options @param {function} options.error(obj) error handler @param {function} options.success(obj,config) success handler @returns {Object} jQuery object **/ case 'submit': //collects value, validate and submit to server for creating new record var config = arguments[1] || {}, $elems = this, errors = this.editable('validate'), values; if($.isEmptyObject(errors)) { values = this.editable('getValue'); if(config.data) { $.extend(values, config.data); } $.ajax($.extend({ url: config.url, data: values, type: 'POST' }, config.ajaxOptions)) .success(function(response) { //successful response 200 OK if(typeof config.success === 'function') { config.success.call($elems, response, config); } }) .error(function(){ //ajax error if(typeof config.error === 'function') { config.error.apply($elems, arguments); } }); } else { //client-side validation error if(typeof config.error === 'function') { config.error.call($elems, errors); } } return this; } //return jquery object return this.each(function () { var $this = $(this), data = $this.data(datakey), options = typeof option === 'object' && option; if (!data) { $this.data(datakey, (data = new Editable(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; $.fn.editable.defaults = { /** Type of input. Can be <code>text|textarea|select|date|checklist</code> and more @property type @type string @default 'text' **/ type: 'text', /** Sets disabled state of editable @property disabled @type boolean @default false **/ disabled: false, /** How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>. When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable. **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document. @example $('#edit-button').click(function(e) { e.stopPropagation(); $('#username').editable('toggle'); }); @property toggle @type string @default 'click' **/ toggle: 'click', /** Text shown when element is empty. @property emptytext @type string @default 'Empty' **/ emptytext: 'Empty', /** Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date. For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>. <code>auto</code> - text will be automatically set only if element is empty. <code>always|never</code> - always(never) try to set element's text. @property autotext @type string @default 'auto' **/ autotext: 'auto', /** Initial value of input. If not set, taken from element's text. Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option). For example, to display currency sign: @example <a id="price" data-type="text" data-value="100"></a> <script> $('#price').editable({ ... display: function(value) { $(this).text(value + '$'); } }) </script> @property value @type mixed @default element's text **/ value: null, /** Callback to perform custom displaying of value in element's text. If `null`, default input's display used. If `false`, no displaying methods will be called, element's text will never change. Runs under element's scope. _**Parameters:**_ * `value` current value to be displayed * `response` server response (if display called after ajax submit), since 1.4.0 For _inputs with source_ (select, checklist) parameters are different: * `value` current value to be displayed * `sourceData` array of items for current input (e.g. dropdown items) * `response` server response (if display called after ajax submit), since 1.4.0 To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`. @property display @type function|boolean @default null @since 1.2.0 @example display: function(value, sourceData) { //display checklist as comma-separated values var html = [], checked = $.fn.editableutils.itemsByValue(value, sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(this).html(html.join(', ')); } else { $(this).empty(); } } **/ display: null, /** Css class applied when editable text is empty. @property emptyclass @type string @since 1.4.1 @default editable-empty **/ emptyclass: 'editable-empty', /** Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). You may set it to `null` if you work with editables locally and submit them together. @property unsavedclass @type string @since 1.4.1 @default editable-unsaved **/ unsavedclass: 'editable-unsaved', /** If selector is provided, editable will be delegated to the specified targets. Usefull for dynamically generated DOM elements. **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, as they actually become editable only after first click. You should manually set class `editable-click` to these elements. Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element: @property selector @type string @since 1.4.1 @default null @example <div id="user"> <!-- empty --> <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a> <!-- non-empty --> <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a> </div> <script> $('#user').editable({ selector: 'a', url: '/post', pk: 1 }); </script> **/ selector: null, /** Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers. @property highlight @type string|boolean @since 1.4.5 @default #FFFF80 **/ highlight: '#FFFF80' }; }(window.jQuery)); /** AbstractInput - base class for all editable inputs. It defines interface to be implemented by any input type. To create your own input you can inherit from this class. @class abstractinput **/ (function ($) { "use strict"; //types $.fn.editabletypes = {}; var AbstractInput = function () { }; AbstractInput.prototype = { /** Initializes input @method init() **/ init: function(type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); }, /* this method called before render to init $tpl that is inserted in DOM */ prerender: function() { this.$tpl = $(this.options.tpl); //whole tpl as jquery object this.$input = this.$tpl; //control itself, can be changed in render method this.$clear = null; //clear button this.error = null; //error message, if input cannot be rendered }, /** Renders input from tpl. Can return jQuery deferred object. Can be overwritten in child objects @method render() **/ render: function() { }, /** Sets element's html by value. @method value2html(value, element) @param {mixed} value @param {DOMElement} element **/ value2html: function(value, element) { $(element).text($.trim(value)); }, /** Converts element's html to value @method html2value(html) @param {string} html @returns {mixed} **/ html2value: function(html) { return $('<div>').html(html).text(); }, /** Converts value to string (for internal compare). For submitting to server used value2submit(). @method value2str(value) @param {mixed} value @returns {string} **/ value2str: function(value) { return value; }, /** Converts string received from server into value. Usually from `data-value` attribute. @method str2value(str) @param {string} str @returns {mixed} **/ str2value: function(str) { return str; }, /** Converts value for submitting to server. Result can be string or object. @method value2submit(value) @param {mixed} value @returns {mixed} **/ value2submit: function(value) { return value; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { this.$input.val(value); }, /** Returns value of input. Value can be object (e.g. datepicker) @method input2value() **/ input2value: function() { return this.$input.val(); }, /** Activates input. For text it sets focus. @method activate() **/ activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); } }, /** Creates input. @method clear() **/ clear: function() { this.$input.val(null); }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /** attach handler to automatically submit form when value changed (useful when buttons not shown) **/ autosubmit: function() { }, /** Additional actions when destroying element **/ destroy: function() { }, // -------- helper functions -------- setClass: function() { if(this.options.inputclass) { this.$input.addClass(this.options.inputclass); } }, setAttr: function(attr) { if (this.options[attr] !== undefined && this.options[attr] !== null) { this.$input.attr(attr, this.options[attr]); } }, option: function(key, value) { this.options[key] = value; } }; AbstractInput.defaults = { /** HTML template of input. Normally you should not change it. @property tpl @type string @default '' **/ tpl: '', /** CSS class automatically applied to input @property inputclass @type string @default input-medium **/ inputclass: 'input-medium', //scope for external methods (e.g. source defined as function) //for internal use only scope: null, //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults) showbuttons: true }; $.extend($.fn.editabletypes, {abstractinput: AbstractInput}); }(window.jQuery)); /** List - abstract class for inputs that have source option loaded from js array or via ajax @class list @extends abstractinput **/ (function ($) { "use strict"; var List = function (options) { }; $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput); $.extend(List.prototype, { render: function () { var deferred = $.Deferred(); this.error = null; this.onSourceReady(function () { this.renderList(); deferred.resolve(); }, function () { this.error = this.options.sourceError; deferred.resolve(); }); return deferred.promise(); }, html2value: function (html) { return null; //can't set value by text }, value2html: function (value, element, display, response) { var deferred = $.Deferred(), success = function () { if(typeof display === 'function') { //custom display method display.call(element, value, this.sourceData, response); } else { this.value2htmlFinal(value, element); } deferred.resolve(); }; //for null value just call success without loading source if(value === null) { success.call(this); } else { this.onSourceReady(success, function () { deferred.resolve(); }); } return deferred.promise(); }, // ------------- additional functions ------------ onSourceReady: function (success, error) { //run source if it function var source; if ($.isFunction(this.options.source)) { source = this.options.source.call(this.options.scope); this.sourceData = null; //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed } else { source = this.options.source; } //if allready loaded just call success if(this.options.sourceCache && $.isArray(this.sourceData)) { success.call(this); return; } //try parse json in single quotes (for double quotes jquery does automatically) try { source = $.fn.editableutils.tryParseJson(source, false); } catch (e) { error.call(this); return; } //loading from url if (typeof source === 'string') { //try to get sourceData from cache if(this.options.sourceCache) { var cacheID = source, cache; if (!$(document).data(cacheID)) { $(document).data(cacheID, {}); } cache = $(document).data(cacheID); //check for cached data if (cache.loading === false && cache.sourceData) { //take source from cache this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); return; } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later cache.callbacks.push($.proxy(function () { this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); }, this)); //also collecting error callbacks cache.err_callbacks.push($.proxy(error, this)); return; } else { //no cache yet, activate it cache.loading = true; cache.callbacks = []; cache.err_callbacks = []; } } //loading sourceData from server $.ajax({ url: source, type: 'get', cache: false, dataType: 'json', success: $.proxy(function (data) { if(cache) { cache.loading = false; } this.sourceData = this.makeArray(data); if($.isArray(this.sourceData)) { if(cache) { //store result in cache cache.sourceData = this.sourceData; //run success callbacks for other fields waiting for this source $.each(cache.callbacks, function () { this.call(); }); } this.doPrepend(); success.call(this); } else { error.call(this); if(cache) { //run error callbacks for other fields waiting for this source $.each(cache.err_callbacks, function () { this.call(); }); } } }, this), error: $.proxy(function () { error.call(this); if(cache) { cache.loading = false; //run error callbacks for other fields $.each(cache.err_callbacks, function () { this.call(); }); } }, this) }); } else { //options as json/array this.sourceData = this.makeArray(source); if($.isArray(this.sourceData)) { this.doPrepend(); success.call(this); } else { error.call(this); } } }, doPrepend: function () { if(this.options.prepend === null || this.options.prepend === undefined) { return; } if(!$.isArray(this.prependData)) { //run prepend if it is function (once) if ($.isFunction(this.options.prepend)) { this.options.prepend = this.options.prepend.call(this.options.scope); } //try parse json in single quotes this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true); //convert prepend from string to object if (typeof this.options.prepend === 'string') { this.options.prepend = {'': this.options.prepend}; } this.prependData = this.makeArray(this.options.prepend); } if($.isArray(this.prependData) && $.isArray(this.sourceData)) { this.sourceData = this.prependData.concat(this.sourceData); } }, /* renders input list */ renderList: function() { // this method should be overwritten in child class }, /* set element's html by value */ value2htmlFinal: function(value, element) { // this method should be overwritten in child class }, /** * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}] */ makeArray: function(data) { var count, obj, result = [], item, iterateItem; if(!data || typeof data === 'string') { return null; } if($.isArray(data)) { //array /* function to iterate inside item of array if item is object. Caclulates count of keys in item and store in obj. */ iterateItem = function (k, v) { obj = {value: k, text: v}; if(count++ >= 2) { return false;// exit from `each` if item has more than one key. } }; for(var i = 0; i < data.length; i++) { item = data[i]; if(typeof item === 'object') { count = 0; //count of keys inside item $.each(item, iterateItem); //case: [{val1: 'text1'}, {val2: 'text2} ...] if(count === 1) { result.push(obj); //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...] } else if(count > 1) { //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text') if(item.children) { item.children = this.makeArray(item.children); } result.push(item); } } else { //case: ['text1', 'text2' ...] result.push({value: item, text: item}); } } } else { //case: {val1: 'text1', val2: 'text2, ...} $.each(data, function (k, v) { result.push({value: k, text: v}); }); } return result; }, option: function(key, value) { this.options[key] = value; if(key === 'source') { this.sourceData = null; } if(key === 'prepend') { this.prependData = null; } } }); List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** Source data for list. If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]` For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order. If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option. If **function**, it should return data in format above (since 1.4.0). Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` @property source @type string | array | object | function @default null **/ source: null, /** Data automatically prepended to the beginning of dropdown list. @property prepend @type string | array | object | function @default false **/ prepend: false, /** Error message when list cannot be loaded (e.g. ajax error) @property sourceError @type string @default Error when loading list **/ sourceError: 'Error when loading list', /** if <code>true</code> and source is **string url** - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. @property sourceCache @type boolean @default true @since 1.2.0 **/ sourceCache: true }); $.fn.editabletypes.list = List; }(window.jQuery)); /** Text input @class text @extends abstractinput @final @example <a href="#" id="username" data-type="text" data-pk="1">awesome</a> <script> $(function(){ $('#username').editable({ url: '/post', title: 'Enter username' }); }); </script> **/ (function ($) { "use strict"; var Text = function (options) { this.init('text', options, Text.defaults); }; $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput); $.extend(Text.prototype, { render: function() { this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length); if(this.toggleClear) { this.toggleClear(); } } }, //render clear button renderClear: function() { if (this.options.clear) { this.$clear = $('<span class="editable-clear-x"></span>'); this.$input.after(this.$clear) .css('padding-right', 24) .keyup($.proxy(function(e) { //arrows, enter, tab, etc if(~$.inArray(e.keyCode, [40,38,9,13,27])) { return; } clearTimeout(this.t); var that = this; this.t = setTimeout(function() { that.toggleClear(e); }, 100); }, this)) .parent().css('position', 'relative'); this.$clear.click($.proxy(this.clear, this)); } }, postrender: function() { /* //now `clear` is positioned via css if(this.$clear) { //can position clear button only here, when form is shown and height can be calculated // var h = this.$input.outerHeight(true) || 20, var h = this.$clear.parent().height(), delta = (h - this.$clear.height()) / 2; //this.$clear.css({bottom: delta, right: delta}); } */ }, //show / hide clear button toggleClear: function(e) { if(!this.$clear) { return; } var len = this.$input.val().length, visible = this.$clear.is(':visible'); if(len && !visible) { this.$clear.show(); } if(!len && visible) { this.$clear.hide(); } }, clear: function() { this.$clear.hide(); this.$input.val('').focus(); } }); Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text">', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.text = Text; }(window.jQuery)); /** Textarea input @class textarea @extends abstractinput @final @example <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments', rows: 10 }); }); </script> **/ (function ($) { "use strict"; var Textarea = function (options) { this.init('textarea', options, Textarea.defaults); }; $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput); $.extend(Textarea.prototype, { render: function () { this.setClass(); this.setAttr('placeholder'); this.setAttr('rows'); //ctrl + enter this.$input.keydown(function (e) { if (e.ctrlKey && e.which === 13) { $(this).closest('form').submit(); } }); }, value2html: function(value, element) { var html = '', lines; if(value) { lines = value.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } html = lines.join('<br>'); } $(element).html(html); }, html2value: function(html) { if(!html) { return ''; } var regex = new RegExp(String.fromCharCode(10), 'g'); var lines = html.split(/<br\s*\/?>/i); for (var i = 0; i < lines.length; i++) { var text = $('<div>').html(lines[i]).text(); // Remove newline characters (\n) to avoid them being converted by value2html() method // thus adding extra <br> tags text = text.replace(regex, ''); lines[i] = text; } return lines.join("\n"); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); } }); Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default input-large **/ inputclass: 'input-large', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Number of rows in textarea @property rows @type integer @default 7 **/ rows: 7 }); $.fn.editabletypes.textarea = Textarea; }(window.jQuery)); /** Select (dropdown) @class select @extends list @final @example <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-original-title="Select status"></a> <script> $(function(){ $('#status').editable({ value: 2, source: [ {value: 1, text: 'Active'}, {value: 2, text: 'Blocked'}, {value: 3, text: 'Deleted'} ] }); }); </script> **/ (function ($) { "use strict"; var Select = function (options) { this.init('select', options, Select.defaults); }; $.fn.editableutils.inherit(Select, $.fn.editabletypes.list); $.extend(Select.prototype, { renderList: function() { this.$input.empty(); var fillItems = function($el, data) { if($.isArray(data)) { for(var i=0; i<data.length; i++) { if(data[i].children) { $el.append(fillItems($('<optgroup>', {label: data[i].text}), data[i].children)); } else { $el.append($('<option>', {value: data[i].value}).text(data[i].text)); } } } return $el; }; fillItems(this.$input, this.sourceData); this.setClass(); //enter submit this.$input.on('keydown.editable', function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); }, value2htmlFinal: function(value, element) { var text = '', items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length) { text = items[0].text; } $(element).text(text); }, autosubmit: function() { this.$input.off('keydown.editable').on('change.editable', function(){ $(this).closest('form').submit(); }); } }); Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <select></select> **/ tpl:'<select></select>' }); $.fn.editabletypes.select = Select; }(window.jQuery)); /** List of checkboxes. Internally value stored as javascript array of values. @class checklist @extends list @final @example <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-original-title="Select options"></a> <script> $(function(){ $('#options').editable({ value: [2, 3], source: [ {value: 1, text: 'option1'}, {value: 2, text: 'option2'}, {value: 3, text: 'option3'} ] }); }); </script> **/ (function ($) { "use strict"; var Checklist = function (options) { this.init('checklist', options, Checklist.defaults); }; $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list); $.extend(Checklist.prototype, { renderList: function() { var $label, $div; this.$tpl.empty(); if(!$.isArray(this.sourceData)) { return; } for(var i=0; i<this.sourceData.length; i++) { $label = $('<label>').append($('<input>', { type: 'checkbox', value: this.sourceData[i].value })) .append($('<span>').text(' '+this.sourceData[i].text)); $('<div>').append($label).appendTo(this.$tpl); } this.$input = this.$tpl.find('input[type="checkbox"]'); this.setClass(); }, value2str: function(value) { return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : ''; }, //parse separated string str2value: function(str) { var reg, value = null; if(typeof str === 'string' && str.length) { reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*'); value = str.split(reg); } else if($.isArray(str)) { value = str; } else { value = [str]; } return value; }, //set checked on required checkboxes value2input: function(value) { this.$input.prop('checked', false); if($.isArray(value) && value.length) { this.$input.each(function(i, el) { var $el = $(el); // cannot use $.inArray as it performs strict comparison $.each(value, function(j, val){ /*jslint eqeq: true*/ if($el.val() == val) { /*jslint eqeq: false*/ $el.prop('checked', true); } }); }); } }, input2value: function() { var checked = []; this.$input.filter(':checked').each(function(i, el) { checked.push($(el).val()); }); return checked; }, //collect text of checked boxes value2htmlFinal: function(value, element) { var html = [], checked = $.fn.editableutils.itemsByValue(value, this.sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(element).html(html.join('<br>')); } else { $(element).empty(); } }, activate: function() { this.$input.first().focus(); }, autosubmit: function() { this.$input.on('keydown', function(e){ if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-checklist"></div>', /** @property inputclass @type string @default null **/ inputclass: null, /** Separator of values when reading from `data-value` attribute @property separator @type string @default ',' **/ separator: ',' }); $.fn.editabletypes.checklist = Checklist; }(window.jQuery)); /** HTML5 input types. Following types are supported: * password * email * url * tel * number * range Learn more about html5 inputs: http://www.w3.org/wiki/HTML5_form_additions To check browser compatibility please see: https://developer.mozilla.org/en-US/docs/HTML/Element/Input @class html5types @extends text @final @since 1.3.0 @example <a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a> <script> $(function(){ $('#email').editable({ url: '/post', title: 'Enter email' }); }); </script> **/ /** @property tpl @default depends on type **/ /* Password */ (function ($) { "use strict"; var Password = function (options) { this.init('password', options, Password.defaults); }; $.fn.editableutils.inherit(Password, $.fn.editabletypes.text); $.extend(Password.prototype, { //do not display password, show '[hidden]' instead value2html: function(value, element) { if(value) { $(element).text('[hidden]'); } else { $(element).empty(); } }, //as password not displayed, should not set value by html html2value: function(html) { return null; } }); Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="password">' }); $.fn.editabletypes.password = Password; }(window.jQuery)); /* Email */ (function ($) { "use strict"; var Email = function (options) { this.init('email', options, Email.defaults); }; $.fn.editableutils.inherit(Email, $.fn.editabletypes.text); Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="email">' }); $.fn.editabletypes.email = Email; }(window.jQuery)); /* Url */ (function ($) { "use strict"; var Url = function (options) { this.init('url', options, Url.defaults); }; $.fn.editableutils.inherit(Url, $.fn.editabletypes.text); Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="url">' }); $.fn.editabletypes.url = Url; }(window.jQuery)); /* Tel */ (function ($) { "use strict"; var Tel = function (options) { this.init('tel', options, Tel.defaults); }; $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text); Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="tel">' }); $.fn.editabletypes.tel = Tel; }(window.jQuery)); /* Number */ (function ($) { "use strict"; var NumberInput = function (options) { this.init('number', options, NumberInput.defaults); }; $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text); $.extend(NumberInput.prototype, { render: function () { NumberInput.superclass.render.call(this); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); }, postrender: function() { if(this.$clear) { //increase right ffset for up/down arrows this.$clear.css({right: 24}); /* //can position clear button only here, when form is shown and height can be calculated var h = this.$input.outerHeight(true) || 20, delta = (h - this.$clear.height()) / 2; //add 12px to offset right for up/down arrows this.$clear.css({top: delta, right: delta + 16}); */ } } }); NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="number">', inputclass: 'input-mini', min: null, max: null, step: null }); $.fn.editabletypes.number = NumberInput; }(window.jQuery)); /* Range (inherit from number) */ (function ($) { "use strict"; var Range = function (options) { this.init('range', options, Range.defaults); }; $.fn.editableutils.inherit(Range, $.fn.editabletypes.number); $.extend(Range.prototype, { render: function () { this.$input = this.$tpl.filter('input'); this.setClass(); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); this.$input.on('input', function(){ $(this).siblings('output').text($(this).val()); }); }, activate: function() { this.$input.focus(); } }); Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, { tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>', inputclass: 'input-medium' }); $.fn.editabletypes.range = Range; }(window.jQuery)); /** Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2. Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options. Compatible **select2 version is 3.4.1**! You should manually download and include select2 distributive: <link href="select2/select2.css" rel="stylesheet" type="text/css"></link> <script src="select2/select2.js"></script> To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link> **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source. You need initially put both `data-value` and element's text youself: <a href="#" data-type="select2" data-value="1">Text1</a> @class select2 @extends abstractinput @since 1.4.1 @final @example <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a> <script> $(function(){ $('#country').editable({ source: [ {id: 'gb', text: 'Great Britain'}, {id: 'us', text: 'United States'}, {id: 'ru', text: 'Russia'} ], select2: { multiple: true } }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('select2', options, Constructor.defaults); options.select2 = options.select2 || {}; this.sourceData = null; //placeholder if(options.placeholder) { options.select2.placeholder = options.placeholder; } //if not `tags` mode, use source if(!options.select2.tags && options.source) { var source = options.source; //if source is function, call it (once!) if ($.isFunction(options.source)) { source = options.source.call(options.scope); } if (typeof source === 'string') { options.select2.ajax = options.select2.ajax || {}; //some default ajax params if(!options.select2.ajax.data) { options.select2.ajax.data = function(term) {return { query:term };}; } if(!options.select2.ajax.results) { options.select2.ajax.results = function(data) { return {results:data };}; } options.select2.ajax.url = source; } else { //check format and convert x-editable format to select2 format (if needed) this.sourceData = this.convertSource(source); options.select2.data = this.sourceData; } } //overriding objects in config (as by default jQuery extend() is not recursive) this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2); //detect whether it is multi-valued this.isMultiple = this.options.select2.tags || this.options.select2.multiple; this.isRemote = ('ajax' in this.options.select2); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function() { this.setClass(); //apply select2 this.$input.select2(this.options.select2); //when data is loaded via ajax, we need to know when it's done to populate listData if(this.isRemote) { //listen to loaded event to populate data this.$input.on('select2-loaded', $.proxy(function(e) { this.sourceData = e.items.results; }, this)); } //trigger resize of editableform to re-position container in multi-valued mode if(this.isMultiple) { this.$input.on('change', function() { $(this).closest('form').parent().triggerHandler('resize'); }); } }, value2html: function(value, element) { var text = '', data; if(this.options.select2.tags) { //in tags mode just assign value data = value; } else if(this.sourceData) { data = $.fn.editableutils.itemsByValue(value, this.sourceData, 'id'); } else { //can not get list of possible values (e.g. autotext for select2 with ajax source) } //data may be array (when multiple values allowed) if($.isArray(data)) { //collect selected data and show with separator text = []; $.each(data, function(k, v){ text.push(v && typeof v === 'object' ? v.text : v); }); } else if(data) { text = data.text; } text = $.isArray(text) ? text.join(this.options.viewseparator) : text; $(element).text(text); }, html2value: function(html) { return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null; }, value2input: function(value) { //for remote source .val() is not working, need to look in sourceData if(this.isRemote) { //todo: check value for array var item, items; //if sourceData loaded, use it to get text for display if(this.sourceData) { items = $.fn.editableutils.itemsByValue(value, this.sourceData, 'id'); if(items.length) { item = items[0]; } } //if item not found by sourceData, use element text (e.g. for the first show) if(!item) { item = {id: value, text: $(this.options.scope).text()}; } //select2('data', ...) allows to set both id and text --> usefull for initial show when items are not loaded this.$input.select2('data', item).trigger('change', true); //second argument needed to separate initial change from user's click (for autosubmit) } else { this.$input.val(value).trigger('change', true); //second argument needed to separate initial change from user's click (for autosubmit) } }, input2value: function() { return this.$input.select2('val'); }, str2value: function(str, separator) { if(typeof str !== 'string' || !this.isMultiple) { return str; } separator = separator || this.options.select2.separator || $.fn.select2.defaults.separator; var val, i, l; if (str === null || str.length < 1) { return null; } val = str.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) { val[i] = $.trim(val[i]); } return val; }, autosubmit: function() { this.$input.on('change', function(e, isInitial){ if(!isInitial) { $(this).closest('form').submit(); } }); }, /* Converts source from x-editable format: {value: 1, text: "1"} to select2 format: {id: 1, text: "1"} */ convertSource: function(source) { if($.isArray(source) && source.length && source[0].value !== undefined) { for(var i = 0; i<source.length; i++) { if(source[i].value !== undefined) { source[i].id = source[i].value; delete source[i].value; } } } return source; } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="hidden"> **/ tpl:'<input type="hidden">', /** Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2). @property select2 @type object @default null **/ select2: null, /** Placeholder attribute of select @property placeholder @type string @default null **/ placeholder: null, /** Source data for select. It will be assigned to select2 `data` property and kept here just for convenience. Please note, that format is different from simple `select` input: use 'id' instead of 'value'. E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`. @property source @type array @default null **/ source: null, /** Separator used to display tags. @property viewseparator @type string @default ', ' **/ viewseparator: ', ' }); $.fn.editabletypes.select2 = Constructor; }(window.jQuery)); /** * Combodate - 1.0.4 * Dropdown date and time picker. * Converts text input into dropdowns to pick day, month, year, hour, minute and second. * Uses momentjs as datetime library http://momentjs.com. * For i18n include corresponding file from https://github.com/timrwood/moment/tree/master/lang * * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight * In combodate: * 12:00 pm --> 12:00 (24-h format, midday) * 12:00 am --> 00:00 (24-h format, midnight, start of day) * * Differs from momentjs parse rules: * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change) * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change) * * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/combodate * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Combodate = function (element, options) { this.$element = $(element); if(!this.$element.is('input')) { $.error('Combodate should be applied to INPUT element'); return; } this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data()); this.init(); }; Combodate.prototype = { constructor: Combodate, init: function () { this.map = { //key regexp moment.method day: ['D', 'date'], month: ['M', 'month'], year: ['Y', 'year'], hour: ['[Hh]', 'hours'], minute: ['m', 'minutes'], second: ['s', 'seconds'], ampm: ['[Aa]', ''] }; this.$widget = $('<span class="combodate"></span>').html(this.getTemplate()); this.initCombos(); //update original input on change this.$widget.on('change', 'select', $.proxy(function(){ this.$element.val(this.getValue()); }, this)); this.$widget.find('select').css('width', 'auto'); //hide original input and insert widget this.$element.hide().after(this.$widget); //set initial value this.setValue(this.$element.val() || this.options.value); }, /* Replace tokens in template with <select> elements */ getTemplate: function() { var tpl = this.options.template; //first pass $.each(this.map, function(k, v) { v = v[0]; var r = new RegExp(v+'+'), token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace(r, '{'+token+'}'); }); //replace spaces with &nbsp; tpl = tpl.replace(/ /g, '&nbsp;'); //second pass $.each(this.map, function(k, v) { v = v[0]; var token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>'); }); return tpl; }, /* Initialize combos that presents in template */ initCombos: function() { var that = this; $.each(this.map, function(k, v) { var $c = that.$widget.find('.'+k), f, items; if($c.length) { that['$'+k] = $c; //set properties like this.$day, this.$month etc. f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); //define method name to fill items, e.g `fillDays` items = that[f](); that['$'+k].html(that.renderItems(items)); } }); }, /* Initialize items of combos. Handles `firstItem` option */ initItems: function(key) { var values = [], relTime; if(this.options.firstItem === 'name') { //need both to support moment ver < 2 and >= 2 relTime = moment.relativeTime || moment.langData()._relativeTime; var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key]; //take last entry (see momentjs lang files structure) header = header.split(' ').reverse()[0]; values.push(['', header]); } else if(this.options.firstItem === 'empty') { values.push(['', '']); } return values; }, /* render items to string of <option> tags */ renderItems: function(items) { var str = []; for(var i=0; i<items.length; i++) { str.push('<option value="'+items[i][0]+'">'+items[i][1]+'</option>'); } return str.join("\n"); }, /* fill day */ fillDay: function() { var items = this.initItems('d'), name, i, twoDigit = this.options.template.indexOf('DD') !== -1; for(i=1; i<=31; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill month */ fillMonth: function() { var items = this.initItems('M'), name, i, longNames = this.options.template.indexOf('MMMM') !== -1, shortNames = this.options.template.indexOf('MMM') !== -1, twoDigit = this.options.template.indexOf('MM') !== -1; for(i=0; i<=11; i++) { if(longNames) { //see https://github.com/timrwood/momentjs.com/pull/36 name = moment().date(1).month(i).format('MMMM'); } else if(shortNames) { name = moment().date(1).month(i).format('MMM'); } else if(twoDigit) { name = this.leadZero(i+1); } else { name = i+1; } items.push([i, name]); } return items; }, /* fill year */ fillYear: function() { var items = [], name, i, longNames = this.options.template.indexOf('YYYY') !== -1; for(i=this.options.maxYear; i>=this.options.minYear; i--) { name = longNames ? i : (i+'').substring(2); items[this.options.yearDescending ? 'push' : 'unshift']([i, name]); } items = this.initItems('y').concat(items); return items; }, /* fill hour */ fillHour: function() { var items = this.initItems('h'), name, i, h12 = this.options.template.indexOf('h') !== -1, h24 = this.options.template.indexOf('H') !== -1, twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1, min = h12 ? 1 : 0, max = h12 ? 12 : 23; for(i=min; i<=max; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill minute */ fillMinute: function() { var items = this.initItems('m'), name, i, twoDigit = this.options.template.indexOf('mm') !== -1; for(i=0; i<=59; i+= this.options.minuteStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill second */ fillSecond: function() { var items = this.initItems('s'), name, i, twoDigit = this.options.template.indexOf('ss') !== -1; for(i=0; i<=59; i+= this.options.secondStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill ampm */ fillAmpm: function() { var ampmL = this.options.template.indexOf('a') !== -1, ampmU = this.options.template.indexOf('A') !== -1, items = [ ['am', ampmL ? 'am' : 'AM'], ['pm', ampmL ? 'pm' : 'PM'] ]; return items; }, /* Returns current date value from combos. If format not specified - `options.format` used. If format = `null` - Moment object returned. */ getValue: function(format) { var dt, values = {}, that = this, notSelected = false; //getting selected values $.each(this.map, function(k, v) { if(k === 'ampm') { return; } var def = k === 'day' ? 1 : 0; values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; if(isNaN(values[k])) { notSelected = true; return false; } }); //if at least one visible combo not selected - return empty string if(notSelected) { return ''; } //convert hours 12h --> 24h if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour === 12) { values.hour = this.$ampm.val() === 'am' ? 0 : 12; } else { values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12; } } dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]); //highlight invalid date this.highlight(dt); format = format === undefined ? this.options.format : format; if(format === null) { return dt.isValid() ? dt : null; } else { return dt.isValid() ? dt.format(format) : ''; } }, setValue: function(value) { if(!value) { return; } var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value), that = this, values = {}; //function to find nearest value in select options function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; } if(dt.isValid()) { //read values from date object $.each(this.map, function(k, v) { if(k === 'ampm') { return; } values[k] = dt[v[1]](); }); if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour >= 12) { values.ampm = 'pm'; if(values.hour > 12) { values.hour -= 12; } } else { values.ampm = 'am'; if(values.hour === 0) { values.hour = 12; } } } $.each(values, function(k, v) { //call val() for each existing combo, e.g. this.$hour.val() if(that['$'+k]) { if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } that['$'+k].val(v); } }); this.$element.val(dt.format(this.options.format)); } }, /* highlight combos if date is invalid */ highlight: function(dt) { if(!dt.isValid()) { if(this.options.errorClass) { this.$widget.addClass(this.options.errorClass); } else { //store original border color if(!this.borderColor) { this.borderColor = this.$widget.find('select').css('border-color'); } this.$widget.find('select').css('border-color', 'red'); } } else { if(this.options.errorClass) { this.$widget.removeClass(this.options.errorClass); } else { this.$widget.find('select').css('border-color', this.borderColor); } } }, leadZero: function(v) { return v <= 9 ? '0' + v : v; }, destroy: function() { this.$widget.remove(); this.$element.removeData('combodate').show(); } //todo: clear method }; $.fn.combodate = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getValue returns date as string / object (not jQuery object) if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) { return d.getValue.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('combodate'), options = typeof option == 'object' && option; if (!data) { $this.data('combodate', (data = new Combodate(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.combodate.defaults = { //in this format value stored in original input format: 'DD-MM-YYYY HH:mm', //in this format items in dropdowns are displayed template: 'D / MMM / YYYY H : mm', //initial value, can be `new Date()` value: null, minYear: 1970, maxYear: 2015, yearDescending: true, minuteStep: 5, secondStep: 1, firstItem: 'empty', //'name', 'empty', 'none' errorClass: null, roundTime: true //whether to round minutes and seconds if step > 1 }; }(window.jQuery)); /** Combodate input - dropdown date and time picker. Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com). <script src="js/moment.min.js"></script> Allows to input: * only date * only time * both date and time Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker. Internally value stored as `momentjs` object. @class combodate @extends abstractinput @final @since 1.4.0 @example <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-original-title="Select date"></a> <script> $(function(){ $('#dob').editable({ format: 'YYYY-MM-DD', viewformat: 'DD.MM.YYYY', template: 'D / MMMM / YYYY', combodate: { minYear: 2000, maxYear: 2015, minuteStep: 1 } } }); }); </script> **/ /*global moment*/ (function ($) { "use strict"; var Constructor = function (options) { this.init('combodate', options, Constructor.defaults); //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse combodate config defined as json string in data-combodate options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true); //overriding combodate config (as by default jQuery extend() is not recursive) this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, { format: this.options.format, template: this.options.template }); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function () { this.$input.combodate(this.options.combodate); //"clear" link /* if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } */ }, value2html: function(value, element) { var text = value ? value.format(this.options.viewformat) : ''; $(element).text(text); }, html2value: function(html) { return html ? moment(html, this.options.viewformat) : null; }, value2str: function(value) { return value ? value.format(this.options.format) : ''; }, str2value: function(str) { return str ? moment(str, this.options.format) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.combodate('setValue', value); }, input2value: function() { return this.$input.combodate('getValue', null); }, activate: function() { this.$input.siblings('.combodate').find('select').eq(0).focus(); }, /* clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); }, */ autosubmit: function() { } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format) @property format @type string @default YYYY-MM-DD **/ format:'YYYY-MM-DD', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to `format`. @property viewformat @type string @default null **/ viewformat: null, /** Template used for displaying dropdowns. @property template @type string @default D / MMM / YYYY **/ template: 'D / MMM / YYYY', /** Configuration of combodate. Full list of options: http://vitalets.github.com/combodate/#docs @property combodate @type object @default null **/ combodate: null /* (not implemented yet) Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' */ //clear: '&times; clear' }); $.fn.editabletypes.combodate = Constructor; }(window.jQuery)); /* Editableform based on Twitter Bootstrap */ (function ($) { "use strict"; $.extend($.fn.editableform.Constructor.prototype, { initTemplate: function() { this.$form = $($.fn.editableform.template); this.$form.find('.editable-error-block').addClass('help-block'); } }); //buttons $.fn.editableform.buttons = '<button type="submit" class="btn btn-primary editable-submit"><i class="icon-ok icon-white"></i></button>'+ '<button type="button" class="btn editable-cancel"><i class="icon-remove"></i></button>'; //error classes $.fn.editableform.errorGroupClass = 'error'; $.fn.editableform.errorBlockClass = null; }(window.jQuery)); /** * Editable Popover * --------------------- * requires bootstrap-popover.js */ (function ($) { "use strict"; //extend methods $.extend($.fn.editableContainer.Popup.prototype, { containerName: 'popover', //for compatibility with bootstrap <= 2.2.1 (content inserted into <p> instead of directly .popover-content) innerCss: $.fn.popover && $($.fn.popover.defaults.template).find('p').length ? '.popover-content p' : '.popover-content', initContainer: function(){ $.extend(this.containerOptions, { trigger: 'manual', selector: false, content: ' ', template: $.fn.popover.defaults.template }); //as template property is used in inputs, hide it from popover var t; if(this.$element.data('template')) { t = this.$element.data('template'); this.$element.removeData('template'); } this.call(this.containerOptions); if(t) { //restore data('template') this.$element.data('template', t); } }, /* show */ innerShow: function () { this.call('show'); }, /* hide */ innerHide: function () { this.call('hide'); }, /* destroy */ innerDestroy: function() { this.call('destroy'); }, setContainerOption: function(key, value) { this.container().options[key] = value; }, /** * move popover to new position. This function mainly copied from bootstrap-popover. */ /*jshint laxcomma: true*/ setPosition: function () { (function() { var $tip = this.tip() , inside , pos , actualWidth , actualHeight , placement , tp; placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; inside = /in/.test(placement); $tip // .detach() //vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover .removeClass('top right bottom left') .css({ top: 0, left: 0, display: 'block' }); // .insertAfter(this.$element); pos = this.getPosition(inside); actualWidth = $tip[0].offsetWidth; actualHeight = $tip[0].offsetHeight; switch (inside ? placement.split(' ')[1] : placement) { case 'bottom': tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 'top': tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}; break; case 'left': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}; break; case 'right': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}; break; } $tip .offset(tp) .addClass(placement) .addClass('in'); }).call(this.container()); /*jshint laxcomma: false*/ } }); }(window.jQuery)); /* ========================================================= * bootstrap-datepicker.js * http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ========================================================= */ (function( $ ) { function UTCDate(){ return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday(){ var today = new Date(); return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); } // Picker object var Datepicker = function(element, options) { var that = this; this._process_options(options); this.element = $(element); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false; this.hasInput = this.component && this.element.find('input').length; if(this.component && this.component.length === 0) this.component = false; this.picker = $(DPGlobal.template); this._buildEvents(); this._attachEvents(); if(this.isInline) { this.picker.addClass('datepicker-inline').appendTo(this.element); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.o.rtl){ this.picker.addClass('datepicker-rtl'); this.picker.find('.prev i, .next i') .toggleClass('icon-arrow-left icon-arrow-right'); } this.viewMode = this.o.startView; if (this.o.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function(i, val){ return parseInt(val) + 1; }); this._allow_update = false; this.setStartDate(this.o.startDate); this.setEndDate(this.o.endDate); this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled); this.fillDow(); this.fillMonths(); this._allow_update = true; this.update(); this.showMode(); if(this.isInline) { this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _process_options: function(opts){ // Store raw options for reference this._o = $.extend({}, this._o, opts); // Processed options var o = this.o = $.extend({}, this._o); // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" var lang = o.language; if (!dates[lang]) { lang = lang.split('-')[0]; if (!dates[lang]) lang = defaults.language; } o.language = lang; switch(o.startView){ case 2: case 'decade': o.startView = 2; break; case 1: case 'year': o.startView = 1; break; default: o.startView = 0; } switch (o.minViewMode) { case 1: case 'months': o.minViewMode = 1; break; case 2: case 'years': o.minViewMode = 2; break; default: o.minViewMode = 0; } o.startView = Math.max(o.startView, o.minViewMode); o.weekStart %= 7; o.weekEnd = ((o.weekStart + 6) % 7); var format = DPGlobal.parseFormat(o.format) if (o.startDate !== -Infinity) { o.startDate = DPGlobal.parseDate(o.startDate, format, o.language); } if (o.endDate !== Infinity) { o.endDate = DPGlobal.parseDate(o.endDate, format, o.language); } o.daysOfWeekDisabled = o.daysOfWeekDisabled||[]; if (!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/); o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) { return parseInt(d, 10); }); }, _events: [], _secondaryEvents: [], _applyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.on(ev); } }, _unapplyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.off(ev); } }, _buildEvents: function(){ if (this.isInput) { // single input this._events = [ [this.element, { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }] ]; } else if (this.component && this.hasInput){ // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')) { // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } this._secondaryEvents = [ [this.picker, { click: $.proxy(this.click, this) }], [$(window), { resize: $.proxy(this.place, this) }], [$(document), { mousedown: $.proxy(function (e) { // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || this.element.find(e.target).size() || this.picker.is(e.target) || this.picker.find(e.target).size() )) { this.hide(); } }, this) }] ]; }, _attachEvents: function(){ this._detachEvents(); this._applyEvents(this._events); }, _detachEvents: function(){ this._unapplyEvents(this._events); }, _attachSecondaryEvents: function(){ this._detachSecondaryEvents(); this._applyEvents(this._secondaryEvents); }, _detachSecondaryEvents: function(){ this._unapplyEvents(this._secondaryEvents); }, _trigger: function(event, altdate){ var date = altdate || this.date, local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000)); this.element.trigger({ type: event, date: local_date, format: $.proxy(function(altformat){ var format = altformat || this.o.format; return DPGlobal.formatDate(date, format, this.o.language); }, this) }); }, show: function(e) { if (!this.isInline) this.picker.appendTo('body'); this.picker.show(); this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); this.place(); this._attachSecondaryEvents(); if (e) { e.preventDefault(); } this._trigger('show'); }, hide: function(e){ if(this.isInline) return; if (!this.picker.is(':visible')) return; this.picker.hide().detach(); this._detachSecondaryEvents(); this.viewMode = this.o.startView; this.showMode(); if ( this.o.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this._trigger('hide'); }, remove: function() { this.hide(); this._detachEvents(); this._detachSecondaryEvents(); this.picker.remove(); delete this.element.data().datepicker; if (!this.isInput) { delete this.element.data().date; } }, getDate: function() { var d = this.getUTCDate(); return new Date(d.getTime() + (d.getTimezoneOffset()*60000)); }, getUTCDate: function() { return this.date; }, setDate: function(d) { this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000))); }, setUTCDate: function(d) { this.date = d; this.setValue(); }, setValue: function() { var formatted = this.getFormattedDate(); if (!this.isInput) { if (this.component){ this.element.find('input').val(formatted); } } else { this.element.val(formatted); } }, getFormattedDate: function(format) { if (format === undefined) format = this.o.format; return DPGlobal.formatDate(this.date, format, this.o.language); }, setStartDate: function(startDate){ this._process_options({startDate: startDate}); this.update(); this.updateNavArrows(); }, setEndDate: function(endDate){ this._process_options({endDate: endDate}); this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function(daysOfWeekDisabled){ this._process_options({daysOfWeekDisabled: daysOfWeekDisabled}); this.update(); this.updateNavArrows(); }, place: function(){ if(this.isInline) return; var zIndex = parseInt(this.element.parents().filter(function() { return $(this).css('z-index') != 'auto'; }).first().css('z-index'))+10; var offset = this.component ? this.component.parent().offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true); this.picker.css({ top: offset.top + height, left: offset.left, zIndex: zIndex }); }, _allow_update: true, update: function(){ if (!this._allow_update) return; var date, fromArgs = false; if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) { date = arguments[0]; fromArgs = true; } else { date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); delete this.element.data().date; } this.date = DPGlobal.parseDate(date, this.o.format, this.o.language); if(fromArgs) this.setValue(); if (this.date < this.o.startDate) { this.viewDate = new Date(this.o.startDate); } else if (this.date > this.o.endDate) { this.viewDate = new Date(this.o.endDate); } else { this.viewDate = new Date(this.date); } this.fill(); }, fillDow: function(){ var dowCnt = this.o.weekStart, html = '<tr>'; if(this.o.calendarWeeks){ var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.o.weekStart + 7) { html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function(){ var html = '', i = 0; while (i < 12) { html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>'; } this.picker.find('.datepicker-months td').html(html); }, setRange: function(range){ if (!range || !range.length) delete this.range; else this.range = $.map(range, function(d){ return d.valueOf(); }); this.fill(); }, getClassNames: function(date){ var cls = [], year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), currentDate = this.date.valueOf(), today = new Date(); if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) { cls.push('old'); } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) { cls.push('new'); } // Compare internal UTC date with local today, not UTC today if (this.o.todayHighlight && date.getUTCFullYear() == today.getFullYear() && date.getUTCMonth() == today.getMonth() && date.getUTCDate() == today.getDate()) { cls.push('today'); } if (currentDate && date.valueOf() == currentDate) { cls.push('active'); } if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate || $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) { cls.push('disabled'); } if (this.range){ if (date > this.range[0] && date < this.range[this.range.length-1]){ cls.push('range'); } if ($.inArray(date.valueOf(), this.range) != -1){ cls.push('selected'); } } return cls; }, fill: function() { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity, startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity, endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity, endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity, currentDate = this.date && this.date.valueOf(), tooltip; this.picker.find('.datepicker-days thead th.datepicker-switch') .text(dates[this.o.language].months[month]+' '+year); this.picker.find('tfoot th.today') .text(dates[this.o.language].today) .toggle(this.o.todayBtn !== false); this.picker.find('tfoot th.clear') .text(dates[this.o.language].clear) .toggle(this.o.clearBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month-1, 28,0,0,0,0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while(prevMonth.valueOf() < nextMonth) { if (prevMonth.getUTCDay() == this.o.weekStart) { html.push('<tr>'); if(this.o.calendarWeeks){ // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">'+ calWeek +'</td>'); } } clsName = this.getClassNames(prevMonth); clsName.push('day'); var before = this.o.beforeShowDay(prevMonth); if (before === undefined) before = {}; else if (typeof(before) === 'boolean') before = {enabled: before}; else if (typeof(before) === 'string') before = {classes: before}; if (before.enabled === false) clsName.push('disabled'); if (before.classes) clsName = clsName.concat(before.classes.split(/\s+/)); if (before.tooltip) tooltip = before.tooltip; clsName = $.unique(clsName); html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() == this.o.weekEnd) { html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate()+1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var currentYear = this.date && this.date.getUTCFullYear(); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear && currentYear == year) { months.eq(this.date.getUTCMonth()).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth).addClass('disabled'); } if (year == endYear) { months.slice(endMonth+1).addClass('disabled'); } html = ''; year = parseInt(year/10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function() { if (!this._allow_update) return; var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode) { case 0: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: case 2: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, click: function(e) { e.preventDefault(); var target = $(e.target).closest('span, td, th'); if (target.length == 1) { switch(target[0].nodeName.toLowerCase()) { case 'th': switch(target[0].className) { case 'datepicker-switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); switch(this.viewMode){ case 0: this.viewDate = this.moveMonth(this.viewDate, dir); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.o.todayBtn == 'linked' ? null : 'view'; this._setDate(date, which); break; case 'clear': var element; if (this.isInput) element = this.element; else if (this.component) element = this.element.find('input'); if (element) element.val("").change(); this._trigger('changeDate'); this.update(); if (this.o.autoclose) this.hide(); break; } break; case 'span': if (!target.is('.disabled')) { this.viewDate.setUTCDate(1); if (target.is('.month')) { var day = 1; var month = target.parent().find('span').index(target); var year = this.viewDate.getUTCFullYear(); this.viewDate.setUTCMonth(month); this._trigger('changeMonth', this.viewDate); if (this.o.minViewMode === 1) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } else { var year = parseInt(target.text(), 10)||0; var day = 1; var month = 0; this.viewDate.setUTCFullYear(year); this._trigger('changeYear', this.viewDate); if (this.o.minViewMode === 2) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')){ var day = parseInt(target.text(), 10)||1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day,0,0,0,0)); } break; } } }, _setDate: function(date, which){ if (!which || which == 'date') this.date = new Date(date); if (!which || which == 'view') this.viewDate = new Date(date); this.fill(); this.setValue(); this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); if (this.o.autoclose && (!which || which == 'date')) { this.hide(); } } }, moveMonth: function(date, dir){ if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1){ test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function(){ return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function(){ return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i=0; i<mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function(){ return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()){ new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function(date, dir){ return this.moveMonth(date, dir*12); }, dateWithinRange: function(date){ return date >= this.o.startDate && date <= this.o.endDate; }, keydown: function(e){ if (this.picker.is(':not(:visible)')){ if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch(e.keyCode){ case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.o.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.o.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir * 7); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter this.hide(); e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged){ this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); } } }, showMode: function(dir) { if (dir) { this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir)); } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover. Method show() does not set display css correctly and datepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); } }; var DateRangePicker = function(element, options){ this.element = $(element); this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; }); delete options.inputs; $(this.inputs) .datepicker(options) .bind('changeDate', $.proxy(this.dateUpdated, this)); this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); }); this.updateDates(); }; DateRangePicker.prototype = { updateDates: function(){ this.dates = $.map(this.pickers, function(i){ return i.date; }); this.updateRanges(); }, updateRanges: function(){ var range = $.map(this.dates, function(d){ return d.valueOf(); }); $.each(this.pickers, function(i, p){ p.setRange(range); }); }, dateUpdated: function(e){ var dp = $(e.target).data('datepicker'), new_date = dp.getUTCDate(), i = $.inArray(e.target, this.inputs), l = this.inputs.length; if (i == -1) return; if (new_date < this.dates[i]){ // Date being moved earlier/left while (i>=0 && new_date < this.dates[i]){ this.pickers[i--].setUTCDate(new_date); } } else if (new_date > this.dates[i]){ // Date being moved later/right while (i<l && new_date > this.dates[i]){ this.pickers[i++].setUTCDate(new_date); } } this.updateDates(); }, remove: function(){ $.map(this.pickers, function(p){ p.remove(); }); delete this.element.data().datepicker; } }; function opts_from_el(el, prefix){ // Derive options from element data-attrs var data = $(el).data(), out = {}, inkey, replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'), prefix = new RegExp('^' + prefix.toLowerCase()); for (var key in data) if (prefix.test(key)){ inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); }); out[inkey] = data[key]; } return out; } function opts_from_locale(lang){ // Derive options from locale plugins var out = {}; // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" if (!dates[lang]) { lang = lang.split('-')[0] if (!dates[lang]) return; } var d = dates[lang]; $.each(locale_opts, function(i,k){ if (k in d) out[k] = d[k]; }); return out; } var old = $.fn.datepicker; var datepicker = $.fn.datepicker = function ( option ) { var args = Array.apply(null, arguments); args.shift(); var internal_return, this_return; this.each(function () { var $this = $(this), data = $this.data('datepicker'), options = typeof option == 'object' && option; if (!data) { var elopts = opts_from_el(this, 'date'), // Preliminary otions xopts = $.extend({}, defaults, elopts, options), locopts = opts_from_locale(xopts.language), // Options priority: js args, data-attrs, locales, defaults opts = $.extend({}, defaults, locopts, elopts, options); if ($this.is('.input-daterange') || opts.inputs){ var ropts = { inputs: opts.inputs || $this.find('input').toArray() }; $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts)))); } else{ $this.data('datepicker', (data = new Datepicker(this, opts))); } } if (typeof option == 'string' && typeof data[option] == 'function') { internal_return = data[option].apply(data, args); if (internal_return !== undefined) return false; } }); if (internal_return !== undefined) return internal_return; else return this; }; var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; var locale_opts = $.fn.datepicker.locale_opts = [ 'format', 'rtl', 'weekStart' ]; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today", clear: "Clear" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function(format){ // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, parseDate: function(date, format, language) { if (date instanceof Date) return date; if (typeof format === 'string') format = DPGlobal.parseFormat(format); if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) { var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i=0; i<parts.length; i++) { part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch(part[2]){ case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } var parts = date && date.match(this.nonpunctuation) || [], date = new Date(), parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function(d,v){ return d.setUTCFullYear(v); }, yy: function(d,v){ return d.setUTCFullYear(2000+v); }, m: function(d,v){ v -= 1; while (v<0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) d.setUTCDate(d.getUTCDate()-1); return d; }, d: function(d,v){ return d.setUTCDate(v); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length != fparts.length) { fparts = $(fparts).filter(function(i,p){ return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder if (parts.length == fparts.length) { for (var i=0, cnt = fparts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)) { switch(part) { case 'MM': filtered = $(dates[language].months).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } for (var i=0, s; i<setters_order.length; i++){ s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) setters_map[s](date, parsed[s]); } } return date; }, formatDate: function(date, format, language){ if (typeof format === 'string') format = DPGlobal.parseFormat(format); var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; var date = [], seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i <= cnt; i++) { if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>'+ '<tr>'+ '<th class="prev"><i class="icon-arrow-left"/></th>'+ '<th colspan="5" class="datepicker-switch"></th>'+ '<th class="next"><i class="icon-arrow-right"/></th>'+ '</tr>'+ '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>' }; DPGlobal.template = '<div class="datepicker">'+ '<div class="datepicker-days">'+ '<table class=" table-condensed">'+ DPGlobal.headTemplate+ '<tbody></tbody>'+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-months">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-years">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; /* DATEPICKER NO CONFLICT * =================== */ $.fn.datepicker.noConflict = function(){ $.fn.datepicker = old; return this; }; /* DATEPICKER DATA-API * ================== */ $(document).on( 'focus.datepicker.data-api click.datepicker.data-api', '[data-provide="datepicker"]', function(e){ var $this = $(this); if ($this.data('datepicker')) return; e.preventDefault(); // component click requires us to explicitly show it datepicker.call($this, 'show'); } ); $(function(){ //$('[data-provide="datepicker-inline"]').datepicker(); //vit: changed to support noConflict() datepicker.call($('[data-provide="datepicker-inline"]')); }); }( window.jQuery )); /** Bootstrap-datepicker. Description and examples: https://github.com/eternicode/bootstrap-datepicker. For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales and set `language` option. Since 1.4.0 date has different appearance in **popup** and **inline** modes. @class date @extends abstractinput @final @example <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-original-title="Select date">15/05/1984</a> <script> $(function(){ $('#dob').editable({ format: 'yyyy-mm-dd', viewformat: 'dd/mm/yyyy', datepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; //store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one $.fn.bdatepicker = $.fn.datepicker.noConflict(); if(!$.fn.datepicker) { //if there were no other datepickers, keep also original name $.fn.datepicker = $.fn.bdatepicker; } var Date = function (options) { this.init('date', options, Date.defaults); this.initPicker(options, Date.defaults); }; $.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput); $.extend(Date.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //overriding datepicker config (as by default jQuery extend() is not recursive) //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, { format: this.options.viewformat }); //language this.options.datepicker.language = this.options.datepicker.language || 'en'; //store DPglobal this.dpg = $.fn.bdatepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat); }, render: function () { this.$input.bdatepicker(this.options.datepicker); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''; Date.superclass.value2html(text, element); }, html2value: function(html) { return this.parseDate(html, this.parsedViewFormat); }, value2str: function(value) { return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : ''; }, str2value: function(str) { return this.parseDate(str, this.parsedFormat); }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.bdatepicker('update', value); }, input2value: function() { return this.$input.data('datepicker').date; }, activate: function() { }, clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.day', function(e){ if($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) { return; } var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); //changedate is not suitable as it triggered when showing datepicker. see #149 /* this.$input.on('changeDate', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); */ }, /* For incorrect date bootstrap-datepicker returns current date that is not suitable for datefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datepicker.language); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language); if(str !== formattedBack) { date = null; } } } return date; } }); Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code> @property format @type string @default yyyy-mm-dd **/ format:'yyyy-mm-dd', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datepicker. Full list of options: http://vitalets.github.com/bootstrap-datepicker @property datepicker @type object @default { weekStart: 0, startView: 0, minViewMode: 0, autoclose: false } **/ datepicker:{ weekStart: 0, startView: 0, minViewMode: 0, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.date = Date; }(window.jQuery)); /** Bootstrap datefield input - modification for inline mode. Shows normal <input type="text"> and binds popup datepicker. Automatically shown in inline mode. @class datefield @extends date @since 1.4.0 **/ (function ($) { "use strict"; var DateField = function (options) { this.init('datefield', options, DateField.defaults); this.initPicker(options, DateField.defaults); }; $.fn.editableutils.inherit(DateField, $.fn.editabletypes.date); $.extend(DateField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); //bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js) this.$tpl.bdatepicker(this.options.datepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.bdatepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''); this.$tpl.bdatepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-small' **/ inputclass: 'input-small', /* datepicker config */ datepicker: { weekStart: 0, startView: 0, minViewMode: 0, autoclose: true } }); $.fn.editabletypes.datefield = DateField; }(window.jQuery)); /** Bootstrap-datetimepicker. Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker). Before usage you should manually include dependent js and css: <link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link> <script src="js/bootstrap-datetimepicker.js"></script> For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales and set `language` option. @class datetime @extends abstractinput @final @since 1.4.4 @example <a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a> <script> $(function(){ $('#last_seen').editable({ format: 'yyyy-mm-dd hh:ii', viewformat: 'dd/mm/yyyy hh:ii', datetimepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; var DateTime = function (options) { this.init('datetime', options, DateTime.defaults); this.initPicker(options, DateTime.defaults); }; $.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput); $.extend(DateTime.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //overriding datetimepicker config (as by default jQuery extend() is not recursive) //since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, { format: this.options.viewformat }); //language this.options.datetimepicker.language = this.options.datetimepicker.language || 'en'; //store DPglobal this.dpg = $.fn.datetimepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType); }, render: function () { this.$input.datetimepicker(this.options.datetimepicker); //adjust container position when viewMode changes //see https://github.com/smalot/bootstrap-datetimepicker/pull/80 this.$input.on('changeMode', function(e) { var f = $(this).closest('form').parent(); //timeout here, otherwise container changes position before form has new size setTimeout(function(){ f.triggerHandler('resize'); }, 0); }); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { //formatDate works with UTCDate! var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : ''; if(element) { DateTime.superclass.value2html(text, element); } else { return text; } }, html2value: function(html) { //parseDate return utc date! var value = this.parseDate(html, this.parsedViewFormat); return value ? this.fromUTC(value) : null; }, value2str: function(value) { //formatDate works with UTCDate! return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : ''; }, str2value: function(str) { //parseDate return utc date! var value = this.parseDate(str, this.parsedFormat); return value ? this.fromUTC(value) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { if(value) { this.$input.data('datetimepicker').setDate(value); } }, input2value: function() { //date may be cleared, in that case getDate() triggers error var dt = this.$input.data('datetimepicker'); return dt.date ? dt.getDate() : null; }, activate: function() { }, clear: function() { this.$input.data('datetimepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.minute', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); }, //convert date from local to utc toUTC: function(value) { return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value; }, //convert date from utc to local fromUTC: function(value) { return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value; }, /* For incorrect date bootstrap-datetimepicker returns current date that is not suitable for datetimefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType); if(str !== formattedBack) { date = null; } } } return date; } }); DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code> @property format @type string @default yyyy-mm-dd hh:ii **/ format:'yyyy-mm-dd hh:ii', formatType:'standard', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datetimepicker. Full list of options: https://github.com/smalot/bootstrap-datetimepicker @property datetimepicker @type object @default { } **/ datetimepicker:{ todayHighlight: false, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.datetime = DateTime; }(window.jQuery)); /** Bootstrap datetimefield input - datetime input for inline mode. Shows normal <input type="text"> and binds popup datetimepicker. Automatically shown in inline mode. @class datetimefield @extends datetime **/ (function ($) { "use strict"; var DateTimeField = function (options) { this.init('datetimefield', options, DateTimeField.defaults); this.initPicker(options, DateTimeField.defaults); }; $.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime); $.extend(DateTimeField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); this.$tpl.datetimepicker(this.options.datetimepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.datetimepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(this.value2html(value)); this.$tpl.datetimepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-medium' **/ inputclass: 'input-medium', /* datetimepicker config */ datetimepicker:{ todayHighlight: false, autoclose: true } }); $.fn.editabletypes.datetimefield = DateTimeField; }(window.jQuery)); /** Typeahead input (bootstrap only). Based on Twitter Bootstrap [typeahead](http://twitter.github.com/bootstrap/javascript.html#typeahead). Depending on `source` format typeahead operates in two modes: * **strings**: When `source` defined as array of strings, e.g. `['text1', 'text2', 'text3' ...]`. User can submit one of these strings or any text entered in input (even if it is not matching source). * **objects**: When `source` defined as array of objects, e.g. `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]`. User can submit only values that are in source (otherwise `null` is submitted). This is more like *dropdown* behavior. @class typeahead @extends list @since 1.4.1 @final @example <a href="#" id="country" data-type="typeahead" data-pk="1" data-url="/post" data-original-title="Input country"></a> <script> $(function(){ $('#country').editable({ value: 'ru', source: [ {value: 'gb', text: 'Great Britain'}, {value: 'us', text: 'United States'}, {value: 'ru', text: 'Russia'} ] }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('typeahead', options, Constructor.defaults); //overriding objects in config (as by default jQuery extend() is not recursive) this.options.typeahead = $.extend({}, Constructor.defaults.typeahead, { //set default methods for typeahead to work with objects matcher: this.matcher, sorter: this.sorter, highlighter: this.highlighter, updater: this.updater }, options.typeahead); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.list); $.extend(Constructor.prototype, { renderList: function() { this.$input = this.$tpl.is('input') ? this.$tpl : this.$tpl.find('input[type="text"]'); //set source of typeahead this.options.typeahead.source = this.sourceData; //apply typeahead this.$input.typeahead(this.options.typeahead); //patch some methods in typeahead var ta = this.$input.data('typeahead'); ta.render = $.proxy(this.typeaheadRender, ta); ta.select = $.proxy(this.typeaheadSelect, ta); ta.move = $.proxy(this.typeaheadMove, ta); this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, value2htmlFinal: function(value, element) { if(this.getIsObjects()) { var items = $.fn.editableutils.itemsByValue(value, this.sourceData); $(element).text(items.length ? items[0].text : ''); } else { $(element).text(value); } }, html2value: function (html) { return html ? html : null; }, value2input: function(value) { if(this.getIsObjects()) { var items = $.fn.editableutils.itemsByValue(value, this.sourceData); this.$input.data('value', value).val(items.length ? items[0].text : ''); } else { this.$input.val(value); } }, input2value: function() { if(this.getIsObjects()) { var value = this.$input.data('value'), items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length && items[0].text.toLowerCase() === this.$input.val().toLowerCase()) { return value; } else { return null; //entered string not found in source } } else { return this.$input.val(); } }, /* if in sourceData values <> texts, typeahead in "objects" mode: user must pick some value from list, otherwise `null` returned. if all values == texts put typeahead in "strings" mode: anything what entered is submited. */ getIsObjects: function() { if(this.isObjects === undefined) { this.isObjects = false; for(var i=0; i<this.sourceData.length; i++) { if(this.sourceData[i].value !== this.sourceData[i].text) { this.isObjects = true; break; } } } return this.isObjects; }, /* Methods borrowed from text input */ activate: $.fn.editabletypes.text.prototype.activate, renderClear: $.fn.editabletypes.text.prototype.renderClear, postrender: $.fn.editabletypes.text.prototype.postrender, toggleClear: $.fn.editabletypes.text.prototype.toggleClear, clear: function() { $.fn.editabletypes.text.prototype.clear.call(this); this.$input.data('value', ''); }, /* Typeahead option methods used as defaults */ /*jshint eqeqeq:false, curly: false, laxcomma: true, asi: true*/ matcher: function (item) { return $.fn.typeahead.Constructor.prototype.matcher.call(this, item.text); }, sorter: function (items) { var beginswith = [] , caseSensitive = [] , caseInsensitive = [] , item , text; while (item = items.shift()) { text = item.text; if (!text.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item); else if (~text.indexOf(this.query)) caseSensitive.push(item); else caseInsensitive.push(item); } return beginswith.concat(caseSensitive, caseInsensitive); }, highlighter: function (item) { return $.fn.typeahead.Constructor.prototype.highlighter.call(this, item.text); }, updater: function (item) { this.$element.data('value', item.value); return item.text; }, /* Overwrite typeahead's render method to store objects. There are a lot of disscussion in bootstrap repo on this point and still no result. See https://github.com/twitter/bootstrap/issues/5967 This function just store item via jQuery data() method instead of attr('data-value') */ typeaheadRender: function (items) { var that = this; items = $(items).map(function (i, item) { // i = $(that.options.item).attr('data-value', item) i = $(that.options.item).data('item', item); i.find('a').html(that.highlighter(item)); return i[0]; }); //add option to disable autoselect of first line //see https://github.com/twitter/bootstrap/pull/4164 if (this.options.autoSelect) { items.first().addClass('active'); } this.$menu.html(items); return this; }, //add option to disable autoselect of first line //see https://github.com/twitter/bootstrap/pull/4164 typeaheadSelect: function () { var val = this.$menu.find('.active').data('item') if(this.options.autoSelect || val){ this.$element .val(this.updater(val)) .change() } return this.hide() }, /* if autoSelect = false and nothing matched we need extra press onEnter that is not convinient. This patch fixes it. */ typeaheadMove: function (e) { if (!this.shown) return switch(e.keyCode) { case 9: // tab case 13: // enter case 27: // escape if (!this.$menu.find('.active').length) return e.preventDefault() break case 38: // up arrow e.preventDefault() this.prev() break case 40: // down arrow e.preventDefault() this.next() break } e.stopPropagation() } /*jshint eqeqeq: true, curly: true, laxcomma: false, asi: false*/ }); Constructor.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** Configuration of typeahead. [Full list of options](http://twitter.github.com/bootstrap/javascript.html#typeahead). @property typeahead @type object @default null **/ typeahead: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.typeahead = Constructor; }(window.jQuery));
ajax/libs/ember-data.js/0.0.12/ember-data.js
pzp1997/cdnjs
// Last commit: 6140f7d (2013-04-11 15:48:46 -0700) (function() { window.DS = Ember.Namespace.create({ // this one goes past 11 CURRENT_API_REVISION: 12 }); })(); (function() { /** * Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> * © 2011 Colin Snover <http://zetafleet.com> * Released under MIT license. */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } })(); (function() { })(); (function() { var DeferredMixin = Ember.DeferredMixin, // ember-runtime/mixins/deferred Evented = Ember.Evented, // ember-runtime/mixins/evented run = Ember.run, // ember-metal/run-loop get = Ember.get; // ember-metal/accessors var LoadPromise = Ember.Mixin.create(Evented, DeferredMixin, { init: function() { this._super.apply(this, arguments); this.one('didLoad', function() { run(this, 'resolve', this); }); if (get(this, 'isLoaded')) { this.trigger('didLoad'); } } }); DS.LoadPromise = LoadPromise; })(); (function() { var get = Ember.get, set = Ember.set; var LoadPromise = DS.LoadPromise; // system/mixins/load_promise /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of DS.RecordArray or its subclasses will be returned by your application's store in response to queries. */ DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, LoadPromise, { /** The model type contained by this record array. @type DS.Model */ type: null, // The array of client ids backing the record array. When a // record is requested from the record array, the record // for the client id at the same index is materialized, if // necessary, by the store. content: null, isLoaded: false, isUpdating: false, // The store that created this record array. store: null, objectAtContent: function(index) { var content = get(this, 'content'), reference = content.objectAt(index), store = get(this, 'store'); if (reference) { return store.recordForReference(reference); } }, materializedObjectAt: function(index) { var reference = get(this, 'content').objectAt(index); if (!reference) { return; } if (get(this, 'store').recordIsMaterialized(reference)) { return this.objectAt(index); } }, update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'), type = get(this, 'type'); store.fetchAll(type, this); }, addReference: function(reference) { get(this, 'content').addObject(reference); }, removeReference: function(reference) { get(this, 'content').removeObject(reference); } }); })(); (function() { var get = Ember.get; DS.FilteredRecordArray = DS.RecordArray.extend({ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, updateFilter: Ember.observer(function() { var store = get(this, 'store'); store.updateRecordArrayFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, 'filterFunction') }); })(); (function() { var get = Ember.get, set = Ember.set; DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, load: function(references) { var store = get(this, 'store'), type = get(this, 'type'); this.beginPropertyChanges(); set(this, 'content', Ember.A(references)); set(this, 'isLoaded', true); this.endPropertyChanges(); var self = this; // TODO: does triggering didLoad event should be the last action of the runLoop? Ember.run.once(function() { self.trigger('didLoad'); }); } }); })(); (function() { var get = Ember.get, set = Ember.set; /** A ManyArray is a RecordArray that represents the contents of a has-many relationship. The ManyArray is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: App.Post = DS.Model.extend({ comments: DS.hasMany('App.Comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('App.Post') }); If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. */ DS.ManyArray = DS.RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** @private The record to which this relationship belongs. @property {DS.Model} */ owner: null, /** @private `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} */ isPolymorphic: false, // LOADING STATE isLoaded: false, loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, fetch: function() { var references = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'); store.fetchUnloadedReferences(references, owner); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = added.map(function(record) { Ember.assert("You can only add records of " + (get(this, 'type') && get(this, 'type').toString()) + " to this relationship.", !get(this, 'type') || (get(this, 'type').detectInstance(record)) ); return get(record, '_reference'); }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { this.fetch(); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var reference = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner.get('_reference'), reference, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var reference = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner.get('_reference'), reference, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(function(change) { change.sync(); }); DS.OneToManyChange.ensureSameTransaction(this._changesToSync, store); this._changesToSync.clear(); } }, // Create a child record within the owner createRecord: function(hash, transaction) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; Ember.assert("You can not create records of " + (get(this, 'type') && get(this, 'type').toString()) + " on this polymorphic relationship.", !get(this, 'isPolymorphic')); transaction = transaction || get(owner, 'transaction'); record = store.createRecord.call(store, type, hash, transaction); this.pushObject(record); return record; } }); })(); (function() { })(); (function() { var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt, removeObject = Ember.EnumerableUtils.removeObject, forEach = Ember.EnumerableUtils.forEach; /** A transaction allows you to collect multiple records into a unit of work that can be committed or rolled back as a group. For example, if a record has local modifications that have not yet been saved, calling `commit()` on its transaction will cause those modifications to be sent to the adapter to be saved. Calling `rollback()` on its transaction would cause all of the modifications to be discarded and the record to return to the last known state before changes were made. If a newly created record's transaction is rolled back, it will immediately transition to the deleted state. If you do not explicitly create a transaction, a record is assigned to an implicit transaction called the default transaction. In these cases, you can treat your application's instance of `DS.Store` as a transaction and call the `commit()` and `rollback()` methods on the store itself. Once a record has been successfully committed or rolled back, it will be moved back to the implicit transaction. Because it will now be in a clean state, it can be moved to a new transaction if you wish. ### Creating a Transaction To create a new transaction, call the `transaction()` method of your application's `DS.Store` instance: var transaction = App.store.transaction(); This will return a new instance of `DS.Transaction` with no records yet assigned to it. ### Adding Existing Records Add records to a transaction using the `add()` method: record = App.store.find(App.Person, 1); transaction.add(record); Note that only records whose `isDirty` flag is `false` may be added to a transaction. Once modifications to a record have been made (its `isDirty` flag is `true`), it is not longer able to be added to a transaction. ### Creating New Records Because newly created records are dirty from the time they are created, and because dirty records can not be added to a transaction, you must use the `createRecord()` method to assign new records to a transaction. For example, instead of this: var transaction = store.transaction(); var person = App.Person.createRecord({ name: "Steve" }); // won't work because person is dirty transaction.add(person); Call `createRecord()` on the transaction directly: var transaction = store.transaction(); transaction.createRecord(App.Person, { name: "Steve" }); ### Asynchronous Commits Typically, all of the records in a transaction will be committed together. However, new records that have a dependency on other new records need to wait for their parent record to be saved and assigned an ID. In that case, the child record will continue to live in the transaction until its parent is saved, at which time the transaction will attempt to commit again. For this reason, you should not re-use transactions once you have committed them. Always make a new transaction and move the desired records to it before calling commit. */ var arrayDefault = function() { return []; }; DS.Transaction = Ember.Object.extend({ /** @private Creates the bucket data structure used to segregate records by type. */ init: function() { set(this, 'buckets', { clean: Ember.OrderedSet.create(), created: Ember.OrderedSet.create(), updated: Ember.OrderedSet.create(), deleted: Ember.OrderedSet.create(), inflight: Ember.OrderedSet.create() }); set(this, 'relationships', Ember.OrderedSet.create()); }, /** Creates a new record of the given type and assigns it to the transaction on which the method was called. This is useful as only clean records can be added to a transaction and new records created using other methods immediately become dirty. @param {DS.Model} type the model type to create @param {Object} hash the data hash to assign the new record */ createRecord: function(type, hash) { var store = get(this, 'store'); return store.createRecord(type, hash, this); }, isEqualOrDefault: function(other) { if (this === other || other === get(this, 'store.defaultTransaction')) { return true; } }, isDefault: Ember.computed(function() { return this === get(this, 'store.defaultTransaction'); }), /** Adds an existing record to this transaction. Only records without modficiations (i.e., records whose `isDirty` property is `false`) can be added to a transaction. @param {DS.Model} record the record to add to the transaction */ add: function(record) { Ember.assert("You must pass a record into transaction.add()", record instanceof DS.Model); var recordTransaction = get(record, 'transaction'), defaultTransaction = get(this, 'store.defaultTransaction'); // Make `add` idempotent if (recordTransaction === this) { return; } // XXX it should be possible to move a dirty transaction from the default transaction // we could probably make this work if someone has a valid use case. Do you? Ember.assert("Once a record has changed, you cannot move it into a different transaction", !get(record, 'isDirty')); Ember.assert("Models cannot belong to more than one transaction at a time.", recordTransaction === defaultTransaction); this.adoptRecord(record); }, relationshipBecameDirty: function(relationship) { get(this, 'relationships').add(relationship); }, relationshipBecameClean: function(relationship) { get(this, 'relationships').remove(relationship); }, /** Commits the transaction, which causes all of the modified records that belong to the transaction to be sent to the adapter to be saved. Once you call `commit()` on a transaction, you should not re-use it. When a record is saved, it will be removed from this transaction and moved back to the store's default transaction. */ commit: function() { var store = get(this, 'store'); var adapter = get(store, '_adapter'); var defaultTransaction = get(store, 'defaultTransaction'); var iterate = function(records) { var set = records.copy(); set.forEach(function (record) { record.send('willCommit'); }); return set; }; var relationships = get(this, 'relationships'); var commitDetails = { created: iterate(this.bucketForType('created')), updated: iterate(this.bucketForType('updated')), deleted: iterate(this.bucketForType('deleted')), relationships: relationships }; if (this === defaultTransaction) { set(store, 'defaultTransaction', store.transaction()); } this.removeCleanRecords(); if (!commitDetails.created.isEmpty() || !commitDetails.updated.isEmpty() || !commitDetails.deleted.isEmpty() || !relationships.isEmpty()) { Ember.assert("You tried to commit records but you have no adapter", adapter); Ember.assert("You tried to commit records but your adapter does not implement `commit`", adapter.commit); adapter.commit(store, commitDetails); } // Once we've committed the transaction, there is no need to // keep the OneToManyChanges around. Destroy them so they // can be garbage collected. relationships.forEach(function(relationship) { relationship.destroy(); }); }, /** Rolling back a transaction resets the records that belong to that transaction. Updated records have their properties reset to the last known value from the persistence layer. Deleted records are reverted to a clean, non-deleted state. Newly created records immediately become deleted, and are not sent to the adapter to be persisted. After the transaction is rolled back, any records that belong to it will return to the store's default transaction, and the current transaction should not be used again. */ rollback: function() { // Loop through all of the records in each of the dirty states // and initiate a rollback on them. As a side effect of telling // the record to roll back, it should also move itself out of // the dirty bucket and into the clean bucket. ['created', 'updated', 'deleted', 'inflight'].forEach(function(bucketType) { var records = this.bucketForType(bucketType); forEach(records, function(record) { record.send('rollback'); }); records.clear(); }, this); // Now that all records in the transaction are guaranteed to be // clean, migrate them all to the store's default transaction. this.removeCleanRecords(); }, /** @private Removes a record from this transaction and back to the store's default transaction. Note: This method is private for now, but should probably be exposed in the future once we have stricter error checking (for example, in the case of the record being dirty). @param {DS.Model} record */ remove: function(record) { var defaultTransaction = get(this, 'store.defaultTransaction'); defaultTransaction.adoptRecord(record); }, /** @private Removes all of the records in the transaction's clean bucket. */ removeCleanRecords: function() { var clean = this.bucketForType('clean'); clean.forEach(function(record) { this.remove(record); }, this); clean.clear(); }, /** @private Returns the bucket for the given bucket type. For example, you might call `this.bucketForType('updated')` to get the `Ember.Map` that contains all of the records that have changes pending. @param {String} bucketType the type of bucket @returns Ember.Map */ bucketForType: function(bucketType) { var buckets = get(this, 'buckets'); return get(buckets, bucketType); }, /** @private This method moves a record into a different transaction without the normal checks that ensure that the user is not doing something weird, like moving a dirty record into a new transaction. It is designed for internal use, such as when we are moving a clean record into a new transaction when the transaction is committed. This method must not be called unless the record is clean. @param {DS.Model} record */ adoptRecord: function(record) { var oldTransaction = get(record, 'transaction'); if (oldTransaction) { oldTransaction.removeFromBucket('clean', record); } this.addToBucket('clean', record); set(record, 'transaction', this); }, /** @private Adds a record to the named bucket. @param {String} bucketType one of `clean`, `created`, `updated`, or `deleted` */ addToBucket: function(bucketType, record) { this.bucketForType(bucketType).add(record); }, /** @private Removes a record from the named bucket. @param {String} bucketType one of `clean`, `created`, `updated`, or `deleted` */ removeFromBucket: function(bucketType, record) { this.bucketForType(bucketType).remove(record); }, /** @private Called by a record's state manager to indicate that the record has entered a dirty state. The record will be moved from the `clean` bucket and into the appropriate dirty bucket. @param {String} bucketType one of `created`, `updated`, or `deleted` */ recordBecameDirty: function(bucketType, record) { this.removeFromBucket('clean', record); this.addToBucket(bucketType, record); }, /** @private Called by a record's state manager to indicate that the record has entered inflight state. The record will be moved from its current dirty bucket and into the `inflight` bucket. @param {String} bucketType one of `created`, `updated`, or `deleted` */ recordBecameInFlight: function(kind, record) { this.removeFromBucket(kind, record); this.addToBucket('inflight', record); }, recordIsMoving: function(kind, record) { this.removeFromBucket(kind, record); this.addToBucket('clean', record); }, /** @private Called by a record's state manager to indicate that the record has entered a clean state. The record will be moved from its current dirty or inflight bucket and into the `clean` bucket. @param {String} bucketType one of `created`, `updated`, or `deleted` */ recordBecameClean: function(kind, record) { this.removeFromBucket(kind, record); this.remove(record); } }); })(); (function() { var classify = Ember.String.classify, get = Ember.get; /** @private The Mappable mixin is designed for classes that would like to behave as a map for configuration purposes. For example, the DS.Adapter class can behave like a map, with more semantic API, via the `map` API: DS.Adapter.map('App.Person', { firstName: { key: 'FIRST' } }); Class configuration via a map-like API has a few common requirements that differentiate it from the standard Ember.Map implementation. First, values often are provided as strings that should be normalized into classes the first time the configuration options are used. Second, the values configured on parent classes should also be taken into account. Finally, setting the value of a key sometimes should merge with the previous value, rather than replacing it. This mixin provides a instance method, `createInstanceMapFor`, that will reify all of the configuration options set on an instance's constructor and provide it for the instance to use. Classes can implement certain hooks that allow them to customize the requirements listed above: * `resolveMapConflict` - called when a value is set for an existing value * `transformMapKey` - allows a key name (for example, a global path to a class) to be normalized * `transformMapValue` - allows a value (for example, a class that should be instantiated) to be normalized Classes that implement this mixin should also implement a class method built using the `generateMapFunctionFor` method: DS.Adapter.reopenClass({ map: DS.Mappable.generateMapFunctionFor('attributes', function(key, newValue, map) { var existingValue = map.get(key); for (var prop in newValue) { if (!newValue.hasOwnProperty(prop)) { continue; } existingValue[prop] = newValue[prop]; } }) }); The function passed to `generateMapFunctionFor` is invoked every time a new value is added to the map. **/ var resolveMapConflict = function(oldValue, newValue, mappingsKey) { return oldValue; }; var transformMapKey = function(key, value) { return key; }; var transformMapValue = function(key, value) { return value; }; DS._Mappable = Ember.Mixin.create({ createInstanceMapFor: function(mapName) { var instanceMeta = Ember.metaPath(this, ['DS.Mappable'], true); instanceMeta.values = instanceMeta.values || {}; if (instanceMeta.values[mapName]) { return instanceMeta.values[mapName]; } var instanceMap = instanceMeta.values[mapName] = new Ember.Map(); var klass = this.constructor; while (klass && klass !== DS.Store) { this._copyMap(mapName, klass, instanceMap); klass = klass.superclass; } instanceMeta.values[mapName] = instanceMap; return instanceMap; }, _copyMap: function(mapName, klass, instanceMap) { var classMeta = Ember.metaPath(klass, ['DS.Mappable'], true); var classMap = classMeta[mapName]; if (classMap) { classMap.forEach(eachMap, this); } function eachMap(key, value) { var transformedKey = (klass.transformMapKey || transformMapKey)(key, value); var transformedValue = (klass.transformMapValue || transformMapValue)(key, value); var oldValue = instanceMap.get(transformedKey); var newValue = transformedValue; if (oldValue) { newValue = (this.constructor.resolveMapConflict || resolveMapConflict)(oldValue, newValue, mapName); } instanceMap.set(transformedKey, newValue); } } }); DS._Mappable.generateMapFunctionFor = function(mapName, transform) { return function(key, value) { var meta = Ember.metaPath(this, ['DS.Mappable'], true); var map = meta[mapName] || Ember.MapWithDefault.create({ defaultValue: function() { return {}; } }); transform.call(this, key, value, map); meta[mapName] = map; }; }; })(); (function() { /*globals Ember*/ /*jshint eqnull:true*/ var get = Ember.get, set = Ember.set, fmt = Ember.String.fmt, once = Ember.run.once; var forEach = Ember.EnumerableUtils.forEach; // These values are used in the data cache when clientIds are // needed but the underlying data has not yet been loaded by // the server. var UNLOADED = 'unloaded'; var LOADING = 'loading'; var MATERIALIZED = { materialized: true }; var CREATED = { created: true }; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. var coerceId = function(id) { return id == null ? null : id+''; }; var map = Ember.EnumerableUtils.map; /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of DS.Model that wraps the individual data for a record, so that they can be bound to in your Handlebars templates. Create a new store like this: MyApp.store = DS.Store.create(); You can retrieve DS.Model instances from the store in several ways. To retrieve a record for a specific id, use the `find()` method: var record = MyApp.store.find(MyApp.Contact, 123); By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. */ DS.Store = Ember.Object.extend(DS._Mappable, { /** Many methods can be invoked without specifying which store should be used. In those cases, the first store created will be used as the default. If an application has multiple stores, it should specify which store to use when performing actions, such as finding records by id. The init method registers this store as the default if none is specified. */ init: function() { // Enforce API revisioning. See BREAKING_CHANGES.md for more. var revision = get(this, 'revision'); if (revision !== DS.CURRENT_API_REVISION && !Ember.ENV.TESTING) { throw new Error("Error: The Ember Data library has had breaking API changes since the last time you updated the library. Please review the list of breaking changes at https://github.com/emberjs/data/blob/master/BREAKING_CHANGES.md, then update your store's `revision` property to " + DS.CURRENT_API_REVISION); } if (!get(DS, 'defaultStore') || get(this, 'isDefaultStore')) { set(DS, 'defaultStore', this); } // internal bookkeeping; not observable this.typeMaps = {}; this.recordCache = []; this.clientIdToId = {}; this.clientIdToType = {}; this.clientIdToData = {}; this.clientIdToPrematerializedData = {}; this.recordArraysByClientId = {}; this.relationshipChanges = {}; this.recordReferences = {}; // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. this.loadingRecordArrays = {}; this._recordsToSave = Ember.OrderedSet.create(); set(this, 'defaultTransaction', this.transaction()); }, /** Returns a new transaction scoped to this store. This delegates responsibility for invoking the adapter's commit mechanism to a transaction. Transaction are responsible for tracking changes to records added to them, and supporting `commit` and `rollback` functionality. Committing a transaction invokes the store's adapter, while rolling back a transaction reverses all changes made to records added to the transaction. A store has an implicit (default) transaction, which tracks changes made to records not explicitly added to a transaction. @see {DS.Transaction} @returns DS.Transaction */ transaction: function() { return DS.Transaction.create({ store: this }); }, ensureSameTransaction: function(records){ var transactions = Ember.A(); forEach( records, function(record){ if (record){ transactions.pushObject(get(record, 'transaction')); } }); var transaction = transactions.reduce(function(prev, t) { if (!get(t, 'isDefault')) { if (prev === null) { return t; } Ember.assert("All records in a changed relationship must be in the same transaction. You tried to change the relationship between records when one is in " + t + " and the other is in " + prev, t === prev); } return prev; }, null); if (transaction) { forEach( records, function(record){ if (record){ transaction.add(record); } }); } else { transaction = transactions.objectAt(0); } return transaction; }, /** @private Instructs the store to materialize the data for a given record. To materialize a record, the store first retrieves the opaque data that was passed to either `load()` or `loadMany()`. Then, the data and the record are passed to the adapter's `materialize()` method, which allows the adapter to translate arbitrary data structures from the adapter into the normalized form the record expects. The adapter's `materialize()` method will invoke `materializeAttribute()`, `materializeHasMany()` and `materializeBelongsTo()` on the record to populate it with normalized values. @param {DS.Model} record */ materializeData: function(record) { var clientId = get(record, 'clientId'), cidToData = this.clientIdToData, adapter = this.adapterForType(record.constructor), data = cidToData[clientId]; cidToData[clientId] = MATERIALIZED; var prematerialized = this.clientIdToPrematerializedData[clientId]; // Ensures the record's data structures are setup // before being populated by the adapter. record.setupData(); if (data !== CREATED) { // Instructs the adapter to extract information from the // opaque data and materialize the record's attributes and // relationships. adapter.materialize(record, data, prematerialized); } }, /** @private Returns true if there is already a record for this clientId. This is used to determine whether cleanup is required, so that "changes" to unmaterialized records do not trigger mass materialization. For example, if a parent record in a relationship with a large number of children is deleted, we want to avoid materializing those children. @param {Object} reference @return {Boolean} */ recordIsMaterialized: function(reference) { return !!this.recordCache[reference.clientId]; }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, a class, or a property path that specifies where the adapter can be located. @property {DS.Adapter|String} */ adapter: 'DS.RESTAdapter', /** @private Returns a JSON representation of the record using the adapter's serialization strategy. This method exists primarily to enable a record, which has access to its store (but not the store's adapter) to provide a `serialize()` convenience. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.adapterForType(record.constructor).serialize(record, options); }, /** @private This property returns the adapter, after resolving a possible property path. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @returns DS.Adapter */ _adapter: Ember.computed(function() { var adapter = get(this, 'adapter'); if (typeof adapter === 'string') { adapter = get(this, adapter, false) || get(Ember.lookup, adapter); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create(); } return adapter; }).property('adapter'), /** @private A monotonically increasing number to be used to uniquely identify data and records. It starts at 1 so other parts of the code can test for truthiness when provided a `clientId` instead of having to explicitly test for undefined. */ clientIdCounter: 1, // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. Note: The third `transaction` property is for internal use only. If you want to create a record inside of a given transaction, use `transaction.createRecord()` instead of `store.createRecord()`. @param {subclass of DS.Model} type @param {Object} properties a hash of properties to set on the newly created record. @returns DS.Model */ createRecord: function(type, properties, transaction) { properties = properties || {}; // Create a new instance of the model `type` and put it // into the specified `transaction`. If no transaction is // specified, the default transaction will be used. var record = type._create({ store: this }); transaction = transaction || get(this, 'defaultTransaction'); // adoptRecord is an internal API that allows records to move // into a transaction without assertions designed for app // code. It is used here to ensure that regardless of new // restrictions on the use of the public `transaction.add()` // API, we will always be able to insert new records into // their transaction. transaction.adoptRecord(record); // `id` is a special property that may not be a `DS.attr` var id = properties.id; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. var adapter; if (Ember.isNone(id)) { adapter = this.adapterForType(type); if (adapter && adapter.generateIdForRecord) { id = coerceId(adapter.generateIdForRecord(this, record)); properties.id = id; } } id = coerceId(id); // Create a new `clientId` and associate it with the // specified (or generated) `id`. Since we don't have // any data for the server yet (by definition), store // the sentinel value CREATED as the data for this // clientId. If we see this value later, we will skip // materialization. var clientId = this.pushData(CREATED, id, type); // Now that we have a clientId, attach it to the record we // just created. set(record, 'clientId', clientId); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Make sure the data is set up so the record doesn't // try to materialize its nonexistent data. record.setupData(); // Store the record we just created in the record cache for // this clientId. this.recordCache[clientId] = record; // Set the properties specified on the record. record.setProperties(properties); // Resolve record promise Ember.run(record, 'resolve', record); return record; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is always a subclass of `DS.Model`. You can use the `find` method on a subclass of `DS.Model` directly if your application only has one store. For example, instead of `store.find(App.Person, 1)`, you could say `App.Person.find(1)`. --- To find a record by ID, pass the `id` as the second parameter: store.find(App.Person, 1); App.Person.find(1); If the record with that `id` had not previously been loaded, the store will return an empty record immediately and ask the adapter to find the data by calling the adapter's `find` method. The `find` method will always return the same object for a given type and `id`. To check whether the adapter has populated a record, you can check its `isLoaded` property. --- To find all records for a type, call `find` with no additional parameters: store.find(App.Person); App.Person.find(); This will return a `RecordArray` representing all known records for the given type and kick off a request to the adapter's `findAll` method to load any additional records for the type. The `RecordArray` returned by `find()` is live. If any more records for the type are added at a later time through any mechanism, it will automatically update to reflect the change. --- To find a record by a query, call `find` with a hash as the second parameter: store.find(App.Person, { page: 1 }); App.Person.find({ page: 1 }); This will return a `RecordArray` immediately, but it will always be an empty `RecordArray` at first. It will call the adapter's `findQuery` method, which will populate the `RecordArray` once the server has returned results. You can check whether a query results `RecordArray` has loaded by checking its `isLoaded` property. */ find: function(type, id) { if (id === undefined) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id)); }, /** @private This method returns a record for a given type and id combination. If the store has never seen this combination of type and id before, it creates a new `clientId` with the LOADING sentinel and asks the adapter to load the data. If the store has seen the combination, this method delegates to `getByReference`. */ findById: function(type, id) { var clientId = this.typeMapFor(type).idToCid[id]; if (clientId) { return this.findByClientId(type, clientId); } clientId = this.pushData(LOADING, id, type); // create a new instance of the model type in the // 'isLoading' state var record = this.materializeRecord(type, clientId, id); // let the adapter set the data, possibly async var adapter = this.adapterForType(type); Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to find a record but your adapter does not implement `find`", adapter.find); adapter.find(this, type, id); return record; }, reloadRecord: function(record) { var type = record.constructor, adapter = this.adapterForType(type), id = get(record, 'id'); Ember.assert("You cannot update a record without an ID", id); Ember.assert("You tried to update a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to update a record but your adapter does not implement `find`", adapter.find); adapter.find(this, type, id); }, /** @private This method returns a record for a given clientId. If there is no record object yet for the clientId, this method materializes a new record object. This allows adapters to eagerly load large amounts of data into the store, and avoid incurring the cost to create the objects until they are requested. Several parts of Ember Data call this method: * findById, if a clientId already exists for a given type and id combination * OneToManyChange, which is backed by clientIds, when getChild, getOldParent or getNewParent are called * RecordArray, which is backed by clientIds, when an object at a particular index is looked up In short, it's a convenient way to get a record for a known clientId, materializing it if necessary. @param {Class} type @param {Number|String} clientId */ findByClientId: function(type, clientId) { var cidToData, record, id; record = this.recordCache[clientId]; if (!record) { // create a new instance of the model type in the // 'isLoading' state id = this.clientIdToId[clientId]; record = this.materializeRecord(type, clientId, id); cidToData = this.clientIdToData; if (typeof cidToData[clientId] === 'object') { record.loadedData(); } } return record; }, /** @private Given an array of `reference`s, determines which of those `clientId`s has not yet been loaded. In preparation for loading, this method also marks any unloaded `clientId`s as loading. */ neededReferences: function(references) { var neededReferences = [], cidToData = this.clientIdToData, reference; for (var i=0, l=references.length; i<l; i++) { reference = references[i]; if (cidToData[reference.clientId] === UNLOADED) { neededReferences.push(reference); cidToData[reference.clientId] = LOADING; } } return neededReferences; }, /** @private This method is the entry point that relationships use to update themselves when their underlying data changes. First, it determines which of its `reference`s are still unloaded, then invokes `findMany` on the adapter. */ fetchUnloadedReferences: function(references, owner) { var neededReferences = this.neededReferences(references); this.fetchMany(neededReferences, owner); }, /** @private This method takes a list of `reference`s, group the `reference`s by type, converts the `reference`s into IDs, and then invokes the adapter's `findMany` method. The `reference`s are grouped by type to invoke `findMany` on adapters for each unique type in `reference`s. It is used both by a brand new relationship (via the `findMany` method) or when the data underlying an existing relationship changes (via the `fetchUnloadedReferences` method). */ fetchMany: function(references, owner) { if (!references.length) { return; } // Group By Type var referencesByTypeMap = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); forEach(references, function(reference) { referencesByTypeMap.get(reference.type).push(reference); }); forEach(referencesByTypeMap, function(type) { var references = referencesByTypeMap.get(type), ids = map(references, function(reference) { return reference.id; }); var adapter = this.adapterForType(type); Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany); adapter.findMany(this, type, ids, owner); }, this); }, referenceForId: function(type, id) { var clientId = this.clientIdForId(type, id); return this.referenceForClientId(clientId); }, referenceForClientId: function(clientId) { var references = this.recordReferences; if (references[clientId]) { return references[clientId]; } var type = this.clientIdToType[clientId]; return references[clientId] = { id: this.idForClientId(clientId), clientId: clientId, type: type }; }, isReferenceMaterialized: function(reference) { return !!this.recordCache[reference.clientId]; }, recordForReference: function(reference) { return this.findByClientId(reference.type, reference.clientId); }, /** @private `findMany` is the entry point that relationships use to generate a new `ManyArray` for the list of IDs specified by the server for the relationship. Its responsibilities are: * convert the IDs into clientIds * determine which of the clientIds still need to be loaded * create a new ManyArray whose content is *all* of the clientIds * notify the ManyArray of the number of its elements that are already loaded * insert the unloaded clientIds into the `loadingRecordArrays` bookkeeping structure, which will allow the `ManyArray` to know when all of its loading elements are loaded from the server. * ask the adapter to load the unloaded elements, by invoking findMany with the still-unloaded IDs. */ findMany: function(type, idsOrReferencesOrOpaque, record, relationship) { // 1. Determine which of the client ids need to be loaded // 2. Create a new ManyArray whose content is ALL of the clientIds // 3. Decrement the ManyArray's counter by the number of loaded clientIds // 4. Put the ManyArray into our bookkeeping data structure, keyed on // the needed clientIds // 5. Ask the adapter to load the records for the unloaded clientIds (but // convert them back to ids) if (!Ember.isArray(idsOrReferencesOrOpaque)) { var adapter = this.adapterForType(type); if (adapter && adapter.findHasMany) { adapter.findHasMany(this, record, relationship, idsOrReferencesOrOpaque); } else if (idsOrReferencesOrOpaque !== undefined) { Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load many records but your adapter does not implement `findHasMany`", adapter.findHasMany); } return this.createManyArray(type, Ember.A()); } // Coerce server IDs into Record Reference var references = map(idsOrReferencesOrOpaque, function(reference) { if (typeof reference !== 'object' && reference !== null) { return this.referenceForId(type, reference); } return reference; }, this); var neededReferences = this.neededReferences(references), manyArray = this.createManyArray(type, Ember.A(references)), loadingRecordArrays = this.loadingRecordArrays, reference, clientId, i, l; // Start the decrementing counter on the ManyArray at the number of // records we need to load from the adapter manyArray.loadingRecordsCount(neededReferences.length); if (neededReferences.length) { for (i=0, l=neededReferences.length; i<l; i++) { reference = neededReferences[i]; clientId = reference.clientId; // keep track of the record arrays that a given loading record // is part of. This way, if the same record is in multiple // ManyArrays, all of their loading records counters will be // decremented when the adapter provides the data. if (loadingRecordArrays[clientId]) { loadingRecordArrays[clientId].push(manyArray); } else { this.loadingRecordArrays[clientId] = [ manyArray ]; } } this.fetchMany(neededReferences, record); } else { // all requested records are available manyArray.set('isLoaded', true); Ember.run.once(function() { manyArray.trigger('didLoad'); }); } return manyArray; }, /** @private This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. @param {Class} type @param {Object} query an opaque query to be used by the adapter @return {DS.AdapterPopulatedRecordArray} */ findQuery: function(type, query) { var array = DS.AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A([]), store: this }); var adapter = this.adapterForType(type); Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery); adapter.findQuery(this, type, query, array); return array; }, /** @private This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @param {Class} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(type) { return this.fetchAll(type, this.all(type)); }, /** @private */ fetchAll: function(type, array) { var adapter = this.adapterForType(type), sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll); adapter.findAll(this, type, sinceToken); return array; }, /** */ metaForType: function(type, property, data) { var target = this.typeMapFor(type).metadata; set(target, property, data); }, /** */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. @param {Class} type @return {DS.RecordArray} */ all: function(type) { var typeMap = this.typeMapFor(type), findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = DS.RecordArray.create({ type: type, content: Ember.A([]), store: this, isLoaded: true }); this.registerRecordArray(array, type); typeMap.findAllCache = array; return array; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Note that the existence of a filter on a type will trigger immediate materialization of all loaded data for a given type, so you might not want to use filters for a type if you are loading many records into the store, many of which are not active at any given time. In this scenario, you might want to consider filtering the raw data before loading it into the store. @param {Class} type @param {Function} filter @return {DS.FilteredRecordArray} */ filter: function(type, query, filter) { // allow an optional server query if (arguments.length === 3) { this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } var array = DS.FilteredRecordArray.create({ type: type, content: Ember.A([]), store: this, filterFunction: filter }); this.registerRecordArray(array, type, filter); return array; }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. @param {Class} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { return !Ember.isNone(this.typeMapFor(type).idToCid[id]); }, // ............ // . UPDATING . // ............ /** @private If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @param {Class} type @param {Number|String} clientId @param {DS.Model} record */ dataWasUpdated: function(type, reference, record) { // Because data updates are invoked at the end of the run loop, // it is possible that a record might be deleted after its data // has been modified and this method was scheduled to be called. // // If that's the case, the record would have already been removed // from all record arrays; calling updateRecordArrays would just // add it back. If the record is deleted, just bail. It shouldn't // give us any more trouble after this. if (get(record, 'isDeleted')) { return; } var cidToData = this.clientIdToData, clientId = reference.clientId, data = cidToData[clientId]; if (typeof data === "object") { this.updateRecordArrays(type, clientId); } }, // ................. // . BASIC ADAPTER . // ................. scheduleSave: function(record) { this._recordsToSave.add(record); Ember.run.once(this, 'flushSavedRecords'); }, flushSavedRecords: function() { var created = Ember.OrderedSet.create(); var updated = Ember.OrderedSet.create(); var deleted = Ember.OrderedSet.create(); this._recordsToSave.forEach(function(record) { if (get(record, 'isNew')) { created.add(record); } else if (get(record, 'isDeleted')) { deleted.add(record); } else { updated.add(record); } }); this._recordsToSave.clear(); get(this, '_adapter').commit(this, { created: created, updated: updated, deleted: deleted }); }, // .............. // . PERSISTING . // .............. /** This method delegates committing to the store's implicit transaction. Calling this method is essentially a request to persist any changes to records that were not explicitly added to a transaction. */ commit: function() { get(this, 'defaultTransaction').commit(); }, /** Adapters should call this method if they would like to acknowledge that all changes related to a record (other than relationship changes) have persisted. Because relationship changes affect multiple records, the adapter is responsible for acknowledging the change to the relationship directly (using `store.didUpdateRelationship`) when all aspects of the relationship change have persisted. It can be called for created, deleted or updated records. If the adapter supplies new data, that data will become the new canonical data for the record. That will result in blowing away all local changes and rematerializing the record with the new data (the "sledgehammer" approach). Alternatively, if the adapter does not supply new data, the record will collapse all local changes into its saved data. Subsequent rollbacks of the record will roll back to this point. If an adapter is acknowledging receipt of a newly created record that did not generate an id in the client, it *must* either provide data or explicitly invoke `store.didReceiveId` with the server-provided id. Note that an adapter may not supply new data when acknowledging a deleted record. @see DS.Store#didUpdateRelationship @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { record.adapterDidCommit(); if (data) { this.updateId(record, data); this.updateRecordData(record, data); } else { this.didUpdateAttributes(record); } }, /** For convenience, if an adapter is performing a bulk commit, it can also acknowledge all of the records at once. If the adapter supplies an array of data, they must be in the same order as the array of records passed in as the first parameter. @param {#forEach} list a list of records whose changes the adapter is acknowledging. You can pass any object that has an ES5-like `forEach` method, including the `OrderedSet` objects passed into the adapter at commit time. @param {Array[Object]} dataList an Array of data. This parameter must be an integer-indexed Array-like. */ didSaveRecords: function(list, dataList) { var i = 0; list.forEach(function(record) { this.didSaveRecord(record, dataList && dataList[i++]); }, this); }, /** This method allows the adapter to specify that a record could not be saved because it had backend-supplied validation errors. The errors object must have keys that correspond to the attribute names. Once each of the specified attributes have changed, the record will automatically move out of the invalid state and be ready to commit again. TODO: We should probably automate the process of converting server names to attribute names using the existing serializer infrastructure. @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method allows the adapter to specify that a record could not be saved because the server returned an unhandled error. @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** This is a lower-level API than `didSaveRecord` that allows an adapter to acknowledge the persistence of a single attribute. This is useful if an adapter needs to make multiple asynchronous calls to fully persist a record. The record will keep track of which attributes and relationships are still outstanding and automatically move into the `saved` state once the adapter has acknowledged everything. If a value is provided, it clobbers the locally specified value. Otherwise, the local value becomes the record's last known saved value (which is used when rolling back a record). Note that the specified attributeName is the normalized name specified in the definition of the `DS.Model`, not a key in the server-provided data. Also note that the adapter is responsible for performing any transformations on the value using the serializer API. @param {DS.Model} record @param {String} attributeName @param {Object} value */ didUpdateAttribute: function(record, attributeName, value) { record.adapterDidUpdateAttribute(attributeName, value); }, /** This method allows an adapter to acknowledge persistence of all attributes of a record but not relationships or other factors. It loops through the record's defined attributes and notifies the record that they are all acknowledged. This method does not take optional values, because the adapter is unlikely to have a hash of normalized keys and transformed values, and instead of building one up, it should just call `didUpdateAttribute` as needed. This method is intended as a middle-ground between `didSaveRecord`, which acknowledges all changes to a record, and `didUpdateAttribute`, which allows an adapter fine-grained control over updates. @param {DS.Model} record */ didUpdateAttributes: function(record) { record.eachAttribute(function(attributeName) { this.didUpdateAttribute(record, attributeName); }, this); }, /** This allows an adapter to acknowledge that it has saved all necessary aspects of a relationship change. This is separated from acknowledging the record itself (via `didSaveRecord`) because a relationship change can involve as many as three separate records. Records should only move out of the in-flight state once the server has acknowledged all of their relationships, and this differs based upon the adapter's semantics. There are three basic scenarios by which an adapter can save a relationship. ### Foreign Key An adapter can save all relationship changes by updating a foreign key on the child record. If it does this, it should acknowledge the changes when the child record is saved. record.eachRelationship(function(name, meta) { if (meta.kind === 'belongsTo') { store.didUpdateRelationship(record, name); } }); store.didSaveRecord(record, data); ### Embedded in Parent An adapter can save one-to-many relationships by embedding IDs (or records) in the parent object. In this case, the relationship is not considered acknowledged until both the old parent and new parent have acknowledged the change. In this case, the adapter should keep track of the old parent and new parent, and acknowledge the relationship change once both have acknowledged. If one of the two sides does not exist (e.g. the new parent does not exist because of nulling out the belongs-to relationship), the adapter should acknowledge the relationship once the other side has acknowledged. ### Separate Entity An adapter can save relationships as separate entities on the server. In this case, they should acknowledge the relationship as saved once the server has acknowledged the entity. @see DS.Store#didSaveRecord @param {DS.Model} record @param {DS.Model} relationshipName */ didUpdateRelationship: function(record, relationshipName) { var relationship = this.relationshipChangeFor(get(record, 'clientId'), relationshipName); //TODO(Igor) if (relationship) { relationship.adapterDidUpdate(); } }, /** This allows an adapter to acknowledge all relationship changes for a given record. Like `didUpdateAttributes`, this is intended as a middle ground between `didSaveRecord` and fine-grained control via the `didUpdateRelationship` API. */ didUpdateRelationships: function(record) { var changes = this.relationshipChangesFor(get(record, '_reference')); for (var name in changes) { if (!changes.hasOwnProperty(name)) { continue; } changes[name].adapterDidUpdate(); } }, /** When acknowledging the creation of a locally created record, adapters must supply an id (if they did not implement `generateIdForRecord` to generate an id locally). If an adapter does not use `didSaveRecord` and supply a hash (for example, if it needs to make multiple HTTP requests to create and then update the record), it will need to invoke `didReceiveId` with the backend-supplied id. When not using `didSaveRecord`, an adapter will need to invoke: * didReceiveId (unless the id was generated locally) * didCreateRecord * didUpdateAttribute(s) * didUpdateRelationship(s) @param {DS.Model} record @param {Number|String} id */ didReceiveId: function(record, id) { var typeMap = this.typeMapFor(record.constructor), clientId = get(record, 'clientId'), oldId = get(record, 'id'); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === undefined || id === oldId); typeMap.idToCid[id] = clientId; this.clientIdToId[clientId] = id; }, /** @private This method re-indexes the data by its clientId in the store and then notifies the record that it should rematerialize itself. @param {DS.Model} record @param {Object} data */ updateRecordData: function(record, data) { var clientId = get(record, 'clientId'), cidToData = this.clientIdToData; cidToData[clientId] = data; record.didChangeData(); }, /** @private If an adapter invokes `didSaveRecord` with data, this method extracts the id from the supplied data (using the adapter's `extractId()` method) and indexes the clientId with that id. @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var typeMap = this.typeMapFor(record.constructor), clientId = get(record, 'clientId'), oldId = get(record, 'id'), type = record.constructor, id = this.preprocessData(type, data); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); typeMap.idToCid[id] = clientId; this.clientIdToId[clientId] = id; this.referenceForClientId(clientId).id = id; }, /** @private This method receives opaque data provided by the adapter and preprocesses it, returning an ID. The actual preprocessing takes place in the adapter. If you would like to change the default behavior, you should override the appropriate hooks in `DS.Serializer`. @see {DS.Serializer} @return {String} id the id represented by the data */ preprocessData: function(type, data) { return this.adapterForType(type).extractId(type, data); }, // ................. // . RECORD ARRAYS . // ................. /** @private Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerRecordArray: function(array, type, filter) { var recordArrays = this.typeMapFor(type).recordArrays; recordArrays.push(array); this.updateRecordArrayFilter(array, type, filter); }, /** @private Create a `DS.ManyArray` for a type and list of clientIds and index the `ManyArray` under each clientId. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @param {Class} type @param {Array} clientIds @return {DS.ManyArray} */ createManyArray: function(type, clientIds) { var array = DS.ManyArray.create({ type: type, content: clientIds, store: this }); clientIds.forEach(function(clientId) { var recordArrays = this.recordArraysForClientId(clientId); recordArrays.add(array); }, this); return array; }, /** @private This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. */ updateRecordArrayFilter: function(array, type, filter) { var typeMap = this.typeMapFor(type), cidToData = this.clientIdToData, clientIds = typeMap.clientIds, clientId, data, shouldFilter, record; for (var i=0, l=clientIds.length; i<l; i++) { clientId = clientIds[i]; shouldFilter = false; data = cidToData[clientId]; if (typeof data === 'object') { if (record = this.recordCache[clientId]) { if (!get(record, 'isDeleted')) { shouldFilter = true; } } else { shouldFilter = true; } if (shouldFilter) { this.updateRecordArray(array, filter, type, clientId); } } } }, updateRecordArraysLater: function(type, clientId) { Ember.run.once(this, function() { this.updateRecordArrays(type, clientId); }); }, /** @private This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when an attribute changes on a record. It updates all filters that a record belongs to. To avoid thrashing, it only runs once per run loop per record. @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function(type, clientId) { var recordArrays = this.typeMapFor(type).recordArrays, filter; recordArrays.forEach(function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, clientId); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = this.loadingRecordArrays[clientId]; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } this.loadingRecordArrays[clientId] = null; } }, /** @private Update an individual filter. @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, clientId) { var shouldBeInArray, record; if (!filter) { shouldBeInArray = true; } else { record = this.findByClientId(type, clientId); shouldBeInArray = filter(record); } var content = get(array, 'content'); var recordArrays = this.recordArraysForClientId(clientId); var reference = this.referenceForClientId(clientId); if (shouldBeInArray) { recordArrays.add(array); array.addReference(reference); } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeReference(reference); } }, /** @private When a record is deleted, it is removed from all its record arrays. @param {DS.Model} record */ removeFromRecordArrays: function(record) { var reference = get(record, '_reference'); var recordArrays = this.recordArraysForClientId(reference.clientId); recordArrays.forEach(function(array) { array.removeReference(reference); }); }, // ............ // . INDEXING . // ............ /** @private Return a list of all `DS.RecordArray`s a clientId is part of. @return {Object(clientId: Ember.OrderedSet)} */ recordArraysForClientId: function(clientId) { var recordArrays = get(this, 'recordArraysByClientId'); var ret = recordArrays[clientId]; if (!ret) { ret = recordArrays[clientId] = Ember.OrderedSet.create(); } return ret; }, typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'); var guidForType = Ember.guidFor(type); var typeMap = typeMaps[guidForType]; if (typeMap) { return typeMap; } else { return (typeMaps[guidForType] = { idToCid: {}, clientIds: [], recordArrays: [], metadata: {} }); } }, /** @private For a given type and id combination, returns the client id used by the store. If no client id has been assigned yet, one will be created and returned. @param {DS.Model} type @param {String|Number} id */ clientIdForId: function(type, id) { id = coerceId(id); var clientId = this.typeMapFor(type).idToCid[id]; if (clientId !== undefined) { return clientId; } return this.pushData(UNLOADED, id, type); }, /** @private This method works exactly like `clientIdForId`, but does not require looking up the `typeMap` for every `clientId` and invoking a method per `clientId`. */ clientIdsForIds: function(type, ids) { var typeMap = this.typeMapFor(type), idToClientIdMap = typeMap.idToCid; return map(ids, function(id) { id = coerceId(id); var clientId = idToClientIdMap[id]; if (clientId) { return clientId; } return this.pushData(UNLOADED, id, type); }, this); }, typeForClientId: function(clientId) { return this.clientIdToType[clientId]; }, idForClientId: function(clientId) { return this.clientIdToId[clientId]; }, // ................ // . LOADING DATA . // ................ /** Load new data into the store for a given id and type combination. If data for that record had been loaded previously, the new information overwrites the old. If the record you are loading data for has outstanding changes that have not yet been saved, an exception will be thrown. @param {DS.Model} type @param {String|Number} id @param {Object} data the data to load */ load: function(type, data, prematerialized) { var id; if (typeof data === 'number' || typeof data === 'string') { id = data; data = prematerialized; prematerialized = null; } if (prematerialized && prematerialized.id) { id = prematerialized.id; } else if (id === undefined) { id = this.preprocessData(type, data); } id = coerceId(id); var typeMap = this.typeMapFor(type), clientId = typeMap.idToCid[id], cidToPrematerialized = this.clientIdToPrematerializedData; if (clientId !== undefined) { this.loadData(data, clientId, type); cidToPrematerialized[clientId] = prematerialized; var record = this.recordCache[clientId]; if (record) { once(record, 'loadedData'); } } else { clientId = this.pushData(data, id, type); cidToPrematerialized[clientId] = prematerialized; } this.updateRecordArraysLater(type, clientId); return this.referenceForClientId(clientId); }, prematerialize: function(reference, prematerialized) { this.clientIdToPrematerializedData[reference.clientId] = prematerialized; }, loadMany: function(type, ids, dataList) { if (dataList === undefined) { dataList = ids; ids = map(dataList, function(data) { return this.preprocessData(type, data); }, this); } return map(ids, function(id, i) { return this.load(type, id, dataList[i]); }, this); }, loadHasMany: function(record, key, ids) { //It looks sad to have to do the conversion in the store var type = record.get(key + '.type'), tuples = map(ids, function(id) { return {id: id, type: type}; }); record.materializeHasMany(key, tuples); // Update any existing many arrays that use the previous IDs, // if necessary. record.hasManyDidChange(key); var relationship = record.cacheFor(key); // TODO (tomdale) this assumes that loadHasMany *always* means // that the records for the provided IDs are loaded. if (relationship) { set(relationship, 'isLoaded', true); relationship.trigger('didLoad'); } }, loadData: function(data, clientId, type){ var cidToData = this.clientIdToData; cidToData[clientId] = data; }, /** @private Stores data for the specified type and id combination and returns the client id. @param {Object} data @param {String|Number} id @param {DS.Model} type @returns {Number} */ pushData: function(data, id, type) { var typeMap = this.typeMapFor(type); var idToClientIdMap = typeMap.idToCid, clientIdToIdMap = this.clientIdToId, clientIdToTypeMap = this.clientIdToType, clientIds = typeMap.clientIds, cidToData = this.clientIdToData; Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToClientIdMap[id]); var clientId = ++this.clientIdCounter; this.loadData(data, clientId, type); clientIdToTypeMap[clientId] = type; // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToClientIdMap[id] = clientId; clientIdToIdMap[clientId] = id; } clientIds.push(clientId); return clientId; }, // .......................... // . RECORD MATERIALIZATION . // .......................... materializeRecord: function(type, clientId, id) { var record; this.recordCache[clientId] = record = type._create({ store: this, clientId: clientId }); set(record, 'id', id); get(this, 'defaultTransaction').adoptRecord(record); record.loadingData(); return record; }, dematerializeRecord: function(record) { var id = get(record, 'id'), clientId = get(record, 'clientId'), type = this.typeForClientId(clientId), typeMap = this.typeMapFor(type); record.updateRecordArrays(); delete this.recordCache[clientId]; delete this.clientIdToId[clientId]; delete this.clientIdToType[clientId]; delete this.clientIdToData[clientId]; delete this.recordArraysByClientId[clientId]; if (id) { delete typeMap.idToCid[id]; } }, willDestroy: function() { if (get(DS, 'defaultStore') === this) { set(DS, 'defaultStore', null); } }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, change) { var clientId = clientReference.clientId, parentClientId = parentReference ? parentReference.clientId : parentReference; var key = childKey + parentKey; var changes = this.relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientReference, childKey, parentReference, parentKey, type) { var clientId = clientReference.clientId, parentClientId = parentReference ? parentReference.clientId : parentReference; var changes = this.relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangeFor: function(clientId, childKey, parentClientId, parentKey, type) { var changes = this.relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId])){ return; } if(type){ return changes[clientId][parentClientId][key][type]; } else{ //TODO(Igor) what if both present return changes[clientId][parentClientId][key]["add"] || changes[clientId][parentClientId][key]["remove"]; } }, relationshipChangePairsFor: function(reference){ var toReturn = []; if( !reference ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this.relationshipChanges[reference.clientId]; for (var objKey in changesObject){ if(changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if(changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, relationshipChangesFor: function(reference) { var toReturn = []; if( !reference ) { return toReturn; } var relationshipPairs = this.relationshipChangePairsFor(reference); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange){ toReturn.push(addedChange); } if(removedChange){ toReturn.push(removedChange); } }); return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... adapterForType: function(type) { this._adaptersMap = this.createInstanceMapFor('adapters'); var adapter = this._adaptersMap.get(type); if (adapter) { return adapter; } return this.get('_adapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. recordAttributeDidChange: function(reference, attributeName, newValue, oldValue) { var record = this.recordForReference(reference), dirtySet = new Ember.OrderedSet(), adapter = this.adapterForType(record.constructor); if (adapter.dirtyRecordsForAttributeChange) { adapter.dirtyRecordsForAttributeChange(dirtySet, record, attributeName, newValue, oldValue); } dirtySet.forEach(function(record) { record.adapterDidDirty(); }); }, recordBelongsToDidChange: function(dirtySet, child, relationship) { var adapter = this.adapterForType(child.constructor); if (adapter.dirtyRecordsForBelongsToChange) { adapter.dirtyRecordsForBelongsToChange(dirtySet, child, relationship); } // adapterDidDirty is called by the RelationshipChange that created // the dirtySet. }, recordHasManyDidChange: function(dirtySet, parent, relationship) { var adapter = this.adapterForType(parent.constructor); if (adapter.dirtyRecordsForHasManyChange) { adapter.dirtyRecordsForHasManyChange(dirtySet, parent, relationship); } // adapterDidDirty is called by the RelationshipChange that created // the dirtySet. } }); DS.Store.reopenClass({ registerAdapter: DS._Mappable.generateMapFunctionFor('adapters', function(type, adapter, map) { map.set(type, adapter); }), transformMapKey: function(key) { if (typeof key === 'string') { var transformedKey; transformedKey = get(Ember.lookup, key); Ember.assert("Could not find model at path " + key, transformedKey); return transformedKey; } else { return key; } }, transformMapValue: function(key, value) { if (Ember.Object.detect(value)) { return value.create(); } return value; } }); })(); (function() { var get = Ember.get, set = Ember.set, once = Ember.run.once, arrayMap = Ember.ArrayPolyfills.map; /** This file encapsulates the various states that a record can transition through during its lifecycle. ### State Manager A record's state manager explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `updated.inFlight` state. (These state paths will be explained in more detail below.) Events are sent by the record or its store to the record's state manager. How the state manager reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical. For example, a record can be in the `deleted.start` state, then transition into the `deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting its manager's current state path: record.get('stateManager.currentPath'); //=> "created.uncommitted" The `DS.Model` states are themselves stateless. What we mean is that, though each instance of a record also has a unique instance of a `DS.StateManager`, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each state manager points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass a reference to the current state manager as the first parameter to every method invoked on a state. The state manager passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. If you need access to the record being acted on, you can retrieve the state manager's `record` property. For example, if you had an event handler `myEvent`: myEvent: function(manager) { var record = manager.get('record'); record.doSomething(); } For more information about state managers in general, see the Ember.js documentation on `Ember.StateManager`. ### Events, Flags, and Transitions A state may implement zero or more events, flags, or transitions. #### Events Events are named functions that are invoked when sent to a record. The state manager will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with "+param); } }) To trigger this event: record.send('myEvent', 'foo'); //=> "Received myEvent with foo" Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the state manager's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * start <-- currentState * inFlight * updated * inFlight If we are currently in the `start` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } You can say: if (record.get('isNew') && record.get('isSaving')) { doSomething(); } If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. #### Transitions Transitions are like event handlers but are called automatically upon entering or exiting a state. To implement a transition, just call a method either `enter` or `exit`: myState: DS.State.create({ // Gets called automatically when entering // this state. enter: function(manager) { console.log("Entered myState"); } }) Note that enter and exit events are called once per transition. If the current state changes, but changes to another child state of the parent, the transition event on the parent will not be triggered. */ var stateProperty = Ember.computed(function(key) { var parent = get(this, 'parentState'); if (parent) { return get(parent, key); } }).property(); var hasDefinedProperties = function(object) { for (var name in object) { if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; }; var didChangeData = function(manager) { var record = get(manager, 'record'); record.materializeData(); }; var willSetProperty = function(manager, context) { context.oldValue = get(get(manager, 'record'), context.name); var change = DS.AttributeChange.createChange(context); get(manager, 'record')._changesToSync[context.name] = change; }; var didSetProperty = function(manager, context) { var change = get(manager, 'record')._changesToSync[context.name]; change.value = get(get(manager, 'record'), context.name); change.sync(); }; DS.State = Ember.State.extend({ isLoaded: stateProperty, isReloading: stateProperty, isDirty: stateProperty, isSaving: stateProperty, isDeleted: stateProperty, isError: stateProperty, isNew: stateProperty, isValid: stateProperty, // For states that are substates of a // DirtyState (updated or created), it is // useful to be able to determine which // type of dirty state it is. dirtyType: stateProperty }); // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record's transaction has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: No client-side validations have failed and the // adapter did not report any server-side validation failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = DS.State.extend({ initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: DS.State.extend({ // TRANSITIONS enter: function(manager) { var dirtyType = get(this, 'dirtyType'), record = get(manager, 'record'); record.withTransaction(function (t) { t.recordBecameDirty(dirtyType, record); }); }, // EVENTS willSetProperty: willSetProperty, didSetProperty: didSetProperty, becomeDirty: Ember.K, willCommit: function(manager) { manager.transitionTo('inFlight'); }, becameClean: function(manager) { var record = get(manager, 'record'), dirtyType = get(this, 'dirtyType'); record.withTransaction(function(t) { t.recordBecameClean(dirtyType, record); }); manager.transitionTo('loaded.materializing'); }, becameInvalid: function(manager) { var dirtyType = get(this, 'dirtyType'), record = get(manager, 'record'); record.withTransaction(function (t) { t.recordBecameInFlight(dirtyType, record); }); manager.transitionTo('invalid'); }, rollback: function(manager) { get(manager, 'record').rollback(); } }), // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: DS.State.extend({ // FLAGS isSaving: true, // TRANSITIONS enter: function(manager) { var dirtyType = get(this, 'dirtyType'), record = get(manager, 'record'); record.becameInFlight(); record.withTransaction(function (t) { t.recordBecameInFlight(dirtyType, record); }); }, // EVENTS didCommit: function(manager) { var dirtyType = get(this, 'dirtyType'), record = get(manager, 'record'); record.withTransaction(function(t) { t.recordBecameClean('inflight', record); }); manager.transitionTo('saved'); manager.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(manager, errors) { var record = get(manager, 'record'); set(record, 'errors', errors); manager.transitionTo('invalid'); manager.send('invokeLifecycleCallbacks'); }, becameError: function(manager) { manager.transitionTo('error'); manager.send('invokeLifecycleCallbacks'); } }), // A record is in the `invalid` state when its client-side // invalidations have failed, or if the adapter has indicated // the the record failed server-side invalidations. invalid: DS.State.extend({ // FLAGS isValid: false, exit: function(manager) { var record = get(manager, 'record'); record.withTransaction(function (t) { t.recordBecameClean('inflight', record); }); }, // EVENTS deleteRecord: function(manager) { manager.transitionTo('deleted'); get(manager, 'record').clearRelationships(); }, willSetProperty: willSetProperty, didSetProperty: function(manager, context) { var record = get(manager, 'record'), errors = get(record, 'errors'), key = context.name; set(errors, key, null); if (!hasDefinedProperties(errors)) { manager.send('becameValid'); } didSetProperty(manager, context); }, becomeDirty: Ember.K, rollback: function(manager) { manager.send('becameValid'); manager.send('rollback'); }, becameValid: function(manager) { manager.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(manager) { var record = get(manager, 'record'); record.trigger('becameInvalid', record); } }) }); // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. var createdState = DirtyState.create({ dirtyType: 'created', // FLAGS isNew: true }); var updatedState = DirtyState.create({ dirtyType: 'updated' }); createdState.states.uncommitted.reopen({ deleteRecord: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.recordIsMoving('created', record); }); record.clearRelationships(); manager.transitionTo('deleted.saved'); } }); createdState.states.uncommitted.reopen({ rollback: function(manager) { this._super(manager); manager.transitionTo('deleted.saved'); } }); updatedState.states.uncommitted.reopen({ deleteRecord: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.recordIsMoving('updated', record); }); manager.transitionTo('deleted'); get(manager, 'record').clearRelationships(); } }); var states = { rootState: Ember.State.create({ // FLAGS isLoaded: false, isReloading: false, isDirty: false, isSaving: false, isDeleted: false, isError: false, isNew: false, isValid: true, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: DS.State.create({ // EVENTS loadingData: function(manager) { manager.transitionTo('loading'); }, loadedData: function(manager) { manager.transitionTo('loaded.created'); } }), // A record enters this state when the store askes // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: DS.State.create({ // EVENTS loadedData: didChangeData, materializingData: function(manager) { manager.transitionTo('loaded.materializing.firstTime'); } }), // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: DS.State.create({ initialState: 'saved', // FLAGS isLoaded: true, // SUBSTATES materializing: DS.State.create({ // EVENTS willSetProperty: Ember.K, didSetProperty: Ember.K, didChangeData: didChangeData, finishedMaterializing: function(manager) { manager.transitionTo('loaded.saved'); }, // SUBSTATES firstTime: DS.State.create({ // FLAGS isLoaded: false, exit: function(manager) { var record = get(manager, 'record'); once(function() { record.trigger('didLoad'); }); } }) }), reloading: DS.State.create({ // FLAGS isReloading: true, // TRANSITIONS enter: function(manager) { var record = get(manager, 'record'), store = get(record, 'store'); store.reloadRecord(record); }, exit: function(manager) { var record = get(manager, 'record'); once(record, 'trigger', 'didReload'); }, // EVENTS loadedData: didChangeData, materializingData: function(manager) { manager.transitionTo('loaded.materializing'); } }), // If there are no local changes to a record, it remains // in the `saved` state. saved: DS.State.create({ // EVENTS willSetProperty: willSetProperty, didSetProperty: didSetProperty, didChangeData: didChangeData, loadedData: didChangeData, reloadRecord: function(manager) { manager.transitionTo('loaded.reloading'); }, materializingData: function(manager) { manager.transitionTo('loaded.materializing'); }, becomeDirty: function(manager) { manager.transitionTo('updated'); }, deleteRecord: function(manager) { manager.transitionTo('deleted'); get(manager, 'record').clearRelationships(); }, unloadRecord: function(manager) { var record = get(manager, 'record'); // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.withTransaction(function(t) { t.recordIsMoving('updated', record); }); manager.transitionTo('deleted.saved'); }, invokeLifecycleCallbacks: function(manager, dirtyType) { var record = get(manager, 'record'); if (dirtyType === 'created') { record.trigger('didCreate', record); } else { record.trigger('didUpdate', record); } } }), // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }), // A record is in this state if it was deleted from the store. deleted: DS.State.create({ initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(manager) { var record = get(manager, 'record'), store = get(record, 'store'); store.removeFromRecordArrays(record); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record's // transaction starts to commit. uncommitted: DS.State.create({ // TRANSITIONS enter: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.recordBecameDirty('deleted', record); }); }, // EVENTS willCommit: function(manager) { manager.transitionTo('inFlight'); }, rollback: function(manager) { get(manager, 'record').rollback(); }, becomeDirty: Ember.K, becameClean: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.recordBecameClean('deleted', record); }); manager.transitionTo('loaded.materializing'); } }), // After a record's transaction is committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: DS.State.create({ // FLAGS isSaving: true, // TRANSITIONS enter: function(manager) { var record = get(manager, 'record'); record.becameInFlight(); record.withTransaction(function (t) { t.recordBecameInFlight('deleted', record); }); }, // EVENTS didCommit: function(manager) { var record = get(manager, 'record'); record.withTransaction(function(t) { t.recordBecameClean('inflight', record); }); manager.transitionTo('saved'); manager.send('invokeLifecycleCallbacks'); } }), // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: DS.State.create({ // FLAGS isDirty: false, setup: function(manager) { var record = get(manager, 'record'), store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(manager) { var record = get(manager, 'record'); record.trigger('didDelete', record); } }) }), // If the adapter indicates that there was an unknown // error saving a record, the record enters the `error` // state. error: DS.State.create({ isError: true, // EVENTS invokeLifecycleCallbacks: function(manager) { var record = get(manager, 'record'); record.trigger('becameError', record); } }) }) }; DS.StateManager = Ember.StateManager.extend({ record: null, initialState: 'rootState', states: states, unhandledEvent: function(manager, originalEvent) { var record = manager.get('record'), contexts = [].slice.call(arguments, 2), errorMessage; errorMessage = "Attempted to handle event `" + originalEvent + "` "; errorMessage += "on " + record.toString() + " while in state "; errorMessage += get(manager, 'currentState.path') + ". Called with "; errorMessage += arrayMap.call(contexts, function(context){ return Ember.inspect(context); }).join(', '); throw new Ember.Error(errorMessage); } }); })(); (function() { var LoadPromise = DS.LoadPromise; // system/mixins/load_promise var get = Ember.get, set = Ember.set, map = Ember.EnumerableUtils.map; var retrieveFromCurrentState = Ember.computed(function(key, value) { return get(get(this, 'stateManager.currentState'), key); }).property('stateManager.currentState').readOnly(); DS.Model = Ember.Object.extend(Ember.Evented, LoadPromise, { isLoaded: retrieveFromCurrentState, isReloading: retrieveFromCurrentState, isDirty: retrieveFromCurrentState, isSaving: retrieveFromCurrentState, isDeleted: retrieveFromCurrentState, isError: retrieveFromCurrentState, isNew: retrieveFromCurrentState, isValid: retrieveFromCurrentState, clientId: null, id: null, transaction: null, stateManager: null, errors: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. Available options: * `includeId`: `true` if the record's ID should be included in the JSON representation. @param {Object} options @returns {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, toJSON: function(options) { var serializer = DS.JSONSerializer.create(); return serializer.serialize(this, options); }, didLoad: Ember.K, didReload: Ember.K, didUpdate: Ember.K, didCreate: Ember.K, didDelete: Ember.K, becameInvalid: Ember.K, becameError: Ember.K, data: Ember.computed(function() { if (!this._data) { this.materializeData(); } return this._data; }).property(), materializeData: function() { this.send('materializingData'); get(this, 'store').materializeData(this); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, _data: null, init: function() { this._super(); var stateManager = DS.StateManager.create({ record: this }); set(this, 'stateManager', stateManager); this._setup(); stateManager.goToState('empty'); }, _setup: function() { this._relationshipChanges = {}; this._changesToSync = {}; }, send: function(name, context) { return get(this, 'stateManager').send(name, context); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, loadingData: function() { this.send('loadingData'); }, loadedData: function() { this.send('loadedData'); }, didChangeData: function() { this.send('didChangeData'); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). */ reload: function() { this.send('reloadRecord'); }, deleteRecord: function() { this.send('deleteRecord'); }, unloadRecord: function() { Ember.assert("You can only unload a loaded, non-dirty record.", !get(this, 'isDirty')); this.send('unloadRecord'); }, clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { this.clearHasMany(relationship); } }, this); }, updateRecordArrays: function() { var store = get(this, 'store'); if (store) { store.dataWasUpdated(this.constructor, get(this, '_reference'), this); } }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. */ adapterDidCommit: function() { var attributes = get(this, 'data').attributes; get(this.constructor, 'attributes').forEach(function(name, meta) { attributes[name] = get(this, name); }, this); this.send('didCommit'); this.updateRecordArraysLater(); }, adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); this.send('finishedMaterializing'); }, 'data'), hasManyDidChange: function(key) { var cachedValue = this.cacheFor(key); if (cachedValue) { var type = get(this.constructor, 'relationshipsByName').get(key).type; var store = get(this, 'store'); var ids = this._data.hasMany[key] || []; var references = map(ids, function(id) { if (typeof id === 'object') { if( id.clientId ) { // if it was already a reference, return the reference return id; } else { // <id, type> tuple for a polymorphic association. return store.referenceForId(id.type, id.id); } } return store.referenceForId(type, id); }); set(cachedValue, 'content', Ember.A(references)); } }, updateRecordArraysLater: function() { Ember.run.once(this, this.updateRecordArrays); }, setupData: function(prematerialized) { this._data = { attributes: {}, belongsTo: {}, hasMany: {}, id: null }; }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes); this._data.attributes = attributes; }, materializeAttribute: function(name, value) { this._data.attributes[name] = value; }, materializeHasMany: function(name, tuplesOrReferencesOrOpaque) { var tuplesOrReferencesOrOpaqueType = typeof tuplesOrReferencesOrOpaque; if (tuplesOrReferencesOrOpaque && tuplesOrReferencesOrOpaqueType !== 'string' && tuplesOrReferencesOrOpaque.length > 1) { Ember.assert('materializeHasMany expects tuples, references or opaque token, not ' + tuplesOrReferencesOrOpaque[0], tuplesOrReferencesOrOpaque[0].hasOwnProperty('id') && tuplesOrReferencesOrOpaque[0].type); } if( tuplesOrReferencesOrOpaqueType === "string" ) { this._data.hasMany[name] = tuplesOrReferencesOrOpaque; } else { var references = tuplesOrReferencesOrOpaque; if (tuplesOrReferencesOrOpaque && Ember.isArray(tuplesOrReferencesOrOpaque)) { references = this._convertTuplesToReferences(tuplesOrReferencesOrOpaque); } this._data.hasMany[name] = references; } }, materializeBelongsTo: function(name, tupleOrReference) { if (tupleOrReference) { Ember.assert('materializeBelongsTo expects a tuple or a reference, not a ' + tupleOrReference, !tupleOrReference || (tupleOrReference.hasOwnProperty('id') && tupleOrReference.hasOwnProperty('type'))); } this._data.belongsTo[name] = tupleOrReference; }, _convertTuplesToReferences: function(tuplesOrReferences) { return map(tuplesOrReferences, function(tupleOrReference) { return this._convertTupleToReference(tupleOrReference); }, this); }, _convertTupleToReference: function(tupleOrReference) { var store = get(this, 'store'); if(tupleOrReference.clientId) { return tupleOrReference; } else { return store.referenceForId(tupleOrReference.type, tupleOrReference.id); } }, rollback: function() { this._setup(); this.send('becameClean'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** @private The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, becameInFlight: function() { }, // FOR USE BY THE BASIC ADAPTER save: function() { this.get('store').scheduleSave(this); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { get(this, 'data.attributes')[attributeName] = value; this.notifyPropertyChange(attributeName); } else { value = get(this, attributeName); get(this, 'data.attributes')[attributeName] = value; } this.updateRecordArraysLater(); }, _reference: Ember.computed(function() { return get(this, 'store').referenceForClientId(get(this, 'clientId')); }), adapterDidInvalidate: function(errors) { this.send('becameInvalid', errors); }, adapterDidError: function() { this.send('becameError'); }, /** @private Override the default event firing from Ember.Evented to also call methods with the given name. */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); } }); // Helper function to generate store aliases. // This returns a function that invokes the named alias // on the default store, but injects the class as the // first parameter. var storeAlias = function(methodName) { return function() { var store = get(DS, 'defaultStore'), args = [].slice.call(arguments); args.unshift(this); Ember.assert("Your application does not have a 'Store' property defined. Attempts to call '" + methodName + "' on model classes will fail. Please provide one as with 'YourAppName.Store = DS.Store.extend()'", !!store); return store[methodName].apply(store, args); }; }; DS.Model.reopenClass({ isLoaded: storeAlias('recordIsLoaded'), find: storeAlias('find'), all: storeAlias('all'), query: storeAlias('findQuery'), filter: storeAlias('filter'), _create: DS.Model.create, create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `createRecord` with the attributes you would like to set."); }, createRecord: storeAlias('createRecord') }); })(); (function() { var get = Ember.get; DS.Model.reopenClass({ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }) }); var AttributeChange = DS.AttributeChange = function(options) { this.reference = options.reference; this.store = options.store; this.name = options.name; this.oldValue = options.oldValue; }; AttributeChange.createChange = function(options) { return new AttributeChange(options); }; AttributeChange.prototype = { sync: function() { this.store.recordAttributeDidChange(this.reference, this.name, this.value, this.oldValue); // TODO: Use this object in the commit process this.destroy(); }, destroy: function() { delete this.store.recordForReference(this.reference)._changesToSync[this.name]; } }; DS.Model.reopen({ eachAttribute: function(callback, binding) { get(this.constructor, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, attributeWillChange: Ember.beforeObserver(function(record, key) { var reference = get(record, '_reference'), store = get(record, 'store'); record.send('willSetProperty', { reference: reference, store: store, name: key }); }), attributeDidChange: Ember.observer(function(record, key) { record.send('didSetProperty', { name: key }); }) }); function getAttr(record, options, key) { var attributes = get(record, 'data').attributes; var value = attributes[key]; if (value === undefined) { value = options.defaultValue; } return value; } DS.attr = function(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed(function(key, value, oldValue) { if (arguments.length > 1) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id'); } else { value = getAttr(this, options, key); } return value; // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).property('data').meta(meta); }; })(); (function() { })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; DS.belongsTo = function(type, options) { Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type))); options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; return Ember.computed(function(key, value) { if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); } if (arguments.length === 2) { Ember.assert("You can only add a record of " + type.toString() + " to this relationship", !value || type.detectInstance(value)); return value === undefined ? null : value; } var data = get(this, 'data').belongsTo, store = get(this, 'store'), id; id = data[key]; if(isNone(id)) { return null; } else if (id.clientId) { return store.recordForReference(id); } else { return store.findById(id.type, id.id); } }).property('data').meta(meta); }; /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. */ DS.Model.reopen({ /** @private */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded')) { var oldParent = get(record, key); var childReference = get(record, '_reference'), store = get(record, 'store'); if (oldParent){ var change = DS.RelationshipChange.createChange(childReference, get(oldParent, '_reference'), store, { key: key, kind:"belongsTo", changeType: "remove" }); change.sync(); this._changesToSync[key] = change; } } }), /** @private */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if(newParent){ var childReference = get(record, '_reference'), store = get(record, 'store'); var change = DS.RelationshipChange.createChange(childReference, get(newParent, '_reference'), store, { key: key, kind:"belongsTo", changeType: "add" }); change.sync(); if(this._changesToSync[key]){ DS.OneToManyChange.ensureSameTransaction([change, this._changesToSync[key]], store); } } } delete this._changesToSync[key]; }) }); })(); (function() { var get = Ember.get, set = Ember.set, forEach = Ember.ArrayPolyfills.forEach; var hasRelationship = function(type, options) { options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; return Ember.computed(function(key, value) { var data = get(this, 'data').hasMany, store = get(this, 'store'), ids, relationship; if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); } //ids can be references or opaque token //(e.g. `{url: '/relationship'}`) that will be passed to the adapter ids = data[key]; relationship = store.findMany(type, ids, this, meta); set(relationship, 'owner', this); set(relationship, 'name', key); set(relationship, 'isPolymorphic', options.polymorphic); return relationship; }).property().meta(meta); }; DS.hasMany = function(type, options) { Ember.assert("The type passed to DS.hasMany must be defined", !!type); return hasRelationship(type, options); }; function clearUnmaterializedHasMany(record, relationship) { var store = get(record, 'store'), data = get(record, 'data').hasMany, type = relationship.type; var references = data[relationship.key]; if (!references) { return; } var inverseName = record.constructor.inverseFor(relationship.key).name; forEach.call(references, function(reference) { var childRecord; if (store.isReferenceMaterialized(reference)) { childRecord = store.recordForReference(reference); record.suspendRelationshipObservers(function() { set(childRecord, inverseName, null); }); } }); } DS.Model.reopen({ clearHasMany: function(relationship) { var hasMany = this.cacheFor(relationship.name); if (hasMany) { hasMany.clear(); } else { clearUnmaterializedHasMany(this, relationship); } } }); })(); (function() { var get = Ember.get, set = Ember.set; /** @private This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ DS.Model.reopen({ // This Ember.js hook allows an object to be notified when a property // is defined. // // In this case, we use it to be notified when an Ember Data user defines a // belongs-to relationship. In that case, we need to set up observers for // each one, allowing us to track relationship changes and automatically // reflect changes in the inverse has-many array. // // This hook passes the class being set up, as well as the key and value // being defined. So, for example, when the user does this: // // DS.Model.extend({ // parent: DS.belongsTo(App.User) // }); // // This hook would be called with "parent" as the key and the computed // property returned by `DS.belongsTo` as the value. didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.Descriptor) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } if (meta.isAttribute) { Ember.addObserver(proto, key, null, 'attributeDidChange'); Ember.addBeforeObserver(proto, key, null, 'attributeWillChange'); } meta.parentType = proto.constructor; } } }); /** These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ DS.Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: App.Post = DS.Model.extend({ comments: DS.hasMany(App.Comment) }); Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; var inverseName, inverseKind; if (options.inverse) { inverseName = options.inverse; inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ".", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This computed property would return a map describing these relationships, like this: var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { if (typeof meta.type === 'string') { meta.type = Ember.get(Ember.lookup, meta.type); } var relationshipsForType = map.get(meta.type); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This property would contain the following: var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This property would contain the following: var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type, types = Ember.A([]); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); } Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); if (!types.contains(type)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); types.push(type); } } }); return types; }), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post) }); This property would contain the following: var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(), type; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || get(Ember.lookup, type); meta.type = type; } map.set(name, meta); } }); return map; }), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: App.Blog = DS.Model.extend({ users: DS.hasMany(App.User), owner: DS.belongsTo(App.User), posts: DS.hasMany(App.Post), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(), type; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); DS.Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); })(); (function() { var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; DS.RelationshipChange = function(options) { this.parentReference = options.parentReference; this.childReference = options.childReference; this.firstRecordReference = options.firstRecordReference; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecordReference = options.secondRecordReference; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.store = options.store; this.committed = {}; this.changeType = options.changeType; }; DS.RelationshipChangeAdd = function(options){ DS.RelationshipChange.call(this, options); }; DS.RelationshipChangeRemove = function(options){ DS.RelationshipChange.call(this, options); }; /** @private */ DS.RelationshipChange.create = function(options) { return new DS.RelationshipChange(options); }; /** @private */ DS.RelationshipChangeAdd.create = function(options) { return new DS.RelationshipChangeAdd(options); }; /** @private */ DS.RelationshipChangeRemove.create = function(options) { return new DS.RelationshipChangeRemove(options); }; DS.OneToManyChange = {}; DS.OneToNoneChange = {}; DS.ManyToNoneChange = {}; DS.OneToOneChange = {}; DS.ManyToManyChange = {}; DS.RelationshipChange._createChange = function(options){ if(options.changeType === "add"){ return DS.RelationshipChangeAdd.create(options); } if(options.changeType === "remove"){ return DS.RelationshipChangeRemove.create(options); } }; DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, type, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse){ key = inverse.name; otherKind = inverse.kind; } if (!inverse){ return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; } else{ if(otherKind === "belongsTo"){ return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; } else{ return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; } } }; DS.RelationshipChange.createChange = function(firstRecordReference, secondRecordReference, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecordReference.type, key, changeType; changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === "oneToMany"){ return DS.OneToManyChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "manyToOne"){ return DS.OneToManyChange.createChange(secondRecordReference, firstRecordReference, store, options); } else if (changeType === "oneToNone"){ return DS.OneToNoneChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "manyToNone"){ return DS.ManyToNoneChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "oneToOne"){ return DS.OneToOneChange.createChange(firstRecordReference, secondRecordReference, store, options); } else if (changeType === "manyToMany"){ return DS.ManyToManyChange.createChange(firstRecordReference, secondRecordReference, store, options); } }; /** @private */ DS.OneToNoneChange.createChange = function(childReference, parentReference, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: "belongsTo" }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; /** @private */ DS.ManyToNoneChange.createChange = function(childReference, parentReference, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentReference: childReference, childReference: parentReference, secondRecordReference: childReference, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: "hasMany" }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; /** @private */ DS.ManyToManyChange.createChange = function(childReference, parentReference, store, options) { // Get the type of the child based on the child's client ID var childType = childReference.type, key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. key = options.key; var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, secondRecordReference: parentReference, firstRecordKind: "hasMany", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; /** @private */ DS.OneToOneChange.createChange = function(childReference, parentReference, store, options) { // Get the type of the child based on the child's client ID var childType = childReference.type, key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, secondRecordReference: parentReference, firstRecordKind: "belongsTo", secondRecordKind: "belongsTo", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; DS.OneToOneChange.maintainInvariant = function(options, store, childReference, key){ if (options.changeType === "add" && store.recordIsMaterialized(childReference)) { var child = store.recordForReference(childReference); var oldParent = get(child, key); if (oldParent){ var correspondingChange = DS.OneToOneChange.createChange(childReference, oldParent.get('_reference'), store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childReference, key, options.parentReference , null, correspondingChange); correspondingChange.sync(); } } }; /** @private */ DS.OneToManyChange.createChange = function(childReference, parentReference, store, options) { // Get the type of the child based on the child's client ID var childType = childReference.type, key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; DS.OneToManyChange.maintainInvariant( options, store, childReference, key ); } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentReference: parentReference, childReference: childReference, firstRecordReference: childReference, secondRecordReference: parentReference, firstRecordKind: "belongsTo", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childReference, key, parentReference, null, change); return change; }; DS.OneToManyChange.maintainInvariant = function(options, store, childReference, key){ if (options.changeType === "add" && store.recordIsMaterialized(childReference)) { var child = store.recordForReference(childReference); var oldParent = get(child, key); if (oldParent){ var correspondingChange = DS.OneToManyChange.createChange(childReference, oldParent.get('_reference'), store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childReference, key, options.parentReference , null, correspondingChange); correspondingChange.sync(); } } }; DS.OneToManyChange.ensureSameTransaction = function(changes, store){ var records = Ember.A(); forEach(changes, function(change){ records.addObject(change.getSecondRecord()); records.addObject(change.getFirstRecord()); }); var transaction = store.ensureSameTransaction(records); forEach(changes, function(change){ change.transaction = transaction; }); }; DS.RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, store = this.store, parent; if (!name) { parent = this.secondRecordReference; if (!parent) { return; } var childType = this.firstRecordReference.type; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @returns {String} */ getFirstRecordName: function() { var name = this.firstRecordName; return name; }, /** @private */ destroy: function() { var childReference = this.childReference, belongsToName = this.getFirstRecordName(), hasManyName = this.getSecondRecordName(), store = this.store, child, oldParent, newParent, lastParent, transaction; store.removeRelationshipChangeFor(childReference, belongsToName, this.parentReference, hasManyName, this.changeType); if (transaction = this.transaction) { transaction.relationshipBecameClean(this); } }, /** @private */ getByReference: function(reference) { var store = this.store; // return null or undefined if the original reference was null or undefined if (!reference) { return reference; } if (store.recordIsMaterialized(reference)) { return store.recordForReference(reference); } }, getSecondRecord: function(){ return this.getByReference(this.secondRecordReference); }, /** @private */ getFirstRecord: function() { return this.getByReference(this.firstRecordReference); }, /** @private Make sure that all three parts of the relationship change are part of the same transaction. If any of the three records is clean and in the default transaction, and the rest are in a different transaction, move them all into that transaction. */ ensureSameTransaction: function() { var child = this.getFirstRecord(), parentRecord = this.getSecondRecord(); var transaction = this.store.ensureSameTransaction([child, parentRecord]); this.transaction = transaction; return transaction; }, callChangeEvents: function(){ var hasManyName = this.getSecondRecordName(), belongsToName = this.getFirstRecordName(), child = this.getFirstRecord(), parentRecord = this.getSecondRecord(); var dirtySet = new Ember.OrderedSet(); // TODO: This implementation causes a race condition in key-value // stores. The fix involves buffering changes that happen while // a record is loading. A similar fix is required for other parts // of ember-data, and should be done as new infrastructure, not // a one-off hack. [tomhuda] if (parentRecord && get(parentRecord, 'isLoaded')) { this.store.recordHasManyDidChange(dirtySet, parentRecord, this); } if (child) { this.store.recordBelongsToDidChange(dirtySet, child, this); } dirtySet.forEach(function(record) { record.adapterDidDirty(); }); }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecordReference); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeAdd.prototype.changeType = "add"; DS.RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); var transaction = this.ensureSameTransaction(); transaction.relationshipBecameDirty(this); this.callChangeEvents(); if (secondRecord && firstRecord) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, firstRecord); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ get(secondRecord, secondRecordName).addObject(firstRecord); }); } } if (firstRecord && secondRecord && get(firstRecord, firstRecordName) !== secondRecord) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, secondRecord); }); } else if(this.firstdRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ get(firstRecord, firstRecordName).addObject(secondRecord); }); } } this.coalesce(); }; DS.RelationshipChangeRemove.prototype.changeType = "remove"; DS.RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); var transaction = this.ensureSameTransaction(firstRecord, secondRecord, secondRecordName, firstRecordName); transaction.relationshipBecameDirty(this); this.callChangeEvents(); if (secondRecord && firstRecord) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, null); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ get(secondRecord, secondRecordName).removeObject(firstRecord); }); } } if (firstRecord && get(firstRecord, firstRecordName)) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, null); }); } else if(this.firstdRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ get(firstRecord, firstRecordName).removeObject(secondRecord); }); } } this.coalesce(); }; })(); (function() { })(); (function() { var set = Ember.set; /** This code registers an injection for Ember.Application. If an Ember.js developer defines a subclass of DS.Store on their application, this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.Store = DS.Store.extend({ adapter: 'App.MyCustomAdapter' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.Store` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { if (Application.registerInjection) { Application.registerInjection({ name: "store", before: "controllers", // If a store subclass is defined, like App.Store, // instantiate it and inject it into the router. injection: function(app, stateManager, property) { if (!stateManager) { return; } if (property === 'Store') { set(stateManager, 'store', app[property].create()); } } }); Application.registerInjection({ name: "giveStoreToControllers", after: ['store','controllers'], // For each controller, set its `store` property // to the DS.Store instance we created above. injection: function(app, stateManager, property) { if (!stateManager) { return; } if (/^[A-Z].*Controller$/.test(property)) { var controllerName = property.charAt(0).toLowerCase() + property.substr(1); var store = stateManager.get('store'); var controller = stateManager.get(controllerName); if(!controller) { return; } controller.set('store', store); } } }); } else if (Application.initializer) { Application.initializer({ name: "store", initialize: function(container, application) { application.register('store:main', application.Store); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); } }); Application.initializer({ name: "injectStore", initialize: function(container, application) { application.inject('controller', 'store', 'store:main'); application.inject('route', 'store', 'store:main'); } }); } }); })(); (function() { var get = Ember.get, set = Ember.set, map = Ember.ArrayPolyfills.map, isNone = Ember.isNone; function mustImplement(name) { return function() { throw new Ember.Error("Your serializer " + this.toString() + " does not implement the required method " + name); }; } /** A serializer is responsible for serializing and deserializing a group of records. `DS.Serializer` is an abstract base class designed to help you build a serializer that can read to and write from any serialized form. While most applications will use `DS.JSONSerializer`, which reads and writes JSON, the serializer architecture allows your adapter to transmit things like XML, strings, or custom binary data. Typically, your application's `DS.Adapter` is responsible for both creating a serializer as well as calling the appropriate methods when it needs to materialize data or serialize a record. The serializer API is designed as a series of layered hooks that you can override to customize any of the individual steps of serialization and deserialization. The hooks are organized by the three responsibilities of the serializer: 1. Determining naming conventions 2. Serializing records into a serialized form 3. Deserializing records from a serialized form Because Ember Data lazily materializes records, the deserialization step, and therefore the hooks you implement, are split into two phases: 1. Extraction, where the serialized forms for multiple records are extracted from a single payload. The IDs of each record are also extracted for indexing. 2. Materialization, where a newly-created record has its attributes and relationships initialized based on the serialized form loaded by the adapter. Additionally, a serializer can convert values from their JavaScript versions into their serialized versions via a declarative API. ## Naming Conventions One of the most common uses of the serializer is to map attribute names from the serialized form to your `DS.Model`. For example, in your model, you may have an attribute called `firstName`: ```javascript App.Person = DS.Model.extend({ firstName: DS.attr('string') }); ``` However, because the web API your adapter is communicating with is legacy, it calls this attribute `FIRST_NAME`. You can determine the attribute name used in the serialized form by implementing `keyForAttributeName`: ```javascript keyForAttributeName: function(type, name) { return name.underscore.toUpperCase(); } ``` If your attribute names are not predictable, you can re-map them one-by-one using the adapter's `map` API: ```javascript App.Adapter.map('App.Person', { firstName: { key: '*API_USER_FIRST_NAME*' } }); ``` This API will also work for relationships and primary keys. For example: ```javascript App.Adapter.map('App.Person', { primaryKey: '_id' }); ``` ## Serialization During the serialization process, a record or records are converted from Ember.js objects into their serialized form. These methods are designed in layers, like a delicious 7-layer cake (but with fewer layers). The main entry point for serialization is the `serialize` method, which takes the record and options. The `serialize` method is responsible for: * turning the record's attributes (`DS.attr`) into attributes on the JSON object. * optionally adding the record's ID onto the hash * adding relationships (`DS.hasMany` and `DS.belongsTo`) to the JSON object. Depending on the backend, the serializer can choose whether to include the `hasMany` or `belongsTo` relationships on the JSON hash. For very custom serialization, you can implement your own `serialize` method. In general, however, you will want to override the hooks described below. ### Adding the ID The default `serialize` will optionally call your serializer's `addId` method with the JSON hash it is creating, the record's type, and the record's ID. The `serialize` method will not call `addId` if the record's ID is undefined. Your adapter must specifically request ID inclusion by passing `{ includeId: true }` as an option to `serialize`. NOTE: You may not want to include the ID when updating an existing record, because your server will likely disallow changing an ID after it is created, and the PUT request itself will include the record's identification. By default, `addId` will: 1. Get the primary key name for the record by calling the serializer's `primaryKey` with the record's type. Unless you override the `primaryKey` method, this will be `'id'`. 2. Assign the record's ID to the primary key in the JSON hash being built. If your backend expects a JSON object with the primary key at the root, you can just override the `primaryKey` method on your serializer subclass. Otherwise, you can override the `addId` method for more specialized handling. ### Adding Attributes By default, the serializer's `serialize` method will call `addAttributes` with the JSON object it is creating and the record to serialize. The `addAttributes` method will then call `addAttribute` in turn, with the JSON object, the record to serialize, the attribute's name and its type. Finally, the `addAttribute` method will serialize the attribute: 1. It will call `keyForAttributeName` to determine the key to use in the JSON hash. 2. It will get the value from the record. 3. It will call `serializeValue` with the attribute's value and attribute type to convert it into a JSON-compatible value. For example, it will convert a Date into a String. If your backend expects a JSON object with attributes as keys at the root, you can just override the `serializeValue` and `keyForAttributeName` methods in your serializer subclass and let the base class do the heavy lifting. If you need something more specialized, you can probably override `addAttribute` and let the default `addAttributes` handle the nitty gritty. ### Adding Relationships By default, `serialize` will call your serializer's `addRelationships` method with the JSON object that is being built and the record being serialized. The default implementation of this method is to loop over all of the relationships defined on your record type and: * If the relationship is a `DS.hasMany` relationship, call `addHasMany` with the JSON object, the record and a description of the relationship. * If the relationship is a `DS.belongsTo` relationship, call `addBelongsTo` with the JSON object, the record and a description of the relationship. The relationship description has the following keys: * `type`: the class of the associated information (the first parameter to `DS.hasMany` or `DS.belongsTo`) * `kind`: either `hasMany` or `belongsTo` The relationship description may get additional information in the future if more capabilities or relationship types are added. However, it will remain backwards-compatible, so the mere existence of new features should not break existing adapters. */ DS.Serializer = Ember.Object.extend({ init: function() { this.mappings = Ember.Map.create(); this.aliases = Ember.Map.create(); this.configurations = Ember.Map.create(); this.globalConfigurations = {}; }, extract: mustImplement('extract'), extractMany: mustImplement('extractMany'), extractId: mustImplement('extractId'), extractAttribute: mustImplement('extractAttribute'), extractHasMany: mustImplement('extractHasMany'), extractBelongsTo: mustImplement('extractBelongsTo'), createSerializedForm: mustImplement('createSerializedForm'), extractRecordRepresentation: function(loader, type, json, shouldSideload) { var prematerialized = {}, reference; if (shouldSideload) { reference = loader.sideload(type, json); } else { reference = loader.load(type, json); } this.eachEmbeddedHasMany(type, function(name, relationship) { var embeddedData = json[this.keyFor(relationship)]; if (!isNone(embeddedData)) { this.extractEmbeddedHasMany(loader, relationship, embeddedData, reference, prematerialized); } }, this); this.eachEmbeddedBelongsTo(type, function(name, relationship) { var embeddedData = json[this.keyFor(relationship)]; if (!isNone(embeddedData)) { this.extractEmbeddedBelongsTo(loader, relationship, embeddedData, reference, prematerialized); } }, this); loader.prematerialize(reference, prematerialized); return reference; }, extractEmbeddedHasMany: function(loader, relationship, array, parent, prematerialized) { var references = map.call(array, function(item) { if (!item) { return; } var foundType = this.extractEmbeddedType(relationship, item), reference = this.extractRecordRepresentation(loader, foundType, item, true); // If the embedded record should also be saved back when serializing the parent, // make sure we set its parent since it will not have an ID. var embeddedType = this.embeddedType(parent.type, relationship.key); if (embeddedType === 'always') { reference.parent = parent; } return reference; }, this); prematerialized[relationship.key] = references; }, extractEmbeddedBelongsTo: function(loader, relationship, data, parent, prematerialized) { var foundType = this.extractEmbeddedType(relationship, data), reference = this.extractRecordRepresentation(loader, foundType, data, true); prematerialized[relationship.key] = reference; // If the embedded record should also be saved back when serializing the parent, // make sure we set its parent since it will not have an ID. var embeddedType = this.embeddedType(parent.type, relationship.key); if (embeddedType === 'always') { reference.parent = parent; } }, /** A hook you can use to customize how the record's type is extracted from the serialized data. The `extractEmbeddedType` hook is called with: * the serialized representation being built * the serialized id (after calling the `serializeId` hook) By default, it returns the type of the relationship. @param {Object} relationship an object representing the relationship @param {any} data the serialized representation that is being built */ extractEmbeddedType: function(relationship, data) { return relationship.type; }, //....................... //. SERIALIZATION HOOKS //....................... /** The main entry point for serializing a record. While you can consider this a hook that can be overridden in your serializer, you will have to manually handle serialization. For most cases, there are more granular hooks that you can override. If overriding this method, these are the responsibilities that you will need to implement yourself: * If the option hash contains `includeId`, add the record's ID to the serialized form. By default, `serialize` calls `addId` if appropriate. * If the option hash contains `includeType`, add the record's type to the serialized form. * Add the record's attributes to the serialized form. By default, `serialize` calls `addAttributes`. * Add the record's relationships to the serialized form. By default, `serialize` calls `addRelationships`. @param {DS.Model} record the record to serialize @param {Object} [options] a hash of options @returns {any} the serialized form of the record */ serialize: function(record, options) { options = options || {}; var serialized = this.createSerializedForm(), id; if (options.includeId) { if (id = get(record, 'id')) { this._addId(serialized, record.constructor, id); } } if (options.includeType) { this.addType(serialized, record.constructor); } this.addAttributes(serialized, record); this.addRelationships(serialized, record); return serialized; }, /** @private Given an attribute type and value, convert the value into the serialized form using the transform registered for that type. @param {any} value the value to convert to the serialized form @param {String} attributeType the registered type (e.g. `string` or `boolean`) @returns {any} the serialized form of the value */ serializeValue: function(value, attributeType) { var transform = this.transforms ? this.transforms[attributeType] : null; Ember.assert("You tried to use an attribute type (" + attributeType + ") that has not been registered", transform); return transform.serialize(value); }, /** A hook you can use to normalize IDs before adding them to the serialized representation. Because the store coerces all IDs to strings for consistency, this is the opportunity for the serializer to, for example, convert numerical IDs back into number form. @param {String} id the id from the record @returns {any} the serialized representation of the id */ serializeId: function(id) { if (isNaN(id)) { return id; } return +id; }, /** A hook you can use to change how attributes are added to the serialized representation of a record. By default, `addAttributes` simply loops over all of the attributes of the passed record, maps the attribute name to the key for the serialized form, and invokes any registered transforms on the value. It then invokes the more granular `addAttribute` with the key and transformed value. Since you can override `keyForAttributeName`, `addAttribute`, and register custom transforms, you should rarely need to override this hook. @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize */ addAttributes: function(data, record) { record.eachAttribute(function(name, attribute) { this._addAttribute(data, record, name, attribute.type); }, this); }, /** A hook you can use to customize how the key/value pair is added to the serialized data. @param {any} serialized the serialized form being built @param {String} key the key to add to the serialized data @param {any} value the value to add to the serialized data */ addAttribute: mustImplement('addAttribute'), /** A hook you can use to customize how the record's id is added to the serialized data. The `addId` hook is called with: * the serialized representation being built * the resolved primary key (taking configurations and the `primaryKey` hook into consideration) * the serialized id (after calling the `serializeId` hook) @param {any} data the serialized representation that is being built @param {String} key the resolved primary key @param {id} id the serialized id */ addId: mustImplement('addId'), /** A hook you can use to customize how the record's type is added to the serialized data. The `addType` hook is called with: * the serialized representation being built * the serialized id (after calling the `serializeId` hook) @param {any} data the serialized representation that is being built @param {DS.Model subclass} type the type of the record */ addType: Ember.K, /** Creates an empty hash that will be filled in by the hooks called from the `serialize()` method. @return {Object} */ createSerializedForm: function() { return {}; }, /** A hook you can use to change how relationships are added to the serialized representation of a record. By default, `addRelationships` loops over all of the relationships of the passed record, maps the relationship names to the key for the serialized form, and then invokes the public `addBelongsTo` and `addHasMany` hooks. Since you can override `keyForBelongsTo`, `keyForHasMany`, `addBelongsTo`, `addHasMany`, and register mappings, you should rarely need to override this hook. @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize */ addRelationships: function(data, record) { record.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { this._addBelongsTo(data, record, name, relationship); } else if (relationship.kind === 'hasMany') { this._addHasMany(data, record, name, relationship); } }, this); }, /** A hook you can use to add a `belongsTo` relationship to the serialized representation. The specifics of this hook are very adapter-specific, so there is no default implementation. You can see `DS.JSONSerializer` for an example of an implementation of the `addBelongsTo` hook. The `belongsTo` relationship object has the following properties: * **type** a subclass of DS.Model that is the type of the relationship. This is the first parameter to DS.belongsTo * **options** the options passed to the call to DS.belongsTo * **kind** always `belongsTo` Additional properties may be added in the future. @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} key the key for the serialized object @param {Object} relationship an object representing the relationship */ addBelongsTo: mustImplement('addBelongsTo'), /** A hook you can use to add a `hasMany` relationship to the serialized representation. The specifics of this hook are very adapter-specific, so there is no default implementation. You may not need to implement this, for example, if your backend only expects relationships on the child of a one to many relationship. The `hasMany` relationship object has the following properties: * **type** a subclass of DS.Model that is the type of the relationship. This is the first parameter to DS.hasMany * **options** the options passed to the call to DS.hasMany * **kind** always `hasMany` Additional properties may be added in the future. @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} key the key for the serialized object @param {Object} relationship an object representing the relationship */ addHasMany: mustImplement('addHasMany'), /** NAMING CONVENTIONS The most commonly overridden APIs of the serializer are the naming convention methods: * `keyForAttributeName`: converts a camelized attribute name into a key in the adapter-provided data hash. For example, if the model's attribute name was `firstName`, and the server used underscored names, you would return `first_name`. * `primaryKey`: returns the key that should be used to extract the id from the adapter-provided data hash. It is also used when serializing a record. */ /** A hook you can use in your serializer subclass to customize how an unmapped attribute name is converted into a key. By default, this method returns the `name` parameter. For example, if the attribute names in your JSON are underscored, you will want to convert them into JavaScript conventional camelcase: ```javascript App.MySerializer = DS.Serializer.extend({ // ... keyForAttributeName: function(type, name) { return name.camelize(); } }); ``` @param {DS.Model subclass} type the type of the record with the attribute name `name` @param {String} name the attribute name to convert into a key @returns {String} the key */ keyForAttributeName: function(type, name) { return name; }, /** A hook you can use in your serializer to specify a conventional primary key. By default, this method will return the string `id`. In general, you should not override this hook to specify a special primary key for an individual type; use `configure` instead. For example, if your primary key is always `__id__`: ```javascript App.MySerializer = DS.Serializer.extend({ // ... primaryKey: function(type) { return '__id__'; } }); ``` In another example, if the primary key always includes the underscored version of the type before the string `id`: ```javascript App.MySerializer = DS.Serializer.extend({ // ... primaryKey: function(type) { // If the type is `BlogPost`, this will return // `blog_post_id`. var typeString = type.toString().split(".")[1].underscore(); return typeString + "_id"; } }); ``` @param {DS.Model subclass} type @returns {String} the primary key for the type */ primaryKey: function(type) { return "id"; }, /** A hook you can use in your serializer subclass to customize how an unmapped `belongsTo` relationship is converted into a key. By default, this method calls `keyForAttributeName`, so if your naming convention is uniform across attributes and relationships, you can use the default here and override just `keyForAttributeName` as needed. For example, if the `belongsTo` names in your JSON always begin with `BT_` (e.g. `BT_posts`), you can strip out the `BT_` prefix:" ```javascript App.MySerializer = DS.Serializer.extend({ // ... keyForBelongsTo: function(type, name) { return name.match(/^BT_(.*)$/)[1].camelize(); } }); ``` @param {DS.Model subclass} type the type of the record with the `belongsTo` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ keyForBelongsTo: function(type, name) { return this.keyForAttributeName(type, name); }, /** A hook you can use in your serializer subclass to customize how an unmapped `hasMany` relationship is converted into a key. By default, this method calls `keyForAttributeName`, so if your naming convention is uniform across attributes and relationships, you can use the default here and override just `keyForAttributeName` as needed. For example, if the `hasMany` names in your JSON always begin with the "table name" for the current type (e.g. `post_comments`), you can strip out the prefix:" ```javascript App.MySerializer = DS.Serializer.extend({ // ... keyForHasMany: function(type, name) { // if your App.BlogPost has many App.BlogComment, the key from // the server would look like: `blog_post_blog_comments` // // 1. Convert the type into a string and underscore the // second part (App.BlogPost -> blog_post) // 2. Extract the part after `blog_post_` (`blog_comments`) // 3. Underscore it, to become `blogComments` var typeString = type.toString().split(".")[1].underscore(); return name.match(new RegExp("^" + typeString + "_(.*)$"))[1].camelize(); } }); ``` @param {DS.Model subclass} type the type of the record with the `belongsTo` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ keyForHasMany: function(type, name) { return this.keyForAttributeName(type, name); }, //......................... //. MATERIALIZATION HOOKS //......................... materialize: function(record, serialized, prematerialized) { var id; if (Ember.isNone(get(record, 'id'))) { if (prematerialized && prematerialized.hasOwnProperty('id')) { id = prematerialized.id; } else { id = this.extractId(record.constructor, serialized); } record.materializeId(id); } this.materializeAttributes(record, serialized, prematerialized); this.materializeRelationships(record, serialized, prematerialized); }, deserializeValue: function(value, attributeType) { var transform = this.transforms ? this.transforms[attributeType] : null; Ember.assert("You tried to use a attribute type (" + attributeType + ") that has not been registered", transform); return transform.deserialize(value); }, materializeAttributes: function(record, serialized, prematerialized) { record.eachAttribute(function(name, attribute) { if (prematerialized && prematerialized.hasOwnProperty(name)) { record.materializeAttribute(name, prematerialized[name]); } else { this.materializeAttribute(record, serialized, name, attribute.type); } }, this); }, materializeAttribute: function(record, serialized, attributeName, attributeType) { var value = this.extractAttribute(record.constructor, serialized, attributeName); value = this.deserializeValue(value, attributeType); record.materializeAttribute(attributeName, value); }, materializeRelationships: function(record, hash, prematerialized) { record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { if (prematerialized && prematerialized.hasOwnProperty(name)) { var tuplesOrReferencesOrOpaque = this._convertPrematerializedHasMany(relationship.type, prematerialized[name]); record.materializeHasMany(name, tuplesOrReferencesOrOpaque); } else { this.materializeHasMany(name, record, hash, relationship, prematerialized); } } else if (relationship.kind === 'belongsTo') { if (prematerialized && prematerialized.hasOwnProperty(name)) { var tupleOrReference = this._convertTuple(relationship.type, prematerialized[name]); record.materializeBelongsTo(name, tupleOrReference); } else { this.materializeBelongsTo(name, record, hash, relationship, prematerialized); } } }, this); }, materializeHasMany: function(name, record, hash, relationship) { var type = record.constructor, key = this._keyForHasMany(type, relationship.key), idsOrTuples = this.extractHasMany(type, hash, key), tuples = idsOrTuples; if(idsOrTuples && Ember.isArray(idsOrTuples)) { tuples = this._convertTuples(relationship.type, idsOrTuples); } record.materializeHasMany(name, tuples); }, materializeBelongsTo: function(name, record, hash, relationship) { var type = record.constructor, key = this._keyForBelongsTo(type, relationship.key), idOrTuple, tuple = null; if(relationship.options && relationship.options.polymorphic) { idOrTuple = this.extractBelongsToPolymorphic(type, hash, key); } else { idOrTuple = this.extractBelongsTo(type, hash, key); } if(!isNone(idOrTuple)) { tuple = this._convertTuple(relationship.type, idOrTuple); } record.materializeBelongsTo(name, tuple); }, _extractEmbeddedRelationship: function(type, hash, name, relationshipType) { var key = this['_keyFor' + relationshipType](type, name); if (this.embeddedType(type, name)) { return this['extractEmbedded' + relationshipType](type, hash, key); } }, _extractEmbeddedBelongsTo: function(type, hash, name) { return this._extractEmbeddedRelationship(type, hash, name, 'BelongsTo'); }, _extractEmbeddedHasMany: function(type, hash, name) { return this._extractEmbeddedRelationship(type, hash, name, 'HasMany'); }, _convertPrematerializedHasMany: function(type, prematerializedHasMany) { var tuplesOrReferencesOrOpaque; if( typeof prematerializedHasMany === 'string' ) { tuplesOrReferencesOrOpaque = prematerializedHasMany; } else { tuplesOrReferencesOrOpaque = this._convertTuples(type, prematerializedHasMany); } return tuplesOrReferencesOrOpaque; }, _convertTuples: function(type, idsOrTuples) { return map.call(idsOrTuples, function(idOrTuple) { return this._convertTuple(type, idOrTuple); }, this); }, _convertTuple: function(type, idOrTuple) { var foundType; if (typeof idOrTuple === 'object') { if (DS.Model.detect(idOrTuple.type)) { return idOrTuple; } else { foundType = this.typeFromAlias(idOrTuple.type); Ember.assert("Unable to resolve type " + idOrTuple.type + ". You may need to configure your serializer aliases.", !!foundType); return {id: idOrTuple.id, type: foundType}; } } return {id: idOrTuple, type: type}; }, /** @private This method is called to get the primary key for a given type. If a primary key configuration exists for this type, this method will return the configured value. Otherwise, it will call the public `primaryKey` hook. @param {DS.Model subclass} type @returns {String} the primary key for the type */ _primaryKey: function(type) { var config = this.configurationForType(type), primaryKey = config && config.primaryKey; if (primaryKey) { return primaryKey; } else { return this.primaryKey(type); } }, /** @private This method looks up the key for the attribute name and transforms the attribute's value using registered transforms. Specifically: 1. Look up the key for the attribute name. If available, this will use any registered mappings. Otherwise, it will invoke the public `keyForAttributeName` hook. 2. Get the value from the record using the `attributeName`. 3. Transform the value using registered transforms for the `attributeType`. 4. Invoke the public `addAttribute` hook with the hash, key, and transformed value. @param {any} data the serialized representation being built @param {DS.Model} record the record to serialize @param {String} attributeName the name of the attribute on the record @param {String} attributeType the type of the attribute (e.g. `string` or `boolean`) */ _addAttribute: function(data, record, attributeName, attributeType) { var key = this._keyForAttributeName(record.constructor, attributeName); var value = get(record, attributeName); this.addAttribute(data, key, this.serializeValue(value, attributeType)); }, /** @private This method looks up the primary key for the `type` and invokes `serializeId` on the `id`. It then invokes the public `addId` hook with the primary key and the serialized id. @param {any} data the serialized representation that is being built @param {Ember.Model subclass} type @param {any} id the materialized id from the record */ _addId: function(hash, type, id) { var primaryKey = this._primaryKey(type); this.addId(hash, primaryKey, this.serializeId(id)); }, /** @private This method is called to get a key used in the data from an attribute name. It first checks for any mappings before calling the public hook `keyForAttributeName`. @param {DS.Model subclass} type the type of the record with the attribute name `name` @param {String} name the attribute name to convert into a key @returns {String} the key */ _keyForAttributeName: function(type, name) { return this._keyFromMappingOrHook('keyForAttributeName', type, name); }, /** @private This method is called to get a key used in the data from a belongsTo relationship. It first checks for any mappings before calling the public hook `keyForBelongsTo`. @param {DS.Model subclass} type the type of the record with the `belongsTo` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ _keyForBelongsTo: function(type, name) { return this._keyFromMappingOrHook('keyForBelongsTo', type, name); }, keyFor: function(description) { var type = description.parentType, name = description.key; switch (description.kind) { case 'belongsTo': return this._keyForBelongsTo(type, name); case 'hasMany': return this._keyForHasMany(type, name); } }, /** @private This method is called to get a key used in the data from a hasMany relationship. It first checks for any mappings before calling the public hook `keyForHasMany`. @param {DS.Model subclass} type the type of the record with the `hasMany` relationship. @param {String} name the relationship name to convert into a key @returns {String} the key */ _keyForHasMany: function(type, name) { return this._keyFromMappingOrHook('keyForHasMany', type, name); }, /** @private This method converts the relationship name to a key for serialization, and then invokes the public `addBelongsTo` hook. @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} name the relationship name @param {Object} relationship an object representing the relationship */ _addBelongsTo: function(data, record, name, relationship) { var key = this._keyForBelongsTo(record.constructor, name); this.addBelongsTo(data, record, key, relationship); }, /** @private This method converts the relationship name to a key for serialization, and then invokes the public `addHasMany` hook. @param {any} data the serialized representation that is being built @param {DS.Model} record the record to serialize @param {String} name the relationship name @param {Object} relationship an object representing the relationship */ _addHasMany: function(data, record, name, relationship) { var key = this._keyForHasMany(record.constructor, name); this.addHasMany(data, record, key, relationship); }, /** @private An internal method that handles checking whether a mapping exists for a particular attribute or relationship name before calling the public hooks. If a mapping is found, and the mapping has a key defined, use that instead of invoking the hook. @param {String} publicMethod the public hook to invoke if a mapping is not found (e.g. `keyForAttributeName`) @param {DS.Model subclass} type the type of the record with the attribute or relationship name. @param {String} name the attribute or relationship name to convert into a key */ _keyFromMappingOrHook: function(publicMethod, type, name) { var key = this.mappingOption(type, name, 'key'); if (key) { return key; } else { return this[publicMethod](type, name); } }, /** TRANSFORMS */ registerTransform: function(type, transform) { this.transforms[type] = transform; }, registerEnumTransform: function(type, objects) { var transform = { deserialize: function(serialized) { return Ember.A(objects).objectAt(serialized); }, serialize: function(deserialized) { return Ember.EnumerableUtils.indexOf(objects, deserialized); }, values: objects }; this.registerTransform(type, transform); }, /** MAPPING CONVENIENCE */ map: function(type, mappings) { this.mappings.set(type, mappings); }, configure: function(type, configuration) { if (type && !configuration) { Ember.merge(this.globalConfigurations, type); return; } var config, alias; if (configuration.alias) { alias = configuration.alias; this.aliases.set(alias, type); delete configuration.alias; } config = Ember.create(this.globalConfigurations); Ember.merge(config, configuration); this.configurations.set(type, config); }, typeFromAlias: function(alias) { this._completeAliases(); return this.aliases.get(alias); }, mappingForType: function(type) { this._reifyMappings(); return this.mappings.get(type) || {}; }, configurationForType: function(type) { this._reifyConfigurations(); return this.configurations.get(type) || this.globalConfigurations; }, _completeAliases: function() { this._pluralizeAliases(); this._reifyAliases(); }, _pluralizeAliases: function() { if (this._didPluralizeAliases) { return; } var aliases = this.aliases, sideloadMapping = this.aliases.sideloadMapping, plural, self = this; aliases.forEach(function(key, type) { plural = self.pluralize(key); Ember.assert("The '" + key + "' alias has already been defined", !aliases.get(plural)); aliases.set(plural, type); }); // This map is only for backward compatibility with the `sideloadAs` option. if (sideloadMapping) { sideloadMapping.forEach(function(key, type) { Ember.assert("The '" + key + "' alias has already been defined", !aliases.get(key) || (aliases.get(key)===type) ); aliases.set(key, type); }); delete this.aliases.sideloadMapping; } this._didPluralizeAliases = true; }, _reifyAliases: function() { if (this._didReifyAliases) { return; } var aliases = this.aliases, reifiedAliases = Ember.Map.create(), foundType; aliases.forEach(function(key, type) { if (typeof type === 'string') { foundType = Ember.get(Ember.lookup, type); Ember.assert("Could not find model at path " + key, type); reifiedAliases.set(key, foundType); } else { reifiedAliases.set(key, type); } }); this.aliases = reifiedAliases; this._didReifyAliases = true; }, _reifyMappings: function() { if (this._didReifyMappings) { return; } var mappings = this.mappings, reifiedMappings = Ember.Map.create(); mappings.forEach(function(key, mapping) { if (typeof key === 'string') { var type = Ember.get(Ember.lookup, key); Ember.assert("Could not find model at path " + key, type); reifiedMappings.set(type, mapping); } else { reifiedMappings.set(key, mapping); } }); this.mappings = reifiedMappings; this._didReifyMappings = true; }, _reifyConfigurations: function() { if (this._didReifyConfigurations) { return; } var configurations = this.configurations, reifiedConfigurations = Ember.Map.create(); configurations.forEach(function(key, mapping) { if (typeof key === 'string' && key !== 'plurals') { var type = Ember.get(Ember.lookup, key); Ember.assert("Could not find model at path " + key, type); reifiedConfigurations.set(type, mapping); } else { reifiedConfigurations.set(key, mapping); } }); this.configurations = reifiedConfigurations; this._didReifyConfigurations = true; }, mappingOption: function(type, name, option) { var mapping = this.mappingForType(type)[name]; return mapping && mapping[option]; }, configOption: function(type, option) { var config = this.configurationForType(type); return config[option]; }, // EMBEDDED HELPERS embeddedType: function(type, name) { return this.mappingOption(type, name, 'embedded'); }, eachEmbeddedRecord: function(record, callback, binding) { this.eachEmbeddedBelongsToRecord(record, callback, binding); this.eachEmbeddedHasManyRecord(record, callback, binding); }, eachEmbeddedBelongsToRecord: function(record, callback, binding) { var type = record.constructor; this.eachEmbeddedBelongsTo(record.constructor, function(name, relationship, embeddedType) { var embeddedRecord = get(record, name); if (embeddedRecord) { callback.call(binding, embeddedRecord, embeddedType); } }); }, eachEmbeddedHasManyRecord: function(record, callback, binding) { var type = record.constructor; this.eachEmbeddedHasMany(record.constructor, function(name, relationship, embeddedType) { var array = get(record, name); for (var i=0, l=get(array, 'length'); i<l; i++) { callback.call(binding, array.objectAt(i), embeddedType); } }); }, eachEmbeddedHasMany: function(type, callback, binding) { this.eachEmbeddedRelationship(type, 'hasMany', callback, binding); }, eachEmbeddedBelongsTo: function(type, callback, binding) { this.eachEmbeddedRelationship(type, 'belongsTo', callback, binding); }, eachEmbeddedRelationship: function(type, kind, callback, binding) { type.eachRelationship(function(name, relationship) { var embeddedType = this.embeddedType(type, name); if (embeddedType) { if (relationship.kind === kind) { callback.call(binding, name, relationship, embeddedType); } } }, this); }, // HELPERS // define a plurals hash in your subclass to define // special-case pluralization pluralize: function(name) { var plurals = this.configurations.get('plurals'); return (plurals && plurals[name]) || name + "s"; }, // use the same plurals hash to determine // special-case singularization singularize: function(name) { var plurals = this.configurations.get('plurals'); if (plurals) { for (var i in plurals) { if (plurals[i] === name) { return i; } } } if (name.lastIndexOf('s') === name.length - 1) { return name.substring(0, name.length - 1); } else { return name; } }, }); })(); (function() { var none = Ember.isNone, empty = Ember.isEmpty; /** DS.Transforms is a hash of transforms used by DS.Serializer. */ DS.JSONTransforms = { string: { deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }, number: { deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }, // Handles the following boolean inputs: // "TrUe", "t", "f", "FALSE", 0, (non-zero), or boolean true/false 'boolean': { deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }, date: { deserialize: function(serialized) { var type = typeof serialized; var date = null; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var pad = function(num) { return num < 10 ? "0"+num : ""+num; }; var utcYear = date.getUTCFullYear(), utcMonth = date.getUTCMonth(), utcDayOfMonth = date.getUTCDate(), utcDay = date.getUTCDay(), utcHours = date.getUTCHours(), utcMinutes = date.getUTCMinutes(), utcSeconds = date.getUTCSeconds(); var dayOfWeek = days[utcDay]; var dayOfMonth = pad(utcDayOfMonth); var month = months[utcMonth]; return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " + pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT"; } else { return null; } } } }; })(); (function() { var get = Ember.get, set = Ember.set; var generatedId = 0; DS.JSONSerializer = DS.Serializer.extend({ init: function() { this._super(); if (!get(this, 'transforms')) { this.set('transforms', DS.JSONTransforms); } this.sideloadMapping = Ember.Map.create(); this.metadataMapping = Ember.Map.create(); this.configure({ meta: 'meta', since: 'since' }); }, configure: function(type, configuration) { var key; if (type && !configuration) { for(key in type){ this.metadataMapping.set(get(type, key), key); } return this._super(type); } var sideloadAs = configuration.sideloadAs, sideloadMapping; if (sideloadAs) { sideloadMapping = this.aliases.sideloadMapping || Ember.Map.create(); sideloadMapping.set(sideloadAs, type); this.aliases.sideloadMapping = sideloadMapping; delete configuration.sideloadAs; } this._super.apply(this, arguments); }, addId: function(data, key, id) { data[key] = id; }, /** A hook you can use to customize how the key/value pair is added to the serialized data. @param {any} hash the JSON hash being built @param {String} key the key to add to the serialized data @param {any} value the value to add to the serialized data */ addAttribute: function(hash, key, value) { hash[key] = value; }, extractAttribute: function(type, hash, attributeName) { var key = this._keyForAttributeName(type, attributeName); return hash[key]; }, extractId: function(type, hash) { var primaryKey = this._primaryKey(type); if (hash.hasOwnProperty(primaryKey)) { // Ensure that we coerce IDs to strings so that record // IDs remain consistent between application runs; especially // if the ID is serialized and later deserialized from the URL, // when type information will have been lost. return hash[primaryKey]+''; } else { return null; } }, extractHasMany: function(type, hash, key) { return hash[key]; }, extractBelongsTo: function(type, hash, key) { return hash[key]; }, extractBelongsToPolymorphic: function(type, hash, key) { var keyForId = this.keyForPolymorphicId(key), keyForType, id = hash[keyForId]; if (id) { keyForType = this.keyForPolymorphicType(key); return {id: id, type: hash[keyForType]}; } return null; }, addBelongsTo: function(hash, record, key, relationship) { var type = record.constructor, name = relationship.key, value = null, includeType = (relationship.options && relationship.options.polymorphic), embeddedChild, child, id; if (this.embeddedType(type, name)) { if (embeddedChild = get(record, name)) { value = this.serialize(embeddedChild, { includeId: true, includeType: includeType }); } hash[key] = value; } else { child = get(record, relationship.key); id = get(child, 'id'); if (relationship.options && relationship.options.polymorphic && !Ember.isNone(id)) { this.addBelongsToPolymorphic(hash, key, id, child.constructor); } else { hash[key] = id === undefined ? null : this.serializeId(id); } } }, addBelongsToPolymorphic: function(hash, key, id, type) { var keyForId = this.keyForPolymorphicId(key), keyForType = this.keyForPolymorphicType(key); hash[keyForId] = id; hash[keyForType] = this.rootForType(type); }, /** Adds a has-many relationship to the JSON hash being built. The default REST semantics are to only add a has-many relationship if it is embedded. If the relationship was initially loaded by ID, we assume that that was done as a performance optimization, and that changes to the has-many should be saved as foreign key changes on the child's belongs-to relationship. @param {Object} hash the JSON being built @param {DS.Model} record the record being serialized @param {String} key the JSON key into which the serialized relationship should be saved @param {Object} relationship metadata about the relationship being serialized */ addHasMany: function(hash, record, key, relationship) { var type = record.constructor, name = relationship.key, serializedHasMany = [], includeType = (relationship.options && relationship.options.polymorphic), manyArray, embeddedType; // If the has-many is not embedded, there is nothing to do. embeddedType = this.embeddedType(type, name); if (embeddedType !== 'always') { return; } // Get the DS.ManyArray for the relationship off the record manyArray = get(record, name); // Build up the array of serialized records manyArray.forEach(function (record) { serializedHasMany.push(this.serialize(record, { includeId: true, includeType: includeType })); }, this); // Set the appropriate property of the serialized JSON to the // array of serialized embedded records hash[key] = serializedHasMany; }, addType: function(hash, type) { var keyForType = this.keyForEmbeddedType(); hash[keyForType] = this.rootForType(type); }, // EXTRACTION extract: function(loader, json, type, record) { var root = this.rootForType(type); this.sideload(loader, type, json, root); this.extractMeta(loader, type, json); if (json[root]) { if (record) { loader.updateId(record, json[root]); } this.extractRecordRepresentation(loader, type, json[root]); } }, extractMany: function(loader, json, type, records) { var root = this.rootForType(type); root = this.pluralize(root); this.sideload(loader, type, json, root); this.extractMeta(loader, type, json); if (json[root]) { var objects = json[root], references = []; if (records) { records = records.toArray(); } for (var i = 0; i < objects.length; i++) { if (records) { loader.updateId(records[i], objects[i]); } var reference = this.extractRecordRepresentation(loader, type, objects[i]); references.push(reference); } loader.populateArray(references); } }, extractMeta: function(loader, type, json) { var meta = this.configOption(type, 'meta'), data = json, key, property, value; if(meta && json[meta]){ data = json[meta]; } this.metadataMapping.forEach(function(property, key){ if(value = data[property]){ loader.metaForType(type, key, value); } }); }, extractEmbeddedType: function(relationship, data) { var foundType = relationship.type; if(relationship.options && relationship.options.polymorphic) { var key = this.keyFor(relationship), keyForEmbeddedType = this.keyForEmbeddedType(key); foundType = this.typeFromAlias(data[keyForEmbeddedType]); delete data[keyForEmbeddedType]; } return foundType; }, /** @private Iterates over the `json` payload and attempts to load any data included alongside `root`. The keys expected for sideloaded data are based upon the types related to the root model. Recursion is used to ensure that types related to related types can be loaded as well. Any custom keys specified by `sideloadAs` mappings will also be respected. @param {DS.Store subclass} loader @param {DS.Model subclass} type @param {Object} json @param {String} root */ sideload: function(loader, type, json, root) { var sideloadedType; this.configureSideloadMappingForType(type); for (var prop in json) { if (!json.hasOwnProperty(prop) || prop === root || !!this.metadataMapping.get(prop)) { continue; } sideloadedType = this.typeFromAlias(prop); Ember.assert("Your server returned a hash with the key " + prop + " but you have no mapping for it", !!sideloadedType); this.loadValue(loader, sideloadedType, json[prop]); } }, /** @private Configures possible sideload mappings for the types related to a particular model. This recursive method ensures that sideloading works for related models as well. @param {DS.Model subclass} type @param {Ember.A} configured an array of types that have already been configured */ configureSideloadMappingForType: function(type, configured) { if (!configured) {configured = Ember.A([]);} configured.pushObject(type); type.eachRelatedType(function(relatedType) { if (!configured.contains(relatedType)) { var root = this.defaultSideloadRootForType(relatedType); this.aliases.set(root, relatedType); this.configureSideloadMappingForType(relatedType, configured); } }, this); }, loadValue: function(loader, type, value) { if (value instanceof Array) { for (var i=0; i < value.length; i++) { loader.sideload(type, value[i]); } } else { loader.sideload(type, value); } }, /** A hook you can use in your serializer subclass to customize how a polymorphic association's name is converted into a key for the id. @param {String} name the association name to convert into a key @returns {String} the key */ keyForPolymorphicId: Ember.K, /** A hook you can use in your serializer subclass to customize how a polymorphic association's name is converted into a key for the type. @param {String} name the association name to convert into a key @returns {String} the key */ keyForPolymorphicType: Ember.K, /** A hook you can use in your serializer subclass to customize the key used to store the type of a record of an embedded polymorphic association. By default, this method returns 'type'. @returns {String} the key */ keyForEmbeddedType: function() { return 'type'; }, // HELPERS /** @private Determines the singular root name for a particular type. This is an underscored, lowercase version of the model name. For example, the type `App.UserGroup` will have the root `user_group`. @param {DS.Model subclass} type @returns {String} name of the root element */ rootForType: function(type) { var typeString = type.toString(); Ember.assert("Your model must not be anonymous. It was " + type, typeString.charAt(0) !== '('); // use the last part of the name as the URL var parts = typeString.split("."); var name = parts[parts.length - 1]; return name.replace(/([A-Z])/g, '_$1').toLowerCase().slice(1); }, /** @private The default root name for a particular sideloaded type. @param {DS.Model subclass} type @returns {String} name of the root element */ defaultSideloadRootForType: function(type) { return this.pluralize(this.rootForType(type)); } }); })(); (function() { function loaderFor(store) { return { load: function(type, data, prematerialized) { return store.load(type, data, prematerialized); }, loadMany: function(type, array) { return store.loadMany(type, array); }, updateId: function(record, data) { return store.updateId(record, data); }, populateArray: Ember.K, sideload: function(type, data) { return store.load(type, data); }, sideloadMany: function(type, array) { return store.loadMany(type, array); }, prematerialize: function(reference, prematerialized) { store.prematerialize(reference, prematerialized); }, metaForType: function(type, property, data) { store.metaForType(type, property, data); } }; } DS.loaderFor = loaderFor; /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. ### Creating an Adapter First, create a new subclass of `DS.Adapter`: App.MyAdapter = DS.Adapter.extend({ // ...your code here }); To tell your store which adapter to use, set its `adapter` property: App.store = DS.Store.create({ revision: 3, adapter: App.MyAdapter.create() }); `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` * `createRecords()` * `updateRecords()` * `deleteRecords()` * `commit()` */ var get = Ember.get, set = Ember.set, merge = Ember.merge; DS.Adapter = Ember.Object.extend(DS._Mappable, { init: function() { var serializer = get(this, 'serializer'); if (Ember.Object.detect(serializer)) { serializer = serializer.create(); set(this, 'serializer', serializer); } this._attributesMap = this.createInstanceMapFor('attributes'); this._configurationsMap = this.createInstanceMapFor('configurations'); this._outstandingOperations = new Ember.MapWithDefault({ defaultValue: function() { return 0; } }); this._dependencies = new Ember.MapWithDefault({ defaultValue: function() { return new Ember.OrderedSet(); } }); this.registerSerializerTransforms(this.constructor, serializer, {}); this.registerSerializerMappings(serializer); }, /** Loads a payload for a record into the store. This method asks the serializer to break the payload into constituent parts, and then loads them into the store. For example, if you have a payload that contains embedded records, they will be extracted by the serializer and loaded into the store. For example: ```javascript adapter.load(store, App.Person, { id: 123, firstName: "Yehuda", lastName: "Katz", occupations: [{ id: 345, title: "Tricycle Mechanic" }] }); ``` This will load the payload for the `App.Person` with ID `123` and the embedded `App.Occupation` with ID `345`. @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload */ load: function(store, type, payload) { var loader = loaderFor(store); get(this, 'serializer').extractRecordRepresentation(loader, type, payload); }, /** Acknowledges that the adapter has finished creating a record. Your adapter should call this method from `createRecord` when it has saved a new record to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the creation, and you want to update the existing record with the new information, pass the payload as the fourth parameter. For example, the `RESTAdapter` saves newly created records by making an Ajax request. When the server returns, the adapter calls didCreateRecord. If the server returns a response body, it is passed as the payload. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didCreateRecord: function(store, type, record, payload) { store.didSaveRecord(record); if (payload) { var loader = DS.loaderFor(store); loader.load = function(type, data, prematerialized) { store.updateId(record, data); return store.load(type, data, prematerialized); }; get(this, 'serializer').extract(loader, payload, type); } }, /** Acknowledges that the adapter has finished creating several records. Your adapter should call this method from `createRecords` when it has saved multiple created records to its persistent storage received an acknowledgement. If the persistent storage returns a new payload in response to the creation, and you want to update the existing record with the new information, pass the payload as the fourth parameter. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didCreateRecords: function(store, type, records, payload) { records.forEach(function(record) { store.didSaveRecord(record); }, this); if (payload) { var loader = DS.loaderFor(store); get(this, 'serializer').extractMany(loader, payload, type, records); } }, /** @private Acknowledges that the adapter has finished updating or deleting a record. Your adapter should call this method from `updateRecord` or `deleteRecord` when it has updated or deleted a record to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the update or delete, and you want to update the existing record with the new information, pass the payload as the fourth parameter. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didSaveRecord: function(store, type, record, payload) { store.didSaveRecord(record); var serializer = get(this, 'serializer'), mappings = serializer.mappingForType(type); serializer.eachEmbeddedRecord(record, function(embeddedRecord, embeddedType) { if (embeddedType === 'load') { return; } this.didSaveRecord(store, embeddedRecord.constructor, embeddedRecord); }, this); if (payload) { var loader = DS.loaderFor(store); serializer.extract(loader, payload, type); } }, /** Acknowledges that the adapter has finished updating a record. Your adapter should call this method from `updateRecord` when it has updated a record to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the update, pass the payload as the fourth parameter. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didUpdateRecord: function() { this.didSaveRecord.apply(this, arguments); }, /** Acknowledges that the adapter has finished deleting a record. Your adapter should call this method from `deleteRecord` when it has deleted a record from its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the deletion, pass the payload as the fourth parameter. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @param {any} payload */ didDeleteRecord: function() { this.didSaveRecord.apply(this, arguments); }, /** Acknowledges that the adapter has finished updating or deleting multiple records. Your adapter should call this method from its `updateRecords` or `deleteRecords` when it has updated or deleted multiple records to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the creation, pass the payload as the fourth parameter. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} records @param {any} payload */ didSaveRecords: function(store, type, records, payload) { records.forEach(function(record) { store.didSaveRecord(record); }, this); if (payload) { var loader = DS.loaderFor(store); get(this, 'serializer').extractMany(loader, payload, type); } }, /** Acknowledges that the adapter has finished updating multiple records. Your adapter should call this method from its `updateRecords` when it has updated multiple records to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the update, pass the payload as the fourth parameter. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} records @param {any} payload */ didUpdateRecords: function() { this.didSaveRecords.apply(this, arguments); }, /** Acknowledges that the adapter has finished updating multiple records. Your adapter should call this method from its `deleteRecords` when it has deleted multiple records to its persistent storage and received an acknowledgement. If the persistent storage returns a new payload in response to the deletion, pass the payload as the fourth parameter. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} records @param {any} payload */ didDeleteRecords: function() { this.didSaveRecords.apply(this, arguments); }, /** Loads the response to a request for a record by ID. Your adapter should call this method from its `find` method with the response from the backend. You should pass the same ID to this method that was given to your find method so that the store knows which record to associate the new data with. @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload @param {String} id */ didFindRecord: function(store, type, payload, id) { var loader = DS.loaderFor(store); loader.load = function(type, data, prematerialized) { prematerialized = prematerialized || {}; prematerialized.id = id; return store.load(type, data, prematerialized); }; get(this, 'serializer').extract(loader, payload, type); }, /** Loads the response to a request for all records by type. You adapter should call this method from its `findAll` method with the response from the backend. @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload */ didFindAll: function(store, type, payload) { var loader = DS.loaderFor(store), serializer = get(this, 'serializer'); store.didUpdateAll(type); serializer.extractMany(loader, payload, type); }, /** Loads the response to a request for records by query. Your adapter should call this method from its `findQuery` method with the response from the backend. @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload @param {DS.AdapterPopulatedRecordArray} recordArray */ didFindQuery: function(store, type, payload, recordArray) { var loader = DS.loaderFor(store); loader.populateArray = function(data) { recordArray.load(data); }; get(this, 'serializer').extractMany(loader, payload, type); }, /** Loads the response to a request for many records by ID. You adapter should call this method from its `findMany` method with the response from the backend. @param {DS.Store} store @param {subclass of DS.Model} type @param {any} payload */ didFindMany: function(store, type, payload) { var loader = DS.loaderFor(store); get(this, 'serializer').extractMany(loader, payload, type); }, /** Notifies the store that a request to the backend returned an error. Your adapter should call this method to indicate that the backend returned an error for a request. @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record */ didError: function(store, type, record) { store.recordWasError(record); }, dirtyRecordsForAttributeChange: function(dirtySet, record, attributeName, newValue, oldValue) { if (newValue !== oldValue) { // If this record is embedded, add its parent // to the dirty set. this.dirtyRecordsForRecordChange(dirtySet, record); } }, dirtyRecordsForRecordChange: function(dirtySet, record) { dirtySet.add(record); }, dirtyRecordsForBelongsToChange: function(dirtySet, child) { this.dirtyRecordsForRecordChange(dirtySet, child); }, dirtyRecordsForHasManyChange: function(dirtySet, parent) { this.dirtyRecordsForRecordChange(dirtySet, parent); }, /** @private This method recursively climbs the superclass hierarchy and registers any class-registered transforms on the adapter's serializer. Once it registers a transform for a given type, it ignores subsequent transforms for the same attribute type. @param {Class} klass the DS.Adapter subclass to extract the transforms from @param {DS.Serializer} serializer the serializer to register the transforms onto @param {Object} seen a hash of attributes already seen */ registerSerializerTransforms: function(klass, serializer, seen) { var transforms = klass._registeredTransforms, superclass, prop; for (prop in transforms) { if (!transforms.hasOwnProperty(prop) || prop in seen) { continue; } seen[prop] = true; serializer.registerTransform(prop, transforms[prop]); } if (superclass = klass.superclass) { this.registerSerializerTransforms(superclass, serializer, seen); } }, /** @private This method recursively climbs the superclass hierarchy and registers any class-registered mappings on the adapter's serializer. @param {Class} klass the DS.Adapter subclass to extract the transforms from @param {DS.Serializer} serializer the serializer to register the mappings onto */ registerSerializerMappings: function(serializer) { var mappings = this._attributesMap, configurations = this._configurationsMap; mappings.forEach(serializer.map, serializer); configurations.forEach(serializer.configure, serializer); }, /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `load()` method to load the record. Here is an example `find` implementation: find: function(store, type, id) { var url = type.url; url = url.fmt(id); jQuery.getJSON(url, function(data) { // data is a hash of key/value pairs. If your server returns a // root, simply do something like: // store.load(type, id, data.person) store.load(type, id, data); }); } */ find: null, serializer: DS.JSONSerializer, registerTransform: function(attributeType, transform) { get(this, 'serializer').registerTransform(attributeType, transform); }, /** A public method that allows you to register an enumerated type on your adapter. This is useful if you want to utilize a text representation of an integer value. Eg: Say you want to utilize "low","medium","high" text strings in your app, but you want to persist those as 0,1,2 in your backend. You would first register the transform on your adapter instance: adapter.registerEnumTransform('priority', ['low', 'medium', 'high']); You would then refer to the 'priority' DS.attr in your model: App.Task = DS.Model.extend({ priority: DS.attr('priority') }); And lastly, you would set/get the text representation on your model instance, but the transformed result will be the index number of the type. App: myTask.get('priority') => 'low' Server Response / Load: { myTask: {priority: 0} } @param {String} type of the transform @param {Array} array of String objects to use for the enumerated values. This is an ordered list and the index values will be used for the transform. */ registerEnumTransform: function(attributeType, objects) { get(this, 'serializer').registerEnumTransform(attributeType, objects); }, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } */ generateIdForRecord: null, materialize: function(record, data, prematerialized) { get(this, 'serializer').materialize(record, data, prematerialized); }, serialize: function(record, options) { return get(this, 'serializer').serialize(record, options); }, extractId: function(type, data) { return get(this, 'serializer').extractId(type, data); }, groupByType: function(enumerable) { var map = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.OrderedSet.create(); } }); enumerable.forEach(function(item) { map.get(item.constructor).add(item); }); return map; }, commit: function(store, commitDetails) { this.save(store, commitDetails); }, save: function(store, commitDetails) { var adapter = this; function filter(records) { var filteredSet = Ember.OrderedSet.create(); records.forEach(function(record) { if (adapter.shouldSave(record)) { filteredSet.add(record); } }); return filteredSet; } this.groupByType(commitDetails.created).forEach(function(type, set) { this.createRecords(store, type, filter(set)); }, this); this.groupByType(commitDetails.updated).forEach(function(type, set) { this.updateRecords(store, type, filter(set)); }, this); this.groupByType(commitDetails.deleted).forEach(function(type, set) { this.deleteRecords(store, type, filter(set)); }, this); }, shouldSave: Ember.K, createRecords: function(store, type, records) { records.forEach(function(record) { this.createRecord(store, type, record); }, this); }, updateRecords: function(store, type, records) { records.forEach(function(record) { this.updateRecord(store, type, record); }, this); }, deleteRecords: function(store, type, records) { records.forEach(function(record) { this.deleteRecord(store, type, record); }, this); }, findMany: function(store, type, ids) { ids.forEach(function(id) { this.find(store, type, id); }, this); } }); DS.Adapter.reopenClass({ registerTransform: function(attributeType, transform) { var registeredTransforms = this._registeredTransforms || {}; registeredTransforms[attributeType] = transform; this._registeredTransforms = registeredTransforms; }, map: DS._Mappable.generateMapFunctionFor('attributes', function(key, newValue, map) { var existingValue = map.get(key); merge(existingValue, newValue); }), configure: DS._Mappable.generateMapFunctionFor('configurations', function(key, newValue, map) { var existingValue = map.get(key); // If a mapping configuration is provided, peel it off and apply it // using the DS.Adapter.map API. var mappings = newValue && newValue.mappings; if (mappings) { this.map(key, mappings); delete newValue.mappings; } merge(existingValue, newValue); }), resolveMapConflict: function(oldValue, newValue, mappingsKey) { merge(newValue, oldValue); return newValue; } }); })(); (function() { var get = Ember.get, set = Ember.set; DS.FixtureSerializer = DS.Serializer.extend({ deserializeValue: function(value, attributeType) { return value; }, serializeValue: function(value, attributeType) { return value; }, addId: function(data, key, id) { data[key] = id; }, addAttribute: function(hash, key, value) { hash[key] = value; }, addBelongsTo: function(hash, record, key, relationship) { var id = get(record, relationship.key+'.id'); if (!Ember.isNone(id)) { hash[key] = id; } }, addHasMany: function(hash, record, key, relationship) { var ids = get(record, relationship.key).map(function(item) { return item.get('id'); }); hash[relationship.key] = ids; }, extract: function(loader, fixture, type, record) { if (record) { loader.updateId(record, fixture); } this.extractRecordRepresentation(loader, type, fixture); }, extractMany: function(loader, fixtures, type, records) { var objects = fixtures, references = []; if (records) { records = records.toArray(); } for (var i = 0; i < objects.length; i++) { if (records) { loader.updateId(records[i], objects[i]); } var reference = this.extractRecordRepresentation(loader, type, objects[i]); references.push(reference); } loader.populateArray(references); }, extractId: function(type, hash) { var primaryKey = this._primaryKey(type); if (hash.hasOwnProperty(primaryKey)) { // Ensure that we coerce IDs to strings so that record // IDs remain consistent between application runs; especially // if the ID is serialized and later deserialized from the URL, // when type information will have been lost. return hash[primaryKey]+''; } else { return null; } }, extractAttribute: function(type, hash, attributeName) { var key = this._keyForAttributeName(type, attributeName); return hash[key]; }, extractHasMany: function(type, hash, key) { return hash[key]; }, extractBelongsTo: function(type, hash, key) { return hash[key]; }, extractBelongsToPolymorphic: function(type, hash, key) { var keyForId = this.keyForPolymorphicId(key), keyForType, id = hash[keyForId]; if (id) { keyForType = this.keyForPolymorphicType(key); return {id: id, type: hash[keyForType]}; } return null; }, keyForPolymorphicId: function(key) { return key; }, keyForPolymorphicType: function(key) { return key + '_type'; } }); })(); (function() { var get = Ember.get, fmt = Ember.String.fmt, dump = Ember.get(window, 'JSON.stringify') || function(object) { return object.toString(); }; /** `DS.FixtureAdapter` is an adapter that loads records from memory. Its primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but are not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. Its possible to do develop your entire application with `DS.FixtureAdapter`. */ DS.FixtureAdapter = DS.Adapter.extend({ simulateRemoteResponse: true, latency: 50, serializer: DS.FixtureSerializer, /* Implement this method in order to provide data associated with a type */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ if(!fixture.id){ throw new Error(fmt('the id property must be defined for fixture %@', [dump(fixture)])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /* Implement this method in order to query fixtures data */ queryFixtures: function(fixtures, query, type) { Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); }, updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /* Implement this method in order to provide provide json for CRUD methods */ mockJSON: function(type, record) { return this.serialize(record, { includeId: true }); }, /* Adapter methods */ generateIdForRecord: function(store, record) { return Ember.guidFor(record); }, find: function(store, type, id) { var fixtures = this.fixturesForType(type), fixture; Ember.warn("Unable to find fixtures for model type " + type.toString(), fixtures); if (fixtures) { fixture = Ember.A(fixtures).findProperty('id', id); } if (fixture) { this.simulateRemoteCall(function() { this.didFindRecord(store, type, fixture, id); }, this); } }, findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); if (fixtures) { fixtures = fixtures.filter(function(item) { return ids.indexOf(item.id) !== -1; }); } if (fixtures) { this.simulateRemoteCall(function() { this.didFindMany(store, type, fixtures); }, this); } }, findAll: function(store, type) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); this.simulateRemoteCall(function() { this.didFindAll(store, type, fixtures); }, this); }, findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { this.simulateRemoteCall(function() { this.didFindQuery(store, type, fixtures, array); }, this); } }, createRecord: function(store, type, record) { var fixture = this.mockJSON(type, record); this.updateFixtures(type, fixture); this.simulateRemoteCall(function() { this.didCreateRecord(store, type, record, fixture); }, this); }, updateRecord: function(store, type, record) { var fixture = this.mockJSON(type, record); this.updateFixtures(type, fixture); this.simulateRemoteCall(function() { this.didUpdateRecord(store, type, record, fixture); }, this); }, deleteRecord: function(store, type, record) { var fixture = this.mockJSON(type, record); this.deleteLoadedFixture(type, fixture); this.simulateRemoteCall(function() { this.didDeleteRecord(store, type, record); }, this); }, /* @private */ deleteLoadedFixture: function(type, record) { var id = this.extractId(type, record); var existingFixture = this.findExistingFixture(type, record); if(existingFixture) { var index = type.FIXTURES.indexOf(existingFixture); type.FIXTURES.splice(index, 1); return true; } }, findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = this.extractId(type, record); return this.findFixtureById(fixtures, id); }, findFixtureById: function(fixtures, id) { var adapter = this; return Ember.A(fixtures).find(function(r) { if(''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, simulateRemoteCall: function(callback, context) { if (get(this, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(context, callback, get(this, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.once(context, callback); } } }); })(); (function() { var get = Ember.get; DS.RESTSerializer = DS.JSONSerializer.extend({ keyForAttributeName: function(type, name) { return Ember.String.decamelize(name); }, keyForBelongsTo: function(type, name) { var key = this.keyForAttributeName(type, name); if (this.embeddedType(type, name)) { return key; } return key + "_id"; }, keyForHasMany: function(type, name) { var key = this.keyForAttributeName(type, name); if (this.embeddedType(type, name)) { return key; } return this.singularize(key) + "_ids"; }, keyForPolymorphicId: function(key) { return key; }, keyForPolymorphicType: function(key) { return key.replace(/_id$/, '_type'); }, extractValidationErrors: function(type, json) { var errors = {}; get(type, 'attributes').forEach(function(name) { var key = this._keyForAttributeName(type, name); if (json['errors'].hasOwnProperty(key)) { errors[name] = json['errors'][key]; } }, this); return errors; } }); })(); (function() { /*global jQuery*/ var get = Ember.get, set = Ember.set, merge = Ember.merge; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { title: "I'm Running to Reform the W3C's Tag", author: "Yehuda Katz" } } ``` ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` */ DS.RESTAdapter = DS.Adapter.extend({ bulkCommit: false, since: 'since', serializer: DS.RESTSerializer, init: function() { this._super.apply(this, arguments); }, shouldSave: function(record) { var reference = get(record, '_reference'); return !reference.parent; }, dirtyRecordsForRecordChange: function(dirtySet, record) { this._dirtyTree(dirtySet, record); }, dirtyRecordsForHasManyChange: function(dirtySet, record, relationship) { var embeddedType = get(this, 'serializer').embeddedType(record.constructor, relationship.secondRecordName); if (embeddedType === 'always') { relationship.childReference.parent = relationship.parentReference; this._dirtyTree(dirtySet, record); } }, _dirtyTree: function(dirtySet, record) { dirtySet.add(record); get(this, 'serializer').eachEmbeddedRecord(record, function(embeddedRecord, embeddedType) { if (embeddedType !== 'always') { return; } if (dirtySet.has(embeddedRecord)) { return; } this._dirtyTree(dirtySet, embeddedRecord); }, this); var reference = record.get('_reference'); if (reference.parent) { var store = get(record, 'store'); var parent = store.recordForReference(reference.parent); this._dirtyTree(dirtySet, parent); } }, createRecord: function(store, type, record) { var root = this.rootForType(type); var data = {}; data[root] = this.serialize(record, { includeId: true }); this.ajax(this.buildURL(root), "POST", { data: data, success: function(json) { Ember.run(this, function(){ this.didCreateRecord(store, type, record, json); }); }, error: function(xhr) { this.didError(store, type, record, xhr); } }); }, createRecords: function(store, type, records) { if (get(this, 'bulkCommit') === false) { return this._super(store, type, records); } var root = this.rootForType(type), plural = this.pluralize(root); var data = {}; data[plural] = []; records.forEach(function(record) { data[plural].push(this.serialize(record, { includeId: true })); }, this); this.ajax(this.buildURL(root), "POST", { data: data, success: function(json) { Ember.run(this, function(){ this.didCreateRecords(store, type, records, json); }); } }); }, updateRecord: function(store, type, record) { var id = get(record, 'id'); var root = this.rootForType(type); var data = {}; data[root] = this.serialize(record); this.ajax(this.buildURL(root, id), "PUT", { data: data, success: function(json) { Ember.run(this, function(){ this.didUpdateRecord(store, type, record, json); }); }, error: function(xhr) { this.didError(store, type, record, xhr); } }); }, updateRecords: function(store, type, records) { if (get(this, 'bulkCommit') === false) { return this._super(store, type, records); } var root = this.rootForType(type), plural = this.pluralize(root); var data = {}; data[plural] = []; records.forEach(function(record) { data[plural].push(this.serialize(record, { includeId: true })); }, this); this.ajax(this.buildURL(root, "bulk"), "PUT", { data: data, success: function(json) { Ember.run(this, function(){ this.didUpdateRecords(store, type, records, json); }); } }); }, deleteRecord: function(store, type, record) { var id = get(record, 'id'); var root = this.rootForType(type); this.ajax(this.buildURL(root, id), "DELETE", { success: function(json) { Ember.run(this, function(){ this.didDeleteRecord(store, type, record, json); }); }, error: function(xhr) { this.didError(store, type, record, xhr); } }); }, deleteRecords: function(store, type, records) { if (get(this, 'bulkCommit') === false) { return this._super(store, type, records); } var root = this.rootForType(type), plural = this.pluralize(root), serializer = get(this, 'serializer'); var data = {}; data[plural] = []; records.forEach(function(record) { data[plural].push(serializer.serializeId( get(record, 'id') )); }); this.ajax(this.buildURL(root, 'bulk'), "DELETE", { data: data, success: function(json) { Ember.run(this, function(){ this.didDeleteRecords(store, type, records, json); }); } }); }, find: function(store, type, id) { var root = this.rootForType(type); this.ajax(this.buildURL(root, id), "GET", { success: function(json) { Ember.run(this, function(){ this.didFindRecord(store, type, json, id); }); } }); }, findAll: function(store, type, since) { var root = this.rootForType(type); this.ajax(this.buildURL(root), "GET", { data: this.sinceQuery(since), success: function(json) { Ember.run(this, function(){ this.didFindAll(store, type, json); }); } }); }, findQuery: function(store, type, query, recordArray) { var root = this.rootForType(type); this.ajax(this.buildURL(root), "GET", { data: query, success: function(json) { Ember.run(this, function(){ this.didFindQuery(store, type, json, recordArray); }); } }); }, findMany: function(store, type, ids, owner) { var root = this.rootForType(type); ids = this.serializeIds(ids); this.ajax(this.buildURL(root), "GET", { data: {ids: ids}, success: function(json) { Ember.run(this, function(){ this.didFindMany(store, type, json); }); } }); }, /** @private This method serializes a list of IDs using `serializeId` @returns {Array} an array of serialized IDs */ serializeIds: function(ids) { var serializer = get(this, 'serializer'); return Ember.EnumerableUtils.map(ids, function(id) { return serializer.serializeId(id); }); }, didError: function(store, type, record, xhr) { if (xhr.status === 422) { var json = JSON.parse(xhr.responseText), serializer = get(this, 'serializer'), errors = serializer.extractValidationErrors(type, json); store.recordWasInvalid(record, errors); } else { this._super.apply(this, arguments); } }, ajax: function(url, type, hash) { hash.url = url; hash.type = type; hash.dataType = 'json'; hash.contentType = 'application/json; charset=utf-8'; hash.context = this; if (hash.data && type !== 'GET') { hash.data = JSON.stringify(hash.data); } jQuery.ajax(hash); }, url: "", rootForType: function(type) { var serializer = get(this, 'serializer'); return serializer.rootForType(type); }, pluralize: function(string) { var serializer = get(this, 'serializer'); return serializer.pluralize(string); }, buildURL: function(record, suffix) { var url = [this.url]; Ember.assert("Namespace URL (" + this.namespace + ") must not start with slash", !this.namespace || this.namespace.toString().charAt(0) !== "/"); Ember.assert("Record URL (" + record + ") must not start with slash", !record || record.toString().charAt(0) !== "/"); Ember.assert("URL suffix (" + suffix + ") must not start with slash", !suffix || suffix.toString().charAt(0) !== "/"); if (this.namespace !== undefined) { url.push(this.namespace); } url.push(this.pluralize(record)); if (suffix !== undefined) { url.push(suffix); } return url.join("/"); }, sinceQuery: function(since) { var query = {}; query[get(this, 'since')] = since; return since ? query : null; } }); })(); (function() { var camelize = Ember.String.camelize, capitalize = Ember.String.capitalize, get = Ember.get, map = Ember.ArrayPolyfills.map, registeredTransforms; var passthruTransform = { serialize: function(value) { return value; }, deserialize: function(value) { return value; } }; var defaultTransforms = { string: passthruTransform, boolean: passthruTransform, number: passthruTransform }; function camelizeKeys(json) { var value; for (var prop in json) { value = json[prop]; delete json[prop]; json[camelize(prop)] = value; } } function munge(json, callback) { callback(json); } function applyTransforms(json, type, transformType) { var transforms = registeredTransforms[transformType]; Ember.assert("You are trying to apply the '" + transformType + "' transforms, but you didn't register any transforms with that name", transforms); get(type, 'attributes').forEach(function(name, attribute) { var attributeType = attribute.type, value = json[name]; var transform = transforms[attributeType] || defaultTransforms[attributeType]; Ember.assert("Your model specified the '" + attributeType + "' type for the '" + name + "' attribute, but no transform for that type was registered", transform); json[name] = transform.deserialize(value); }); } function ObjectProcessor(json, type, store) { this.json = json; this.type = type; this.store = store; } ObjectProcessor.prototype = { camelizeKeys: function() { camelizeKeys(this.json); return this; }, munge: function(callback) { munge(this.json, callback); return this; }, applyTransforms: function(transformType) { applyTransforms(this.json, this.type, transformType); return this; } }; function LoadObjectProcessor() { ObjectProcessor.apply(this, arguments); } LoadObjectProcessor.prototype = Ember.create(ObjectProcessor.prototype); LoadObjectProcessor.prototype.load = function() { this.store.load(this.type, {}, this.json); }; function loadObjectProcessorFactory(store, type) { return function(json) { return new LoadObjectProcessor(json, type, store); }; } function ArrayProcessor(json, type, array, store) { this.json = json; this.type = type; this.array = array; this.store = store; } ArrayProcessor.prototype = { load: function() { var store = this.store, type = this.type; var references = this.json.map(function(object) { return store.load(type, {}, object); }); this.array.load(references); }, camelizeKeys: function() { this.json.forEach(camelizeKeys); return this; }, munge: function(callback) { this.json.forEach(function(object) { munge(object, callback); }); return this; }, applyTransforms: function(transformType) { var type = this.type; this.json.forEach(function(object) { applyTransforms(object, type, transformType); }); return this; } }; function arrayProcessorFactory(store, type, array) { return function(json) { return new ArrayProcessor(json, type, array, store); }; } var HasManyProcessor = function(json, store, record, relationship) { this.json = json; this.store = store; this.record = record; this.type = record.constructor; this.relationship = relationship; }; HasManyProcessor.prototype = Ember.create(ArrayProcessor.prototype); HasManyProcessor.prototype.load = function() { var store = this.store; var ids = map.call(this.json, function(obj) { return obj.id; }); store.loadMany(this.relationship.type, this.json); store.loadHasMany(this.record, this.relationship.key, ids); }; function hasManyProcessorFactory(store, record, relationship) { return function(json) { return new HasManyProcessor(json, store, record, relationship); }; } function SaveProcessor(record, store, type, includeId) { this.record = record; ObjectProcessor.call(this, record.toJSON({ includeId: includeId }), type, store); } SaveProcessor.prototype = Ember.create(ObjectProcessor.prototype); SaveProcessor.prototype.save = function(callback) { callback(this.json); }; function saveProcessorFactory(store, type, includeId) { return function(record) { return new SaveProcessor(record, store, type, includeId); }; } DS.BasicAdapter = DS.Adapter.extend({ find: function(store, type, id) { var sync = type.sync; Ember.assert("You are trying to use the BasicAdapter to find id '" + id + "' of " + type + " but " + type + ".sync was not found", sync); Ember.assert("The sync code on " + type + " does not implement find(), but you are trying to find id '" + id + "'.", sync.find); sync.find(id, loadObjectProcessorFactory(store, type)); }, findQuery: function(store, type, query, recordArray) { var sync = type.sync; Ember.assert("You are trying to use the BasicAdapter to query " + type + " but " + type + ".sync was not found", sync); Ember.assert("The sync code on " + type + " does not implement query(), but you are trying to query " + type + ".", sync.query); sync.query(query, arrayProcessorFactory(store, type, recordArray)); }, findHasMany: function(store, record, relationship, data) { var name = capitalize(relationship.key), sync = record.constructor.sync, processor = hasManyProcessorFactory(store, record, relationship); Ember.assert("You are trying to use the BasicAdapter to query " + record.constructor + " but " + record.constructor + ".sync was not found", sync); var options = { relationship: relationship.key, data: data }; if (sync['find'+name]) { sync['find' + name](record, options, processor); } else if (sync.findHasMany) { sync.findHasMany(record, options, processor); } else { Ember.assert("You are trying to use the BasicAdapter to find the " + relationship.key + " has-many relationship, but " + record.constructor + ".sync did not implement findHasMany or find" + name + ".", false); } }, createRecord: function(store, type, record) { var sync = type.sync; Ember.assert("You are trying to use the BasicAdapter to query " + type + " but " + type + ".sync was not found", sync); Ember.assert("The sync code on " + type + " does not implement createRecord(), but you are trying to create a " + type + " record", sync.createRecord); sync.createRecord(record, saveProcessorFactory(store, type)); }, updateRecord: function(store, type, record) { var sync = type.sync; Ember.assert("You are trying to use the BasicAdapter to query " + type + " but " + type + ".sync was not found", sync); Ember.assert("The sync code on " + type + " does not implement updateRecord(), but you are trying to update a " + type + " record", sync.updateRecord); sync.updateRecord(record, saveProcessorFactory(store, type, true)); }, deleteRecord: function(store, type, record) { var sync = type.sync; Ember.assert("You are trying to use the BasicAdapter to query " + type + " but " + type + ".sync was not found", sync); Ember.assert("The sync code on " + type + " does not implement deleteRecord(), but you are trying to delete a " + type + " record", sync.deleteRecord); sync.deleteRecord(record, saveProcessorFactory(store, type, true)); } }); DS.registerTransforms = function(kind, object) { registeredTransforms[kind] = object; }; DS.clearTransforms = function() { registeredTransforms = {}; }; DS.clearTransforms(); })(); (function() { })(); (function() { //Copyright (C) 2011 by Living Social, Inc. //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. })();
src/components/AdminDocOrder.js
aurigadl/EnvReactAsk
import React from 'react' import { Button, Select, Form } from 'antd'; const FormItem = Form.Item; const ButtonGroup = Button.Group; const Option = Select.Option; const AdminDocDate = React.createClass({ render: function () { const formItemLayout = { labelCol: { sm: { span: 6 }, }, wrapperCol: { sm: { span: 18 }, }, }; return ( <div> <h4> Identificacíon y Clasificacón de Documentos: </h4> <p> Crea, activa e inactiva documentos. Clasificlos segun el tipo de movimientos que se realicen en la organización, documentos como Entrada, Salida, Factura, Memorando, Edicto y las referencias que requieras, en las cuales se agrupen a un gran numero de documentos. </p> <FormItem {...formItemLayout} label="Orden 1" style={{ 'marginTop': 30 }}> <Select style={{ width: 120 }} > <Option value=""> -- Ninguno --</Option> <Option value="0">Documento</Option> <Option value="1">Consecutivo</Option> <Option value="2">Grupo</Option> <Option value="3">Fecha</Option> <Option value="4">Comodin</Option> </Select> </FormItem> <FormItem {...formItemLayout} label="Orden 2" > <Select style={{ width: 120 }} > <Option value=""> -- Ninguno --</Option> <Option value="0">Documento</Option> <Option value="1">Consecutivo</Option> <Option value="2">Grupo</Option> <Option value="3">Fecha</Option> <Option value="4">Comodin</Option> </Select> </FormItem> <FormItem {...formItemLayout} label="Orden 3" > <Select style={{ width: 120 }} > <Option value=""> -- Ninguno --</Option> <Option value="0">Documento</Option> <Option value="1">Consecutivo</Option> <Option value="2">Grupo</Option> <Option value="3">Fecha</Option> <Option value="4">Comodin</Option> </Select> </FormItem> <FormItem {...formItemLayout} label="Orden 4" > <Select style={{ width: 120 }} > <Option value=""> -- Ninguno --</Option> <Option value="0">Documento</Option> <Option value="1">Consecutivo</Option> <Option value="2">Grupo</Option> <Option value="3">Fecha</Option> <Option value="4">Comodin</Option> </Select> </FormItem> <FormItem {...formItemLayout} label="Orden 5" > <Select style={{ width: 120 }} > <Option value=""> -- Ninguno --</Option> <Option value="0">Documento</Option> <Option value="1">Consecutivo</Option> <Option value="2">Grupo</Option> <Option value="3">Fecha</Option> <Option value="4">Comodin</Option> </Select> </FormItem> <ButtonGroup> <Button>Restaurar</Button> <Button type="primary">Grabar</Button> </ButtonGroup> </div> ); } }) export default AdminDocDate