target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
app/javascript/src/components/conversations/QuickReplyDialog.js
michelson/chaskiq
import React from 'react' import { connect } from 'react-redux' import { successMessage, errorMessage } from '../../actions/status_messages' import FormDialog from '../FormDialog' import Button from '../Button' import graphql from '../../graphql/client' import { QUICK_REPLY_CREATE } from '../../graphql/mutations' function QuickReplyDialog ({ open, app, lang, dispatch, closeHandler }) { const [isOpen, setIsOpen] = React.useState(open) const [title, setTitle] = React.useState('') React.useEffect(() => { setIsOpen(open) }, [open]) function close () { setIsOpen(false) closeHandler && closeHandler() } function createQuickReply () { graphql(QUICK_REPLY_CREATE, { appKey: app.key, title: title, content: open, lang: lang }, { success: (_data) => { close() dispatch(successMessage( I18n.t('quick_replies.create.success') )) }, error: (_err) => { dispatch(errorMessage( I18n.t('quick_replies.create.error') )) } }) } return <div> {isOpen && ( <FormDialog open={isOpen} handleClose={closeHandler} titleContent={ I18n.t('quick_replies.add_as_dialog.title') } formComponent={ <form> <input className="shadow appearance-none border border-gray-500 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" onChange={(e) => setTitle(e.target.value) } placeholder={'add title'} /> </form> } dialogButtons={ <React.Fragment> { title && <Button onClick={createQuickReply} className="ml-2" variant="danger"> {I18n.t('common.create')} </Button> } <Button onClick={close} variant="outlined"> {I18n.t('common.cancel')} </Button> </React.Fragment> } ></FormDialog> )} </div> } function mapStateToProps (state) { const { app } = state return { app } } export default connect(mapStateToProps)(QuickReplyDialog)
storybook/stories/button.story.js
imomix/mastodon
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import Button from 'mastodon/components/button'; storiesOf('Button', module) .add('default state', () => ( <Button text='submit' onClick={action('clicked')} /> )) .add('secondary', () => ( <Button secondary text='submit' onClick={action('clicked')} /> )) .add('disabled', () => ( <Button disabled text='submit' onClick={action('clicked')} /> )) .add('block', () => ( <Button block text='submit' onClick={action('clicked')} /> ));
src/components/Common/PublicationInfo/index.js
LifeSourceUA/lifesource.ua
/** * [IL] * Library Import */ import React, { Component } from 'react'; import { connect } from 'react-redux'; /** * [IV] * View Import */ import Common from './Views/Common'; /** * [ICONF] * Config Import */ import config from './config'; /** * [IRDX] * Redux connect (optional) */ @connect((state) => { return { mediaType: state.browser.mediaType }; }) class PublicationInfo extends Component { /** * [CDN] * Component display name */ static displayName = config.id; /** * [CR] * Render function */ render = () => { /** * [RV] * View */ const view = ( <Common { ...this.props }/> ); /** * [RR] * Return Component */ return view; } } /** * [IE] * Export */ export default PublicationInfo;
js/vendor/contrib/libs/jquery-ui/tests/jquery-1.8.0.js
khalid-s/psa-recovery
/*! * jQuery JavaScript Library v1.8.0 * 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 Aug 09 2012 16:24:48 GMT-0400 (Eastern Daylight 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+/, // IE doesn't match non-breaking spaces with \s rtrim = core_rnotwhite.test("\xA0") ? (/^[\s\xA0]+|[\s\xA0]+$/g) : /^\s+|\s+$/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.0", // 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.toUpperCase() === name.toUpperCase(); }, // 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 ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : text.toString().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 || proxy.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. if ( document.readyState === "complete" || ( document.readyState !== "loading" && document.addEventListener ) ) { // 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 ) { if ( jQuery.isFunction( arg ) && ( !options.unique || !self.has( arg ) ) ) { list.push( arg ); } else if ( arg && arg.length ) { // 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 typeof obj === "object" ? 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 || !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.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, window.getComputedStyle was used here // instead of getComputedStyle because it gave a better gzip size. // The difference between window.getComputedStyle and getComputedStyle is // 7 bytes 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 = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // 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 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.uuid; } 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-" ) === 0 ) { 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 ), 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(); } 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 ( !queue.length && 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-- ) { if ( (tmp = jQuery._data( elements[ i ], type + "queueHooks" )) && 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 ] + " " ) ) { 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 ] + " ") > -1 ) { 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 ) > -1 ) { 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, 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( 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, jqcur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].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") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #xxxx) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = jqcur.is( sel ); } 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: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, 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, dirruns, sortOrder, siblingCheck, assertGetIdNotName, document = window.document, docElem = document.documentElement, strundefined = "undefined", hasDuplicate = false, baseHasDuplicate = true, done = 0, slice = [].slice, push = [].push, expando = ( "sizcache" + Math.random() ).replace( ".", "" ), // 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 + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)", pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)", combinators = whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*", groups = "(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|" + attributes + "|" + pseudos.replace( 2, 7 ) + "|[^\\\\(),])+", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcombinators = new RegExp( "^" + combinators ), // All simple (non-comma) selectors, excluding insignifant trailing whitespace rgroups = new RegExp( groups + "?(?=" + whitespace + "*,|$)", "g" ), // A selector, or everything after leading whitespace // Optionally followed in either case by a ")" for terminating sub-selectors rselector = new RegExp( "^(?:(?!,)(?:(?:^|,)" + whitespace + "*" + groups + ")*?|" + whitespace + "*(.*?))(\\)|$)" ), // All combinators and selector components (attribute test, tag, pseudo, etc.), the latter appearing together when consecutive rtokens = new RegExp( groups.slice( 19, -6 ) + "\\x20\\t\\r\\n\\f>+~])+|" + combinators, "g" ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, 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( "[-", "[-\\*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "POS": new RegExp( pos, "ig" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, classCache = {}, cachedClasses = [], compilerCache = {}, cachedSelectors = [], // Mark a function for use in filtering markFunction = function( fn ) { fn.sizzleFilter = true; return fn; }, // Returns a function to use in pseudos for input types createInputFunction = function( type ) { return function( elem ) { // Check the input's nodeName and type return elem.nodeName.toLowerCase() === "input" && elem.type === type; }; }, // Returns a function to use in pseudos for buttons createButtonFunction = function( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; }, // Used for testing something on an element assert = function( fn ) { var pass = false, div = document.createElement("div"); try { pass = fn( div ); } catch (e) {} // release memory in IE div = null; return pass; }, // 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 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 === // buggy browsers will return more than the correct 0 2 + document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }), // Check if the browser returns only elements // when doing getElementsByTagName("*") assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return div.getElementsByTagName("*").length === 0; }), // 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 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 === 0 ) { return false; } // Safari caches class attributes, doesn't catch changes (in 3.2) div.lastChild.className = "e"; return div.getElementsByClassName("e").length !== 1; }); var Sizzle = function( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( nodeType !== 1 && nodeType !== 9 ) { return []; } if ( !selector || typeof selector !== "string" ) { return results; } 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, context, results, seed, xml ); }; var Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, match: matchExpr, order: [ "ID", "TAG" ], attrHandle: {}, createPseudo: markFunction, 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; } }, 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 argument, unquoted = match[4]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Relinquish our claim on characters in `unquoted` from a closing parenthesis on if ( unquoted && (argument = rselector.exec( unquoted )) && argument.pop() ) { match[0] = match[0].slice( 0, argument[0].length - unquoted.length - 1 ); unquoted = argument[0].slice( 0, -1 ); } // Quoted or unquoted, we have the full argument // Return only captures needed by the pseudo filter method (type and argument) match.splice( 2, 3, unquoted || match[3] ); return match; } }, 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[ className ]; if ( !pattern ) { pattern = classCache[ className ] = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ); cachedClasses.push( className ); // Avoid too large of a cache if ( cachedClasses.length > Expr.cacheLength ) { delete classCache[ cachedClasses.shift() ]; } } return function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }; }, "ATTR": function( name, operator, check ) { if ( !operator ) { return function( elem ) { return Sizzle.attr( elem, name ) != null; }; } return function( elem ) { var result = Sizzle.attr( elem, name ), value = result + ""; if ( result == null ) { return operator === "!="; } switch ( operator ) { case "=": return value === check; case "!=": return value !== check; case "^=": return check && value.indexOf( check ) === 0; case "*=": return check && value.indexOf( check ) > -1; case "$=": return check && value.substr( value.length - check.length ) === check; case "~=": return ( " " + value + " " ).indexOf( check ) > -1; case "|=": return value === check || value.substr( 0, check.length + 1 ) === check + "-"; } }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { var doneName = done++; return function( elem ) { var parent, diff, count = 0, node = elem; if ( first === 1 && last === 0 ) { return true; } parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) { for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.sizset = ++count; if ( node === elem ) { break; } } } parent[ expando ] = doneName; } diff = elem.sizset - last; if ( first === 0 ) { return diff === 0; } else { return ( 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, context, xml ) { // 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 var fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ]; if ( !fn ) { Sizzle.error( "unsupported pseudo: " + pseudo ); } // The user may set fn.sizzleFilter to indicate // that arguments are needed to create the filter function // just as Sizzle does if ( !fn.sizzleFilter ) { return fn; } return fn( argument, context, xml ); } }, pseudos: { "not": markFunction(function( selector, context, xml ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var matcher = compile( selector.replace( rtrim, "$1" ), context, xml ); return function( elem ) { return !matcher( elem ); }; }), "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; }, "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "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": createInputFunction("radio"), "checkbox": createInputFunction("checkbox"), "file": createInputFunction("file"), "password": createInputFunction("password"), "image": createInputFunction("image"), "submit": createButtonFunction("submit"), "reset": createButtonFunction("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; } }, setFilters: { "first": function( elements, argument, not ) { return not ? elements.slice( 1 ) : [ elements[0] ]; }, "last": function( elements, argument, not ) { var elem = elements.pop(); return not ? elements : [ elem ]; }, "even": function( elements, argument, not ) { var results = [], i = not ? 1 : 0, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "odd": function( elements, argument, not ) { var results = [], i = not ? 0 : 1, len = elements.length; for ( ; i < len; i = i + 2 ) { results.push( elements[i] ); } return results; }, "lt": function( elements, argument, not ) { return not ? elements.slice( +argument ) : elements.slice( 0, +argument ); }, "gt": function( elements, argument, not ) { return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 ); }, "eq": function( elements, argument, not ) { var elem = elements.splice( +argument, 1 ); return not ? elements : elem; } } }; // Deprecated Expr.setFilters["nth"] = Expr.setFilters["eq"]; // Back-compat Expr.filters = Expr.pseudos; // IE6/7 return a modified href if ( !assertHrefNotNormalized ) { Expr.attrHandle = { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; } // Add getElementsByName if usable if ( assertUsableName ) { Expr.order.push("NAME"); Expr.find["NAME"] = function( name, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; } // Add getElementsByClassName if usable if ( assertUsableClassName ) { Expr.order.splice( 1, 0, "CLASS" ); Expr.find["CLASS"] = function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } }; } // 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; }; } var 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 var contains = Sizzle.contains = docElem.compareDocumentPosition ? function( a, b ) { return !!( a.compareDocumentPosition( b ) & 16 ); } : docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ var 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; }; Sizzle.attr = function( elem, name ) { var attr, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( Expr.attrHandle[ name ] ) { return Expr.attrHandle[ name ]( elem ); } if ( assertAttributes || xml ) { return elem.getAttribute( name ); } attr = elem.getAttributeNode( name ); return attr ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : attr.specified ? attr.value : null : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // 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() { return (baseHasDuplicate = 0); }); if ( docElem.compareDocumentPosition ) { sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : 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; }; } // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, i = 1; if ( sortOrder ) { hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } } return results; }; function multipleContexts( selector, contexts, results, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } } function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) { var results, fn = Expr.setFilters[ posfilter.toLowerCase() ]; if ( !fn ) { Sizzle.error( posfilter ); } if ( selector || !(results = seed) ) { multipleContexts( selector || "*", contexts, (results = []), seed ); } return results.length > 0 ? fn( results, argument, not ) : []; } function handlePOS( selector, context, results, seed, groups ) { var match, not, anchor, ret, elements, currentContexts, part, lastIndex, i = 0, len = groups.length, rpos = matchExpr["POS"], // This is generated here in case matchExpr["POS"] is extended rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ), // This is for making sure non-participating // matching groups are represented cross-browser (IE6-8) setUndefined = function() { var i = 1, len = arguments.length - 2; for ( ; i < len; i++ ) { if ( arguments[i] === undefined ) { match[i] = undefined; } } }; for ( ; i < len; i++ ) { // Reset regex index to 0 rpos.exec(""); selector = groups[i]; ret = []; anchor = 0; elements = seed; while ( (match = rpos.exec( selector )) ) { lastIndex = rpos.lastIndex = match.index + match[0].length; if ( lastIndex > anchor ) { part = selector.slice( anchor, match.index ); anchor = lastIndex; currentContexts = [ context ]; if ( rcombinators.test(part) ) { if ( elements ) { currentContexts = elements; } elements = seed; } if ( (not = rendsWithNot.test( part )) ) { part = part.slice( 0, -5 ).replace( rcombinators, "$&*" ); } if ( match.length > 1 ) { match[0].replace( rposgroups, setUndefined ); } elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not ); } } if ( elements ) { ret = ret.concat( elements ); if ( (part = selector.slice( anchor )) && part !== ")" ) { if ( rcombinators.test(part) ) { multipleContexts( part, ret, results, seed ); } else { Sizzle( part, context, results, seed ? seed.concat(elements) : elements ); } } else { push.apply( results, ret ); } } else { Sizzle( selector, context, results, seed ); } } // Do not sort if this is a single filter return len === 1 ? results : Sizzle.uniqueSort( results ); } function tokenize( selector, context, xml ) { var tokens, soFar, type, groups = [], i = 0, // Catch obvious selector issues: terminal ")"; nonempty fallback match // rselector never fails to match *something* match = rselector.exec( selector ), matched = !match.pop() && !match.pop(), selectorGroups = matched && selector.match( rgroups ) || [""], preFilters = Expr.preFilter, filters = Expr.filter, checkContext = !xml && context !== document; for ( ; (soFar = selectorGroups[i]) != null && matched; i++ ) { groups.push( tokens = [] ); // Need to make sure we're within a narrower context if necessary // Adding a descendant combinator will generate what is needed if ( checkContext ) { soFar = " " + soFar; } while ( soFar ) { matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { soFar = soFar.slice( match[0].length ); // Cast descendant combinators to space matched = tokens.push({ part: match.pop().replace( rtrim, " " ), captures: match }); } // Filters for ( type in filters ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match, context, xml )) ) ) { soFar = soFar.slice( match.shift().length ); matched = tokens.push({ part: type, captures: match }); } } if ( !matched ) { break; } } } if ( !matched ) { Sizzle.error( selector ); } return groups; } function addCombinator( matcher, combinator, context ) { var dir = combinator.dir, doneName = done++; if ( !matcher ) { // If there is no matcher to check, check against the context matcher = function( elem ) { return elem === context; }; } return combinator.first ? function( elem, context ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 ) { return matcher( elem, context ) && elem; } } } : function( elem, context ) { var cache, dirkey = doneName + "." + dirruns, cachedkey = dirkey + "." + cachedruns; while ( (elem = elem[ dir ]) ) { if ( 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 ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } }; } function addMatcher( higher, deeper ) { return higher ? function( elem, context ) { var result = deeper( elem, context ); return result && higher( result === true ? elem : result, context ); } : deeper; } // ["TAG", ">", "ID", " ", "CLASS"] function matcherFromTokens( tokens, context, xml ) { var token, matcher, i = 0; for ( ; (token = tokens[i]); i++ ) { if ( Expr.relative[ token.part ] ) { matcher = addCombinator( matcher, Expr.relative[ token.part ], context ); } else { token.captures.push( context, xml ); matcher = addMatcher( matcher, Expr.filter[ token.part ].apply( null, token.captures ) ); } } return matcher; } function matcherFromGroupMatchers( matchers ) { return function( elem, context ) { var matcher, j = 0; for ( ; (matcher = matchers[j]); j++ ) { if ( matcher(elem, context) ) { return true; } } return false; }; } var compile = Sizzle.compile = function( selector, context, xml ) { var tokens, group, i, cached = compilerCache[ selector ]; // Return a cached group function if already generated (context dependent) if ( cached && cached.context === context ) { return cached; } // Generate a function of recursive functions that can be used to check each element group = tokenize( selector, context, xml ); for ( i = 0; (tokens = group[i]); i++ ) { group[i] = matcherFromTokens( tokens, context, xml ); } // Cache the compiled function cached = compilerCache[ selector ] = matcherFromGroupMatchers( group ); cached.context = context; cached.runs = cached.dirruns = 0; cachedSelectors.push( selector ); // Ensure only the most recent are cached if ( cachedSelectors.length > Expr.cacheLength ) { delete compilerCache[ cachedSelectors.shift() ]; } return cached; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; var select = function( selector, context, results, seed, xml ) { // Remove excessive whitespace selector = selector.replace( rtrim, "$1" ); var elements, matcher, i, len, elem, token, type, findContext, notTokens, match = selector.match( rgroups ), tokens = selector.match( rtokens ), contextNodeType = context.nodeType; // POS handling if ( matchExpr["POS"].test(selector) ) { return handlePOS( selector, context, results, seed, match ); } if ( seed ) { elements = slice.call( seed, 0 ); // To maintain document order, only narrow the // set if there is one group } else if ( match && match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID if ( tokens.length > 1 && contextNodeType === 9 && !xml && (match = matchExpr["ID"].exec( tokens[0] )) ) { context = Expr.find["ID"]( match[1], context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } findContext = ( (match = rsibling.exec( tokens[0] )) && !match.index && context.parentNode ) || context; // Get the last token, excluding :not notTokens = tokens.pop(); token = notTokens.split(":not")[0]; for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = matchExpr[ type ].exec( token )) ) { elements = Expr.find[ type ]( (match[1] || "").replace( rbackslash, "" ), findContext, xml ); if ( elements == null ) { continue; } if ( token === notTokens ) { selector = selector.slice( 0, selector.length - notTokens.length ) + token.replace( matchExpr[ type ], "" ); if ( !selector ) { push.apply( results, slice.call(elements, 0) ); } } break; } } } // Only loop over the given elements once // If selector is empty, we're already done if ( selector ) { matcher = compile( selector, context, xml ); dirruns = matcher.dirruns++; if ( elements == null ) { elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context ); } for ( i = 0; (elem = elements[i]); i++ ) { cachedruns = matcher.runs++; if ( matcher(elem, context) ) { results.push( elem ); } } } return results; }; if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, rbuggyQSA = [], // 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 ) { 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 = 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 )) ) { if ( context.nodeType === 9 ) { try { push.apply( results, slice.call(context.querySelectorAll( selector ), 0) ); return results; } 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 old = context.getAttribute("id"), nid = old || expando, newContext = rsibling.test( selector ) && context.parentNode || context; if ( old ) { nid = nid.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } try { push.apply( results, slice.call( newContext.querySelectorAll( selector.replace( rgroups, "[id='" + nid + "'] $&" ) ), 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( Expr.match.PSEUDO ); } catch ( e ) {} }); // rbuggyMatches always contains :active, 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; }; } })(); } // 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 context = context || document; context = (context[0] || context).ownerDocument || context[0] || context; // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( typeof context.createDocumentFragment === "undefined" ) { context = 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 // 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 j, safe, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, i = 0, 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 ( safe = context === document && safeFragment; (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 = div || safe.appendChild( context.createElement("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; // Remember the top-level container for proper cleanup div = safe.lastChild; } } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { safe.removeChild( 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; } // Deprecated, use jQuery.browser.webkit instead // Maintained for back-compat only 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)$/, 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, lineHeight: 1 }, 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 used both window.getComputedStyle // and getComputedStyle here to produce a better gzip size if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = getComputedStyle( elem, null ), style = elem.style; if ( computed ) { ret = computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, 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"; if ( val <= 0 ) { // 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 ) { if ( elem.offsetWidth !== 0 || curCSS( elem, "display" ) !== "none" ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { 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 ajaxLocation, // Document location segments ajaxLocParts, 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 ( 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 ); // 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 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, prevScale, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1; 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 prevScale = scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zeroes from tween.cur() scale = tween.cur() / target; // Stop looping if we've hit the mark or scale is unchanged } while ( scale !== 1 && scale !== prevScale ); } 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 ]; this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); 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 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 box, docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, top, left, 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 we're not dealing with a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return { top: 0, left: 0 }; } 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; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; 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 ); }; }); }); // 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 );
packages/material-ui-icons/lib/esm/Slideshow.js
mbrookes/material-ui
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M10 8v8l5-4-5-4zm9-5H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z" }), 'Slideshow');
node_modules/react-native/Libraries/CustomComponents/Navigator/Navigator.js
nauman-ahmad-qureshi/adsManagement
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * Facebook, Inc. ("Facebook") owns all right, title and interest, including * all intellectual property and other proprietary rights, in and to the React * Native CustomComponents software (the "Software"). Subject to your * compliance with these terms, you are hereby granted a non-exclusive, * worldwide, royalty-free copyright license to (1) use and copy the Software; * and (2) reproduce and distribute the Software as part of your own software * ("Your Software"). Facebook reserves all rights not expressly granted to * you in this license agreement. * * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. * IN NO EVENT SHALL FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR * EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THE SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @providesModule Navigator */ /* eslint-disable no-extra-boolean-cast*/ 'use strict'; var AnimationsDebugModule = require('NativeModules').AnimationsDebugModule; var Dimensions = require('Dimensions'); var InteractionMixin = require('InteractionMixin'); var NavigationContext = require('NavigationContext'); var NavigatorBreadcrumbNavigationBar = require('NavigatorBreadcrumbNavigationBar'); var NavigatorNavigationBar = require('NavigatorNavigationBar'); var NavigatorSceneConfigs = require('NavigatorSceneConfigs'); var PanResponder = require('PanResponder'); var React = require('React'); var StyleSheet = require('StyleSheet'); var Subscribable = require('Subscribable'); var TVEventHandler = require('TVEventHandler'); var TimerMixin = require('react-timer-mixin'); var View = require('View'); var clamp = require('clamp'); var flattenStyle = require('flattenStyle'); var invariant = require('fbjs/lib/invariant'); var rebound = require('rebound'); var PropTypes = React.PropTypes; // TODO: this is not ideal because there is no guarantee that the navigator // is full screen, however we don't have a good way to measure the actual // size of the navigator right now, so this is the next best thing. var SCREEN_WIDTH = Dimensions.get('window').width; var SCREEN_HEIGHT = Dimensions.get('window').height; var SCENE_DISABLED_NATIVE_PROPS = { pointerEvents: 'none', style: { top: SCREEN_HEIGHT, bottom: -SCREEN_HEIGHT, opacity: 0, }, }; var __uid = 0; function getuid() { return __uid++; } function getRouteID(route) { if (route === null || typeof route !== 'object') { return String(route); } var key = '__navigatorRouteID'; if (!route.hasOwnProperty(key)) { Object.defineProperty(route, key, { enumerable: false, configurable: false, writable: false, value: getuid(), }); } return route[key]; } // styles moved to the top of the file so getDefaultProps can refer to it var styles = StyleSheet.create({ container: { flex: 1, overflow: 'hidden', }, defaultSceneStyle: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0, transform: [ {translateX: 0}, {translateY: 0}, {scaleX: 1}, {scaleY: 1}, {rotate: '0deg'}, {skewX: '0deg'}, {skewY: '0deg'}, ], }, baseScene: { position: 'absolute', overflow: 'hidden', left: 0, right: 0, bottom: 0, top: 0, }, disabledScene: { top: SCREEN_HEIGHT, bottom: -SCREEN_HEIGHT, }, transitioner: { flex: 1, backgroundColor: 'transparent', overflow: 'hidden', } }); var GESTURE_ACTIONS = [ 'pop', 'jumpBack', 'jumpForward', ]; /** * `Navigator` handles the transition between different scenes in your app. * It is implemented in JavaScript and is available on both iOS and Android. If * you are targeting iOS only, you may also want to consider using * [`NavigatorIOS`](docs/navigatorios.html) as it leverages native UIKit * navigation. * * To set up the `Navigator` you provide one or more objects called routes, * to identify each scene. You also provide a `renderScene` function that * renders the scene for each route object. * * ``` * import React, { Component } from 'react'; * import { Text, Navigator, TouchableHighlight } from 'react-native'; * * export default class NavAllDay extends Component { * render() { * return ( * <Navigator * initialRoute={{ title: 'Awesome Scene', index: 0 }} * renderScene={(route, navigator) => * <Text>Hello {route.title}!</Text> * } * style={{padding: 100}} * /> * ); * } * } * ``` * * In the above example, `initialRoute` is used to specify the first route. It * contains a `title` property that identifies the route. The `renderScene` * prop returns a function that displays text based on the route's title. * * ### Additional Scenes * * The first example demonstrated one scene. To set up multiple scenes, you pass * the `initialRouteStack` prop to `Navigator`: * * ``` * render() { * const routes = [ * {title: 'First Scene', index: 0}, * {title: 'Second Scene', index: 1}, * ]; * return ( * <Navigator * initialRoute={routes[0]} * initialRouteStack={routes} * renderScene={(route, navigator) => * <TouchableHighlight onPress={() => { * if (route.index === 0) { * navigator.push(routes[1]); * } else { * navigator.pop(); * } * }}> * <Text>Hello {route.title}!</Text> * </TouchableHighlight> * } * style={{padding: 100}} * /> * ); * } * ``` * * In the above example, a `routes` variable is defined with two route objects * representing two scenes. Each route has an `index` property that is used to * manage the scene being rendered. The `renderScene` method is changed to * either push or pop the navigator depending on the current route's index. * Finally, the `Text` component in the scene is now wrapped in a * `TouchableHighlight` component to help trigger the navigator transitions. * * ### Navigation Bar * * You can optionally pass in your own navigation bar by returning a * `Navigator.NavigationBar` component to the `navigationBar` prop in * `Navigator`. You can configure the navigation bar properties, through * the `routeMapper` prop. There you set up the left, right, and title * properties of the navigation bar: * * ``` * <Navigator * renderScene={(route, navigator) => * // ... * } * navigationBar={ * <Navigator.NavigationBar * routeMapper={{ * LeftButton: (route, navigator, index, navState) => * { return (<Text>Cancel</Text>); }, * RightButton: (route, navigator, index, navState) => * { return (<Text>Done</Text>); }, * Title: (route, navigator, index, navState) => * { return (<Text>Awesome Nav Bar</Text>); }, * }} * style={{backgroundColor: 'gray'}} * /> * } * /> * ``` * * When configuring the left, right, and title items for the navigation bar, * you have access to info such as the current route object and navigation * state. This allows you to customize the title for each scene as well as * the buttons. For example, you can choose to hide the left button for one of * the scenes. * * Typically you want buttons to represent the left and right buttons. Building * on the previous example, you can set this up as follows: * * ``` * LeftButton: (route, navigator, index, navState) => * { * if (route.index === 0) { * return null; * } else { * return ( * <TouchableHighlight onPress={() => navigator.pop()}> * <Text>Back</Text> * </TouchableHighlight> * ); * } * }, * ``` * * This sets up a left navigator bar button that's visible on scenes after the * the first one. When the button is tapped the navigator is popped. * * Another type of navigation bar, with breadcrumbs, is provided by * `Navigator.BreadcrumbNavigationBar`. You can also provide your own navigation * bar by passing it through the `navigationBar` prop. See the * [UIExplorer](https://github.com/facebook/react-native/tree/master/Examples/UIExplorer) * demo to try out both built-in navigation bars out and see how to use them. * * ### Scene Transitions * * To change the animation or gesture properties of the scene, provide a * `configureScene` prop to get the config object for a given route: * * ``` * <Navigator * renderScene={(route, navigator) => * // ... * } * configureScene={(route, routeStack) => * Navigator.SceneConfigs.FloatFromBottom} * /> * ``` * In the above example, the newly pushed scene will float up from the bottom. * See `Navigator.SceneConfigs` for default animations and more info on * available [scene config options](docs/navigator.html#configurescene). */ var Navigator = React.createClass({ propTypes: { /** * Optional function where you can configure scene animations and * gestures. Will be invoked with `route` and `routeStack` parameters, * where `route` corresponds to the current scene being rendered by the * `Navigator` and `routeStack` is the set of currently mounted routes * that the navigator could transition to. * * The function should return a scene configuration object. * * ``` * (route, routeStack) => Navigator.SceneConfigs.FloatFromRight * ``` * * Available scene configuration options are: * * - Navigator.SceneConfigs.PushFromRight (default) * - Navigator.SceneConfigs.FloatFromRight * - Navigator.SceneConfigs.FloatFromLeft * - Navigator.SceneConfigs.FloatFromBottom * - Navigator.SceneConfigs.FloatFromBottomAndroid * - Navigator.SceneConfigs.FadeAndroid * - Navigator.SceneConfigs.SwipeFromLeft * - Navigator.SceneConfigs.HorizontalSwipeJump * - Navigator.SceneConfigs.HorizontalSwipeJumpFromRight * - Navigator.SceneConfigs.HorizontalSwipeJumpFromLeft * - Navigator.SceneConfigs.VerticalUpSwipeJump * - Navigator.SceneConfigs.VerticalDownSwipeJump * */ configureScene: PropTypes.func, /** * Required function which renders the scene for a given route. Will be * invoked with the `route` and the `navigator` object. * * ``` * (route, navigator) => * <MySceneComponent title={route.title} navigator={navigator} /> * ``` */ renderScene: PropTypes.func.isRequired, /** * The initial route for navigation. A route is an object that the navigator * will use to identify each scene it renders. * * If both `initialRoute` and `initialRouteStack` props are passed to * `Navigator`, then `initialRoute` must be in a route in * `initialRouteStack`. If `initialRouteStack` is passed as a prop but * `initialRoute` is not, then `initialRoute` will default internally to * the last item in `initialRouteStack`. */ initialRoute: PropTypes.object, /** * Pass this in to provide a set of routes to initially mount. This prop * is required if `initialRoute` is not provided to the navigator. If this * prop is not passed in, it will default internally to an array * containing only `initialRoute`. */ initialRouteStack: PropTypes.arrayOf(PropTypes.object), /** * Pass in a function to get notified with the target route when * the navigator component is mounted and before each navigator transition. */ onWillFocus: PropTypes.func, /** * Will be called with the new route of each scene after the transition is * complete or after the initial mounting. */ onDidFocus: PropTypes.func, /** * Use this to provide an optional component representing a navigation bar * that is persisted across scene transitions. This component will receive * two props: `navigator` and `navState` representing the navigator * component and its state. The component is re-rendered when the route * changes. */ navigationBar: PropTypes.node, /** * Optionally pass in the navigator object from a parent `Navigator`. */ navigator: PropTypes.object, /** * Styles to apply to the container of each scene. */ sceneStyle: View.propTypes.style, }, statics: { BreadcrumbNavigationBar: NavigatorBreadcrumbNavigationBar, NavigationBar: NavigatorNavigationBar, SceneConfigs: NavigatorSceneConfigs, }, mixins: [TimerMixin, InteractionMixin, Subscribable.Mixin], getDefaultProps: function() { return { configureScene: () => NavigatorSceneConfigs.PushFromRight, sceneStyle: styles.defaultSceneStyle, }; }, getInitialState: function() { this._navigationBarNavigator = this.props.navigationBarNavigator || this; this._renderedSceneMap = new Map(); this._sceneRefs = []; var routeStack = this.props.initialRouteStack || [this.props.initialRoute]; invariant( routeStack.length >= 1, 'Navigator requires props.initialRoute or props.initialRouteStack.' ); var initialRouteIndex = routeStack.length - 1; if (this.props.initialRoute) { initialRouteIndex = routeStack.indexOf(this.props.initialRoute); invariant( initialRouteIndex !== -1, 'initialRoute is not in initialRouteStack.' ); } return { sceneConfigStack: routeStack.map( (route) => this.props.configureScene(route, routeStack) ), routeStack, presentedIndex: initialRouteIndex, transitionFromIndex: null, activeGesture: null, pendingGestureProgress: null, transitionQueue: [], }; }, componentWillMount: function() { // TODO(t7489503): Don't need this once ES6 Class landed. this.__defineGetter__('navigationContext', this._getNavigationContext); this._subRouteFocus = []; this.parentNavigator = this.props.navigator; this._handlers = {}; this.springSystem = new rebound.SpringSystem(); this.spring = this.springSystem.createSpring(); this.spring.setRestSpeedThreshold(0.05); this.spring.setCurrentValue(0).setAtRest(); this.spring.addListener({ onSpringEndStateChange: () => { if (!this._interactionHandle) { this._interactionHandle = this.createInteractionHandle(); } }, onSpringUpdate: () => { this._handleSpringUpdate(); }, onSpringAtRest: () => { this._completeTransition(); }, }); this.panGesture = PanResponder.create({ onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder, onPanResponderRelease: this._handlePanResponderRelease, onPanResponderMove: this._handlePanResponderMove, onPanResponderTerminate: this._handlePanResponderTerminate, }); this._interactionHandle = null; this._emitWillFocus(this.state.routeStack[this.state.presentedIndex]); }, componentDidMount: function() { this._handleSpringUpdate(); this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]); this._enableTVEventHandler(); }, componentWillUnmount: function() { if (this._navigationContext) { this._navigationContext.dispose(); this._navigationContext = null; } this.spring.destroy(); if (this._interactionHandle) { this.clearInteractionHandle(this._interactionHandle); } this._disableTVEventHandler(); }, /** * Reset every scene with an array of routes. * * @param {RouteStack} nextRouteStack Next route stack to reinitialize. * All existing route stacks are destroyed and potentially recreated. There * is no accompanying animation and this method immediately replaces and * re-renders the navigation bar and the stack items. */ immediatelyResetRouteStack: function(nextRouteStack) { var destIndex = nextRouteStack.length - 1; this._emitWillFocus(nextRouteStack[destIndex]); this.setState({ routeStack: nextRouteStack, sceneConfigStack: nextRouteStack.map( route => this.props.configureScene(route, nextRouteStack) ), presentedIndex: destIndex, activeGesture: null, transitionFromIndex: null, transitionQueue: [], }, () => { this._handleSpringUpdate(); var navBar = this._navBar; if (navBar && navBar.immediatelyRefresh) { navBar.immediatelyRefresh(); } this._emitDidFocus(this.state.routeStack[this.state.presentedIndex]); }); }, _transitionTo: function(destIndex, velocity, jumpSpringTo, cb) { if (this.state.presentedIndex === destIndex) { cb && cb(); return; } if (this.state.transitionFromIndex !== null) { // Navigation is still transitioning, put the `destIndex` into queue. this.state.transitionQueue.push({ destIndex, velocity, cb, }); return; } this.state.transitionFromIndex = this.state.presentedIndex; this.state.presentedIndex = destIndex; this.state.transitionCb = cb; this._onAnimationStart(); if (AnimationsDebugModule) { AnimationsDebugModule.startRecordingFps(); } var sceneConfig = this.state.sceneConfigStack[this.state.transitionFromIndex] || this.state.sceneConfigStack[this.state.presentedIndex]; invariant( sceneConfig, 'Cannot configure scene at index ' + this.state.transitionFromIndex ); if (jumpSpringTo != null) { this.spring.setCurrentValue(jumpSpringTo); } this.spring.setOvershootClampingEnabled(true); this.spring.getSpringConfig().friction = sceneConfig.springFriction; this.spring.getSpringConfig().tension = sceneConfig.springTension; this.spring.setVelocity(velocity || sceneConfig.defaultTransitionVelocity); this.spring.setEndValue(1); }, /** * This happens for each frame of either a gesture or a transition. If both are * happening, we only set values for the transition and the gesture will catch up later */ _handleSpringUpdate: function() { if (!this.isMounted()) { return; } // Prioritize handling transition in progress over a gesture: if (this.state.transitionFromIndex != null) { this._transitionBetween( this.state.transitionFromIndex, this.state.presentedIndex, this.spring.getCurrentValue() ); } else if (this.state.activeGesture != null) { var presentedToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._transitionBetween( this.state.presentedIndex, presentedToIndex, this.spring.getCurrentValue() ); } }, /** * This happens at the end of a transition started by transitionTo, and when the spring catches up to a pending gesture */ _completeTransition: function() { if (!this.isMounted()) { return; } if (this.spring.getCurrentValue() !== 1 && this.spring.getCurrentValue() !== 0) { // The spring has finished catching up to a gesture in progress. Remove the pending progress // and we will be in a normal activeGesture state if (this.state.pendingGestureProgress) { this.state.pendingGestureProgress = null; } return; } this._onAnimationEnd(); var presentedIndex = this.state.presentedIndex; var didFocusRoute = this._subRouteFocus[presentedIndex] || this.state.routeStack[presentedIndex]; if (AnimationsDebugModule) { AnimationsDebugModule.stopRecordingFps(Date.now()); } this.state.transitionFromIndex = null; this.spring.setCurrentValue(0).setAtRest(); this._hideScenes(); if (this.state.transitionCb) { this.state.transitionCb(); this.state.transitionCb = null; } this._emitDidFocus(didFocusRoute); if (this._interactionHandle) { this.clearInteractionHandle(this._interactionHandle); this._interactionHandle = null; } if (this.state.pendingGestureProgress) { // A transition completed, but there is already another gesture happening. // Enable the scene and set the spring to catch up with the new gesture var gestureToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._enableScene(gestureToIndex); this.spring.setEndValue(this.state.pendingGestureProgress); return; } if (this.state.transitionQueue.length) { var queuedTransition = this.state.transitionQueue.shift(); this._enableScene(queuedTransition.destIndex); this._emitWillFocus(this.state.routeStack[queuedTransition.destIndex]); this._transitionTo( queuedTransition.destIndex, queuedTransition.velocity, null, queuedTransition.cb ); } }, _emitDidFocus: function(route) { this.navigationContext.emit('didfocus', {route: route}); if (this.props.onDidFocus) { this.props.onDidFocus(route); } }, _emitWillFocus: function(route) { this.navigationContext.emit('willfocus', {route: route}); var navBar = this._navBar; if (navBar && navBar.handleWillFocus) { navBar.handleWillFocus(route); } if (this.props.onWillFocus) { this.props.onWillFocus(route); } }, /** * Hides all scenes that we are not currently on, gesturing to, or transitioning from */ _hideScenes: function() { var gesturingToIndex = null; if (this.state.activeGesture) { gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); } for (var i = 0; i < this.state.routeStack.length; i++) { if (i === this.state.presentedIndex || i === this.state.transitionFromIndex || i === gesturingToIndex) { continue; } this._disableScene(i); } }, /** * Push a scene off the screen, so that opacity:0 scenes will not block touches sent to the presented scenes */ _disableScene: function(sceneIndex) { this._sceneRefs[sceneIndex] && this._sceneRefs[sceneIndex].setNativeProps(SCENE_DISABLED_NATIVE_PROPS); }, /** * Put the scene back into the state as defined by props.sceneStyle, so transitions can happen normally */ _enableScene: function(sceneIndex) { // First, determine what the defined styles are for scenes in this navigator var sceneStyle = flattenStyle([styles.baseScene, this.props.sceneStyle]); // Then restore the pointer events and top value for this scene var enabledSceneNativeProps = { pointerEvents: 'auto', style: { top: sceneStyle.top, bottom: sceneStyle.bottom, }, }; if (sceneIndex !== this.state.transitionFromIndex && sceneIndex !== this.state.presentedIndex) { // If we are not in a transition from this index, make sure opacity is 0 // to prevent the enabled scene from flashing over the presented scene enabledSceneNativeProps.style.opacity = 0; } this._sceneRefs[sceneIndex] && this._sceneRefs[sceneIndex].setNativeProps(enabledSceneNativeProps); }, _clearTransformations: function(sceneIndex) { const defaultStyle = flattenStyle([styles.defaultSceneStyle]); this._sceneRefs[sceneIndex].setNativeProps({ style: defaultStyle }); }, _onAnimationStart: function() { var fromIndex = this.state.presentedIndex; var toIndex = this.state.presentedIndex; if (this.state.transitionFromIndex != null) { fromIndex = this.state.transitionFromIndex; } else if (this.state.activeGesture) { toIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); } this._setRenderSceneToHardwareTextureAndroid(fromIndex, true); this._setRenderSceneToHardwareTextureAndroid(toIndex, true); var navBar = this._navBar; if (navBar && navBar.onAnimationStart) { navBar.onAnimationStart(fromIndex, toIndex); } }, _onAnimationEnd: function() { var max = this.state.routeStack.length - 1; for (var index = 0; index <= max; index++) { this._setRenderSceneToHardwareTextureAndroid(index, false); } var navBar = this._navBar; if (navBar && navBar.onAnimationEnd) { navBar.onAnimationEnd(); } }, _setRenderSceneToHardwareTextureAndroid: function(sceneIndex, shouldRenderToHardwareTexture) { var viewAtIndex = this._sceneRefs[sceneIndex]; if (viewAtIndex === null || viewAtIndex === undefined) { return; } viewAtIndex.setNativeProps({renderToHardwareTextureAndroid: shouldRenderToHardwareTexture}); }, _handleTouchStart: function() { this._eligibleGestures = GESTURE_ACTIONS; }, _handleMoveShouldSetPanResponder: function(e, gestureState) { var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex]; if (!sceneConfig) { return false; } this._expectingGestureGrant = this._matchGestureAction(this._eligibleGestures, sceneConfig.gestures, gestureState); return !!this._expectingGestureGrant; }, _doesGestureOverswipe: function(gestureName) { var wouldOverswipeBack = this.state.presentedIndex <= 0 && (gestureName === 'pop' || gestureName === 'jumpBack'); var wouldOverswipeForward = this.state.presentedIndex >= this.state.routeStack.length - 1 && gestureName === 'jumpForward'; return wouldOverswipeForward || wouldOverswipeBack; }, _deltaForGestureAction: function(gestureAction) { switch (gestureAction) { case 'pop': case 'jumpBack': return -1; case 'jumpForward': return 1; default: invariant(false, 'Unsupported gesture action ' + gestureAction); return; } }, _handlePanResponderRelease: function(e, gestureState) { var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex]; var releaseGestureAction = this.state.activeGesture; if (!releaseGestureAction) { // The gesture may have been detached while responder, so there is no action here return; } var releaseGesture = sceneConfig.gestures[releaseGestureAction]; var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); if (this.spring.getCurrentValue() === 0) { // The spring is at zero, so the gesture is already complete this.spring.setCurrentValue(0).setAtRest(); this._completeTransition(); return; } var isTravelVertical = releaseGesture.direction === 'top-to-bottom' || releaseGesture.direction === 'bottom-to-top'; var isTravelInverted = releaseGesture.direction === 'right-to-left' || releaseGesture.direction === 'bottom-to-top'; var velocity, gestureDistance; if (isTravelVertical) { velocity = isTravelInverted ? -gestureState.vy : gestureState.vy; gestureDistance = isTravelInverted ? -gestureState.dy : gestureState.dy; } else { velocity = isTravelInverted ? -gestureState.vx : gestureState.vx; gestureDistance = isTravelInverted ? -gestureState.dx : gestureState.dx; } var transitionVelocity = clamp(-10, velocity, 10); if (Math.abs(velocity) < releaseGesture.notMoving) { // The gesture velocity is so slow, is "not moving" var hasGesturedEnoughToComplete = gestureDistance > releaseGesture.fullDistance * releaseGesture.stillCompletionRatio; transitionVelocity = hasGesturedEnoughToComplete ? releaseGesture.snapVelocity : -releaseGesture.snapVelocity; } if (transitionVelocity < 0 || this._doesGestureOverswipe(releaseGestureAction)) { // This gesture is to an overswiped region or does not have enough velocity to complete // If we are currently mid-transition, then this gesture was a pending gesture. Because this gesture takes no action, we can stop here if (this.state.transitionFromIndex == null) { // There is no current transition, so we need to transition back to the presented index var transitionBackToPresentedIndex = this.state.presentedIndex; // slight hack: change the presented index for a moment in order to transitionTo correctly this.state.presentedIndex = destIndex; this._transitionTo( transitionBackToPresentedIndex, -transitionVelocity, 1 - this.spring.getCurrentValue() ); } } else { // The gesture has enough velocity to complete, so we transition to the gesture's destination this._emitWillFocus(this.state.routeStack[destIndex]); this._transitionTo( destIndex, transitionVelocity, null, () => { if (releaseGestureAction === 'pop') { this._cleanScenesPastIndex(destIndex); } } ); } this._detachGesture(); }, _handlePanResponderTerminate: function(e, gestureState) { if (this.state.activeGesture == null) { return; } var destIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._detachGesture(); var transitionBackToPresentedIndex = this.state.presentedIndex; // slight hack: change the presented index for a moment in order to transitionTo correctly this.state.presentedIndex = destIndex; this._transitionTo( transitionBackToPresentedIndex, null, 1 - this.spring.getCurrentValue() ); }, _attachGesture: function(gestureId) { this.state.activeGesture = gestureId; var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._enableScene(gesturingToIndex); }, _detachGesture: function() { this.state.activeGesture = null; this.state.pendingGestureProgress = null; this._hideScenes(); }, _handlePanResponderMove: function(e, gestureState) { if (this._isMoveGestureAttached !== undefined) { invariant( this._expectingGestureGrant, 'Responder granted unexpectedly.' ); this._attachGesture(this._expectingGestureGrant); this._onAnimationStart(); this._expectingGestureGrant = undefined; } var sceneConfig = this.state.sceneConfigStack[this.state.presentedIndex]; if (this.state.activeGesture) { var gesture = sceneConfig.gestures[this.state.activeGesture]; return this._moveAttachedGesture(gesture, gestureState); } var matchedGesture = this._matchGestureAction(GESTURE_ACTIONS, sceneConfig.gestures, gestureState); if (matchedGesture) { this._attachGesture(matchedGesture); } }, _moveAttachedGesture: function(gesture, gestureState) { var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top'; var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top'; var distance = isTravelVertical ? gestureState.dy : gestureState.dx; distance = isTravelInverted ? -distance : distance; var gestureDetectMovement = gesture.gestureDetectMovement; var nextProgress = (distance - gestureDetectMovement) / (gesture.fullDistance - gestureDetectMovement); if (nextProgress < 0 && gesture.isDetachable) { var gesturingToIndex = this.state.presentedIndex + this._deltaForGestureAction(this.state.activeGesture); this._transitionBetween(this.state.presentedIndex, gesturingToIndex, 0); this._detachGesture(); if (this.state.pendingGestureProgress != null) { this.spring.setCurrentValue(0); } return; } if (gesture.overswipe && this._doesGestureOverswipe(this.state.activeGesture)) { var frictionConstant = gesture.overswipe.frictionConstant; var frictionByDistance = gesture.overswipe.frictionByDistance; var frictionRatio = 1 / ((frictionConstant) + (Math.abs(nextProgress) * frictionByDistance)); nextProgress *= frictionRatio; } nextProgress = clamp(0, nextProgress, 1); if (this.state.transitionFromIndex != null) { this.state.pendingGestureProgress = nextProgress; } else if (this.state.pendingGestureProgress) { this.spring.setEndValue(nextProgress); } else { this.spring.setCurrentValue(nextProgress); } }, _matchGestureAction: function(eligibleGestures, gestures, gestureState) { if (!gestures || !eligibleGestures || !eligibleGestures.some) { return null; } var matchedGesture = null; eligibleGestures.some((gestureName, gestureIndex) => { var gesture = gestures[gestureName]; if (!gesture) { return; } if (gesture.overswipe == null && this._doesGestureOverswipe(gestureName)) { // cannot swipe past first or last scene without overswiping return false; } var isTravelVertical = gesture.direction === 'top-to-bottom' || gesture.direction === 'bottom-to-top'; var isTravelInverted = gesture.direction === 'right-to-left' || gesture.direction === 'bottom-to-top'; var startedLoc = isTravelVertical ? gestureState.y0 : gestureState.x0; var currentLoc = isTravelVertical ? gestureState.moveY : gestureState.moveX; var travelDist = isTravelVertical ? gestureState.dy : gestureState.dx; var oppositeAxisTravelDist = isTravelVertical ? gestureState.dx : gestureState.dy; var edgeHitWidth = gesture.edgeHitWidth; if (isTravelInverted) { startedLoc = -startedLoc; currentLoc = -currentLoc; travelDist = -travelDist; oppositeAxisTravelDist = -oppositeAxisTravelDist; edgeHitWidth = isTravelVertical ? -(SCREEN_HEIGHT - edgeHitWidth) : -(SCREEN_WIDTH - edgeHitWidth); } if (startedLoc === 0) { startedLoc = currentLoc; } var moveStartedInRegion = gesture.edgeHitWidth == null || startedLoc < edgeHitWidth; if (!moveStartedInRegion) { return false; } var moveTravelledFarEnough = travelDist >= gesture.gestureDetectMovement; if (!moveTravelledFarEnough) { return false; } var directionIsCorrect = Math.abs(travelDist) > Math.abs(oppositeAxisTravelDist) * gesture.directionRatio; if (directionIsCorrect) { matchedGesture = gestureName; return true; } else { this._eligibleGestures = this._eligibleGestures.slice().splice(gestureIndex, 1); } }); return matchedGesture || null; }, _transitionSceneStyle: function(fromIndex, toIndex, progress, index) { var viewAtIndex = this._sceneRefs[index]; if (viewAtIndex === null || viewAtIndex === undefined) { return; } // Use toIndex animation when we move forwards. Use fromIndex when we move back var sceneConfigIndex = fromIndex < toIndex ? toIndex : fromIndex; var sceneConfig = this.state.sceneConfigStack[sceneConfigIndex]; // this happens for overswiping when there is no scene at toIndex if (!sceneConfig) { sceneConfig = this.state.sceneConfigStack[sceneConfigIndex - 1]; } var styleToUse = {}; var useFn = index < fromIndex || index < toIndex ? sceneConfig.animationInterpolators.out : sceneConfig.animationInterpolators.into; var directionAdjustedProgress = fromIndex < toIndex ? progress : 1 - progress; var didChange = useFn(styleToUse, directionAdjustedProgress); if (didChange) { viewAtIndex.setNativeProps({style: styleToUse}); } }, _transitionBetween: function(fromIndex, toIndex, progress) { this._transitionSceneStyle(fromIndex, toIndex, progress, fromIndex); this._transitionSceneStyle(fromIndex, toIndex, progress, toIndex); var navBar = this._navBar; if (navBar && navBar.updateProgress && toIndex >= 0 && fromIndex >= 0) { navBar.updateProgress(progress, fromIndex, toIndex); } }, _handleResponderTerminationRequest: function() { return false; }, _getDestIndexWithinBounds: function(n) { var currentIndex = this.state.presentedIndex; var destIndex = currentIndex + n; invariant( destIndex >= 0, 'Cannot jump before the first route.' ); var maxIndex = this.state.routeStack.length - 1; invariant( maxIndex >= destIndex, 'Cannot jump past the last route.' ); return destIndex; }, _jumpN: function(n) { var destIndex = this._getDestIndexWithinBounds(n); this._enableScene(destIndex); this._emitWillFocus(this.state.routeStack[destIndex]); this._transitionTo(destIndex); }, /** * Transition to an existing scene without unmounting. * @param {object} route Route to transition to. The specified route must * be in the currently mounted set of routes defined in `routeStack`. */ jumpTo: function(route) { var destIndex = this.state.routeStack.indexOf(route); invariant( destIndex !== -1, 'Cannot jump to route that is not in the route stack' ); this._jumpN(destIndex - this.state.presentedIndex); }, /** * Jump forward to the next scene in the route stack. */ jumpForward: function() { this._jumpN(1); }, /** * Jump backward without unmounting the current scene. */ jumpBack: function() { this._jumpN(-1); }, /** * Navigate forward to a new scene, squashing any scenes that you could * jump forward to. * @param {object} route Route to push into the navigator stack. */ push: function(route) { invariant(!!route, 'Must supply route to push'); var activeLength = this.state.presentedIndex + 1; var activeStack = this.state.routeStack.slice(0, activeLength); var activeAnimationConfigStack = this.state.sceneConfigStack.slice(0, activeLength); var nextStack = activeStack.concat([route]); var destIndex = nextStack.length - 1; var nextSceneConfig = this.props.configureScene(route, nextStack); var nextAnimationConfigStack = activeAnimationConfigStack.concat([nextSceneConfig]); this._emitWillFocus(nextStack[destIndex]); this.setState({ routeStack: nextStack, sceneConfigStack: nextAnimationConfigStack, }, () => { this._enableScene(destIndex); this._transitionTo(destIndex, nextSceneConfig.defaultTransitionVelocity); }); }, /** * Go back N scenes at once. When N=1, behavior matches `pop()`. * When N is invalid(negative or bigger than current routes count), do nothing. * @param {number} n The number of scenes to pop. Should be an integer. */ popN: function(n) { invariant(typeof n === 'number', 'Must supply a number to popN'); n = parseInt(n, 10); if (n <= 0 || this.state.presentedIndex - n < 0) { return; } var popIndex = this.state.presentedIndex - n; var presentedRoute = this.state.routeStack[this.state.presentedIndex]; var popSceneConfig = this.props.configureScene(presentedRoute); // using the scene config of the currently presented view this._enableScene(popIndex); // This is needed because scene at the pop index may be transformed // with a configuration different from the configuration on the presented // route. this._clearTransformations(popIndex); this._emitWillFocus(this.state.routeStack[popIndex]); this._transitionTo( popIndex, popSceneConfig.defaultTransitionVelocity, null, // no spring jumping () => { this._cleanScenesPastIndex(popIndex); } ); }, /** * Transition back and unmount the current scene. */ pop: function() { if (this.state.transitionQueue.length) { // This is the workaround to prevent user from firing multiple `pop()` // calls that may pop the routes beyond the limit. // Because `this.state.presentedIndex` does not update until the // transition starts, we can't reliably use `this.state.presentedIndex` // to know whether we can safely keep popping the routes or not at this // moment. return; } this.popN(1); }, /** * Replace a scene as specified by an index. * @param {object} route Route representing the new scene to render. * @param {number} index The route in the stack that should be replaced. * If negative, it counts from the back of the stack. * @param {Function} cb Callback function when the scene has been replaced. */ replaceAtIndex: function(route, index, cb) { invariant(!!route, 'Must supply route to replace'); if (index < 0) { index += this.state.routeStack.length; } if (this.state.routeStack.length <= index) { return; } var nextRouteStack = this.state.routeStack.slice(); var nextAnimationModeStack = this.state.sceneConfigStack.slice(); nextRouteStack[index] = route; nextAnimationModeStack[index] = this.props.configureScene(route, nextRouteStack); if (index === this.state.presentedIndex) { this._emitWillFocus(route); } this.setState({ routeStack: nextRouteStack, sceneConfigStack: nextAnimationModeStack, }, () => { if (index === this.state.presentedIndex) { this._emitDidFocus(route); } cb && cb(); }); }, /** * Replace the current scene with a new route. * @param {object} route Route that replaces the current scene. */ replace: function(route) { this.replaceAtIndex(route, this.state.presentedIndex); }, /** * Replace the previous scene. * @param {object} route Route that replaces the previous scene. */ replacePrevious: function(route) { this.replaceAtIndex(route, this.state.presentedIndex - 1); }, /** * Pop to the first scene in the stack, unmounting every other scene. */ popToTop: function() { this.popToRoute(this.state.routeStack[0]); }, /** * Pop to a particular scene, as specified by its route. * All scenes after it will be unmounted. * @param {object} route Route to pop to. */ popToRoute: function(route) { var indexOfRoute = this.state.routeStack.indexOf(route); invariant( indexOfRoute !== -1, 'Calling popToRoute for a route that doesn\'t exist!' ); var numToPop = this.state.presentedIndex - indexOfRoute; this.popN(numToPop); }, /** * Replace the previous scene and pop to it. * @param {object} route Route that replaces the previous scene. */ replacePreviousAndPop: function(route) { if (this.state.routeStack.length < 2) { return; } this.replacePrevious(route); this.pop(); }, /** * Navigate to a new scene and reset route stack. * @param {object} route Route to navigate to. */ resetTo: function(route) { invariant(!!route, 'Must supply route to push'); this.replaceAtIndex(route, 0, () => { // Do not use popToRoute here, because race conditions could prevent the // route from existing at this time. Instead, just go to index 0 this.popN(this.state.presentedIndex); }); }, /** * Returns the current list of routes. */ getCurrentRoutes: function() { // Clone before returning to avoid caller mutating the stack return this.state.routeStack.slice(); }, _cleanScenesPastIndex: function(index) { var newStackLength = index + 1; // Remove any unneeded rendered routes. if (newStackLength < this.state.routeStack.length) { this.setState({ sceneConfigStack: this.state.sceneConfigStack.slice(0, newStackLength), routeStack: this.state.routeStack.slice(0, newStackLength), }); } }, _renderScene: function(route, i) { var disabledSceneStyle = null; var disabledScenePointerEvents = 'auto'; if (i !== this.state.presentedIndex) { disabledSceneStyle = styles.disabledScene; disabledScenePointerEvents = 'none'; } return ( <View collapsable={false} key={'scene_' + getRouteID(route)} ref={(scene) => { this._sceneRefs[i] = scene; }} onStartShouldSetResponderCapture={() => { return (this.state.transitionFromIndex != null); }} pointerEvents={disabledScenePointerEvents} style={[styles.baseScene, this.props.sceneStyle, disabledSceneStyle]}> {this.props.renderScene( route, this )} </View> ); }, _renderNavigationBar: function() { const { navigationBar } = this.props; if (!navigationBar) { return null; } return React.cloneElement(navigationBar, { ref: (navBar) => { this._navBar = navBar; if (navigationBar && typeof navigationBar.ref === 'function') { navigationBar.ref(navBar); } }, navigator: this._navigationBarNavigator, navState: this.state, }); }, _tvEventHandler: TVEventHandler, _enableTVEventHandler: function() { this._tvEventHandler = new TVEventHandler(); this._tvEventHandler.enable(this, function(cmp, evt) { if (evt && evt.eventType === 'menu') { cmp.pop(); } }); }, _disableTVEventHandler: function() { if (this._tvEventHandler) { this._tvEventHandler.disable(); delete this._tvEventHandler; } }, render: function() { var newRenderedSceneMap = new Map(); var scenes = this.state.routeStack.map((route, index) => { var renderedScene; if (this._renderedSceneMap.has(route) && index !== this.state.presentedIndex) { renderedScene = this._renderedSceneMap.get(route); } else { renderedScene = this._renderScene(route, index); } newRenderedSceneMap.set(route, renderedScene); return renderedScene; }); this._renderedSceneMap = newRenderedSceneMap; return ( <View style={[styles.container, this.props.style]}> <View style={styles.transitioner} {...this.panGesture.panHandlers} onTouchStart={this._handleTouchStart} onResponderTerminationRequest={ this._handleResponderTerminationRequest }> {scenes} </View> {this._renderNavigationBar()} </View> ); }, _getNavigationContext: function() { if (!this._navigationContext) { this._navigationContext = new NavigationContext(); } return this._navigationContext; } }); module.exports = Navigator;
demo/index.js
CezaryDanielNowak/React-dotdotdot
import React from 'react'; import ReactDOM from 'react-dom'; import Dotdotdot from 'react-dotdotdot' class App extends React.Component { render() { return ( <div> <div> This page is clamped version of: <a href="https://codepen.io/carolynmcneillie/pen/Lewxrm" target="_blank">Codepen</a> <br /> Thanks to Carolyn McNeillie </div> <hr /> <p className="intro"> What CSS property do you use to set the colour of a text block? If you said <em>color</em> you were&nbsp;… wrong! </p> <p className="intro"> Don’t take it too hard, though. It was a trick question. In typographic parlance, “color” refers to the visual density of a block of text. Here's a little sandbox where you can play with some of the properties that impact typographic color. </p> <h1>Font Weight</h1> <div className="wrapper"> <div className="font-weight small"> <h2>Light / clamp=3 useNativeClamp=false</h2> <Dotdotdot clamp={ 3 } useNativeClamp={ false } > <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="font-weight medium"> <h2>Normal / clamp=7 useNativeClamp=true</h2> <Dotdotdot clamp={ 7 } useNativeClamp={ true }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="font-weight large"> <h2>Heavy / clamp=7</h2> <Dotdotdot clamp={ 7 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> </div> <h1>Tracking</h1> <div className="wrapper"> <div className="letter-spacing small"> <h2>Tight / clamp=5 useNativeClamp=false truncationChar="&raquo;"</h2> <Dotdotdot clamp={ 5 } useNativeClamp={ false } truncationChar="&raquo;"> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="letter-spacing medium"> <h2>Normal / clamp=5 useNativeClamp=false truncationHTML="&lt;br />&lt;marquee>…&lt;/marquee>" truncationChar=""</h2> <Dotdotdot clamp={ 5 } useNativeClamp={ false } truncationHTML="<br /><marquee>…</marquee>" truncationChar=""> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="letter-spacing large"> <h2>Wide / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> </div> <h1>Word Spacing / clamp=3</h1> <div className="wrapper"> <div className="word-spacing small"> <h2>Tight</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="word-spacing medium"> <h2>Normal / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="word-spacing large"> <h2>Wide / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> </div> <h1>Ledding</h1> <div className="wrapper"> <div className="line-height small"> <h2>Tight / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="line-height medium"> <h2>Normal / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="line-height large"> <h2>Double / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> </div> <h1>Justification / clamp=3</h1> <div className="wrapper"> <div className="left"> <h2>Ragged Right</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="justified"> <h2>Justified / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> <div className="justified-hyphen"> <h2>Justified with Hyphenation / clamp=3</h2> <Dotdotdot clamp={ 3 }> <p> Either the well was very deep, or she fell very slowly, for she had plenty of time as she went down to look about her and to wonder what was going to happen next. First, she tried to look down and make out what she was coming to, but it was too dark to see anything; then she looked at the sides of the well, and noticed that they were filled with cupboards and book-shelves; here and there she saw maps and pictures hung upon pegs. She took down a jar from one of the shelves as she passed; it was labelled `ORANGE MARMALADE', but to her great disappointment it was empty: she did not like to drop the jar for fear of killing somebody, so managed to put it into one of the cupboards as she fell past it. </p> </Dotdotdot> </div> </div> </div> ); } } ReactDOM.hydrate(<App />, document.querySelector('#app'));
front-end/app/components/category/Display_category_component.js
akumbhani66/cantaloupe
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; import React, {Component} from 'react'; import { Link } from 'react-router' import axios from 'axios'; import Select from 'react-select'; import 'react-select/dist/react-select.css'; import './styles.css'; function Validator(value){ if(!value){ return "*required"; } return true; } class Display_category extends Component { constructor(props) { super(props); this.state = { data :[], activeAll: 'active' }; this.filterCategory = this.filterCategory.bind(this); this.editCategory = this.editCategory.bind(this); this.deleteCategory = this.deleteCategory.bind(this); this.addCategory = this.addCategory.bind(this); } editCategory(row, cellName, cellValue) { this.props.actions.editCategory(row); } addCategory(row) { this.props.actions.addCategory(row); } deleteCategory(id) { this.props.actions.deleteCategory(id); } filterCategory(val) { this.setState({activeAll: val.value}); var all = false; if(val.value == "all") { all = true } if(this.state.activeAll != val.value) { this.props.actions.fetchCategories(all); } } componentDidMount() { this.props.actions.fetchCategories(false); $('.modal-content').css("width", "500px"); } render() { let categories = []; if(this.props.state.category.AllCategories.length) { categories = this.props.state.category.AllCategories; } let selectRowProp = { mode: "checkbox", clickToSelect: true, bgColor: "rgb(238, 193, 213)" }; let options = [ { value: 'active', label: 'Active' }, { value: 'all', label: 'All' } ]; return ( <div> <div className="clearfix"> <div className="col-lg-2"> <Select className="activeStyle" clearable={ false } options={ options } onChange={ this.filterCategory } placeholder="Active" searchable={ false } value={ this.state.activeAll } /> </div> </div> <div> <BootstrapTable data={ categories } pagination={true} options={{ afterDeleteRow :this.deleteCategory, onAddRow :this.addCategory }} deleteRow={true} selectRow={selectRowProp} insertRow={true} exportCSV={true} cellEdit={{ mode: "dbclick", blurToSave: true, afterSaveCell: this.editCategory }} search={true} striped={true} hover={true} > <TableHeaderColumn dataField="Id" editable={false} isKey={true} autoValue={true} hidden={true} >Id</TableHeaderColumn> <TableHeaderColumn width="260" dataSort={true} dataField="Category" editable={{ validator:Validator }} >Category</TableHeaderColumn> <TableHeaderColumn width="350" dataSort={true} dataField="Description" editable={{ type:'textarea' }} >Description</TableHeaderColumn> </BootstrapTable> </div> </div> ) } } export default Display_category
app/javascript/flavours/glitch/features/follow_requests/components/account_authorize.js
glitch-soc/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Permalink from 'flavours/glitch/components/permalink'; import Avatar from 'flavours/glitch/components/avatar'; import DisplayName from 'flavours/glitch/components/display_name'; import IconButton from 'flavours/glitch/components/icon_button'; import { defineMessages, injectIntl } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ authorize: { id: 'follow_request.authorize', defaultMessage: 'Authorize' }, reject: { id: 'follow_request.reject', defaultMessage: 'Reject' }, }); export default @injectIntl class AccountAuthorize extends ImmutablePureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, onAuthorize: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; render () { const { intl, account, onAuthorize, onReject } = this.props; const content = { __html: account.get('note_emojified') }; return ( <div className='account-authorize__wrapper'> <div className='account-authorize'> <Permalink href={account.get('url')} to={`/@${account.get('acct')}`} className='detailed-status__display-name'> <div className='account-authorize__avatar'><Avatar account={account} size={48} /></div> <DisplayName account={account} /> </Permalink> <div className='account__header__content translate' dangerouslySetInnerHTML={content} /> </div> <div className='account--panel'> <div className='account--panel__button'><IconButton title={intl.formatMessage(messages.authorize)} icon='check' onClick={onAuthorize} /></div> <div className='account--panel__button'><IconButton title={intl.formatMessage(messages.reject)} icon='times' onClick={onReject} /></div> </div> </div> ); } }
ajax/libs/react-native-web/0.0.0-e886427e3/exports/createElement/index.js
cdnjs/cdnjs
/** * Copyright (c) Nicolas Gallagher. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import AccessibilityUtil from '../../modules/AccessibilityUtil'; import createDOMProps from '../../modules/createDOMProps'; import React from 'react'; var createElement = function createElement(component, props) { // Use equivalent platform elements where possible. var accessibilityComponent; if (component && component.constructor === String) { accessibilityComponent = AccessibilityUtil.propsToAccessibilityComponent(props); } var Component = accessibilityComponent || component; var domProps = createDOMProps(Component, props); for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { children[_key - 2] = arguments[_key]; } return /*#__PURE__*/React.createElement.apply(React, [Component, domProps].concat(children)); }; export default createElement;
packages/material-ui-icons/src/DirectionsBoatRounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M20 21c-1.29 0-2.58-.41-3.74-1.14-.16-.1-.37-.1-.53 0-2.31 1.47-5.16 1.47-7.47 0-.16-.1-.37-.1-.53 0C6.58 20.59 5.29 21 4 21H3c-.55 0-1 .45-1 1s.45 1 1 1h1c1.38 0 2.74-.35 4-.99 2.52 1.29 5.48 1.29 8 0 1.26.65 2.62.99 4 .99h1c.55 0 1-.45 1-1s-.45-1-1-1h-1zM3.95 19H4c1.42 0 2.7-.7 3.66-1.64.19-.18.5-.18.69 0C9.3 18.3 10.58 19 12 19s2.7-.7 3.66-1.64c.19-.19.49-.19.69 0C17.3 18.3 18.58 19 20 19h.05l1.89-6.68c.08-.26.06-.54-.06-.78s-.34-.42-.6-.5L20 10.62V6c0-1.1-.9-2-2-2h-3V2c0-.55-.45-1-1-1h-4c-.55 0-1 .45-1 1v2H6c-1.1 0-2 .9-2 2v4.62l-1.29.42c-.26.08-.48.26-.6.5s-.15.52-.06.78L3.95 19zM7 6h10c.55 0 1 .45 1 1v2.97L12.62 8.2c-.41-.13-.84-.13-1.25 0L6 9.97V7c0-.55.45-1 1-1z" /></React.Fragment> , 'DirectionsBoatRounded');
app/javascript/mastodon/features/compose/components/warning.js
imas/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; export default class Warning extends React.PureComponent { static propTypes = { message: PropTypes.node.isRequired, }; render () { const { message } = this.props; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( <div className='compose-form__warning' style={{ opacity: opacity, transform: `scale(${scaleX}, ${scaleY})` }}> {message} </div> )} </Motion> ); } }
ajax/libs/react-router/0.8.0/react-router.min.js
cgvarela/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=e()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&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}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){var LocationActions={SETUP:"setup",PUSH:"push",REPLACE:"replace",POP:"pop"};module.exports=LocationActions},{}],2:[function(_dereq_,module){function DefaultRoute(props){return Route(merge(props,{path:null,isDefault:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=DefaultRoute},{"./Route":6,"react/lib/merge":49}],3:[function(_dereq_,module){function isLeftClickEvent(event){return 0===event.button}function isModifiedEvent(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,merge=_dereq_("react/lib/merge"),ActiveState=_dereq_("../mixins/ActiveState"),Transitions=_dereq_("../mixins/Transitions"),Link=React.createClass({displayName:"Link",mixins:[ActiveState,Transitions],propTypes:{to:React.PropTypes.string.isRequired,activeClassName:React.PropTypes.string.isRequired,params:React.PropTypes.object,query:React.PropTypes.object,onClick:React.PropTypes.func},getDefaultProps:function(){return{activeClassName:"active"}},getInitialState:function(){return{isActive:!1}},updateActiveState:function(){this.setState({isActive:this.isActive(this.props.to,this.props.params,this.props.query)})},componentWillReceiveProps:function(nextProps){this.setState({isActive:this.isActive(nextProps.to,nextProps.params,nextProps.query)})},handleClick:function(event){var onClickResult,allowTransition=!0;this.props.onClick&&(onClickResult=this.props.onClick(event)),!isModifiedEvent(event)&&isLeftClickEvent(event)&&((onClickResult===!1||event.defaultPrevented===!0)&&(allowTransition=!1),event.preventDefault(),allowTransition&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var className=this.props.className||"";return this.state.isActive&&(className+=" "+this.props.activeClassName),className},render:function(){var props=merge(this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return React.DOM.a(props,this.props.children)}});module.exports=Link},{"../mixins/ActiveState":14,"../mixins/Transitions":24,"react/lib/merge":49}],4:[function(_dereq_,module){function NotFoundRoute(props){return Route(merge(props,{path:null,catchAll:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=NotFoundRoute},{"./Route":6,"react/lib/merge":49}],5:[function(_dereq_,module){function createRedirectHandler(to){return React.createClass({statics:{willTransitionTo:function(transition,params,query){transition.redirect(to,params,query)}},render:function(){return null}})}function Redirect(props){return Route({name:props.name,path:props.from||props.path||"*",handler:createRedirectHandler(props.to)})}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Route=_dereq_("./Route");module.exports=Redirect},{"./Route":6}],6:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,withoutProperties=_dereq_("../utils/withoutProperties"),RESERVED_PROPS={handler:!0,path:!0,defaultRoute:!0,notFoundRoute:!0,paramNames:!0,children:!0},Route=React.createClass({displayName:"Route",statics:{getUnreservedProps:function(props){return withoutProperties(props,RESERVED_PROPS)}},propTypes:{handler:React.PropTypes.any.isRequired,path:React.PropTypes.string,name:React.PropTypes.string},render:function(){throw new Error("The <Route> component should not be rendered directly. You may be missing a <Routes> wrapper around your list of routes.")}});module.exports=Route},{"../utils/withoutProperties":34}],7:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,TransitionHandler=_dereq_("../mixins/TransitionHandler"),Routes=React.createClass({displayName:"Routes",mixins:[TransitionHandler],render:function(){var match=this.state.matches[0];return null==match?null:match.route.props.handler(this.getHandlerProps())}});module.exports=Routes},{"../mixins/TransitionHandler":23}],8:[function(_dereq_,module){var copyProperties=_dereq_("react/lib/copyProperties"),Dispatcher=_dereq_("flux").Dispatcher,LocationDispatcher=copyProperties(new Dispatcher,{handleViewAction:function(action){this.dispatch({source:"VIEW_ACTION",action:action})}});module.exports=LocationDispatcher},{flux:36,"react/lib/copyProperties":45}],9:[function(_dereq_,module,exports){exports.DefaultRoute=_dereq_("./components/DefaultRoute"),exports.Link=_dereq_("./components/Link"),exports.NotFoundRoute=_dereq_("./components/NotFoundRoute"),exports.Redirect=_dereq_("./components/Redirect"),exports.Route=_dereq_("./components/Route"),exports.Routes=_dereq_("./components/Routes"),exports.ActiveState=_dereq_("./mixins/ActiveState"),exports.AsyncState=_dereq_("./mixins/AsyncState"),exports.PathState=_dereq_("./mixins/PathState"),exports.RouteLookup=_dereq_("./mixins/RouteLookup"),exports.Transitions=_dereq_("./mixins/Transitions")},{"./components/DefaultRoute":2,"./components/Link":3,"./components/NotFoundRoute":4,"./components/Redirect":5,"./components/Route":6,"./components/Routes":7,"./mixins/ActiveState":14,"./mixins/AsyncState":15,"./mixins/PathState":18,"./mixins/RouteLookup":20,"./mixins/Transitions":24}],10:[function(_dereq_,module){function getHashPath(){return window.location.hash.substr(1)}function ensureSlash(){var path=getHashPath();return"/"===path.charAt(0)?!0:(HashLocation.replace("/"+path),!1)}function onHashChange(){if(ensureSlash()){{getHashPath()}LocationDispatcher.handleViewAction({type:_actionType||LocationActions.POP,path:getHashPath()}),_actionType=null}}var _actionType,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),getWindowPath=_dereq_("../utils/getWindowPath"),_isSetup=!1,HashLocation={setup:function(){_isSetup||(invariant(canUseDOM,"You cannot use HashLocation in an environment with no DOM"),ensureSlash(),LocationDispatcher.handleViewAction({type:LocationActions.SETUP,path:getHashPath()}),window.addEventListener?window.addEventListener("hashchange",onHashChange,!1):window.attachEvent("onhashchange",onHashChange),_isSetup=!0)},teardown:function(){window.removeEventListener?window.removeEventListener("hashchange",onHashChange,!1):window.detachEvent("onhashchange",onHashChange),_isSetup=!1},push:function(path){_actionType=LocationActions.PUSH,window.location.hash=path},replace:function(path){_actionType=LocationActions.REPLACE,window.location.replace(getWindowPath()+"#"+path)},pop:function(){_actionType=LocationActions.POP,window.history.back()},toString:function(){return"<HashLocation>"}};module.exports=HashLocation},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":8,"../utils/getWindowPath":30,"react/lib/ExecutionEnvironment":44,"react/lib/invariant":47}],11:[function(_dereq_,module){function onPopState(){LocationDispatcher.handleViewAction({type:LocationActions.POP,path:getWindowPath()})}var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),getWindowPath=_dereq_("../utils/getWindowPath"),_isSetup=!1,HistoryLocation={setup:function(){_isSetup||(invariant(canUseDOM,"You cannot use HistoryLocation in an environment with no DOM"),LocationDispatcher.handleViewAction({type:LocationActions.SETUP,path:getWindowPath()}),window.addEventListener?window.addEventListener("popstate",onPopState,!1):window.attachEvent("popstate",onPopState),_isSetup=!0)},teardown:function(){window.removeEventListener?window.removeEventListener("popstate",onPopState,!1):window.detachEvent("popstate",onPopState),_isSetup=!1},push:function(path){window.history.pushState({path:path},"",path),LocationDispatcher.handleViewAction({type:LocationActions.PUSH,path:getWindowPath()})},replace:function(path){window.history.replaceState({path:path},"",path),LocationDispatcher.handleViewAction({type:LocationActions.REPLACE,path:getWindowPath()})},pop:function(){window.history.back()},toString:function(){return"<HistoryLocation>"}};module.exports=HistoryLocation},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":8,"../utils/getWindowPath":30,"react/lib/ExecutionEnvironment":44,"react/lib/invariant":47}],12:[function(_dereq_,module){var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),getWindowPath=_dereq_("../utils/getWindowPath"),RefreshLocation={setup:function(){invariant(canUseDOM,"You cannot use RefreshLocation in an environment with no DOM"),LocationDispatcher.handleViewAction({type:LocationActions.SETUP,path:getWindowPath()})},push:function(path){window.location=path},replace:function(path){window.location.replace(path)},pop:function(){window.history.back()},toString:function(){return"<RefreshLocation>"}};module.exports=RefreshLocation},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":8,"../utils/getWindowPath":30,"react/lib/ExecutionEnvironment":44,"react/lib/invariant":47}],13:[function(_dereq_,module){function routeIsActive(activeRoutes,routeName){return activeRoutes.some(function(route){return route.props.name===routeName})}function paramsAreActive(activeParams,params){for(var property in params)if(String(activeParams[property])!==String(params[property]))return!1;return!0}function queryIsActive(activeQuery,query){for(var property in query)if(String(activeQuery[property])!==String(query[property]))return!1;return!0}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,ChangeEmitter=_dereq_("./ChangeEmitter"),ActiveDelegate={mixins:[ChangeEmitter],childContextTypes:{activeDelegate:React.PropTypes.any.isRequired},getChildContext:function(){return{activeDelegate:this}},propTypes:{initialActiveState:React.PropTypes.object},getDefaultProps:function(){return{initialActiveState:{}}},getInitialState:function(){var state=this.props.initialActiveState;return{activeRoutes:state.activeRoutes||[],activeParams:state.activeParams||{},activeQuery:state.activeQuery||{}}},isActive:function(routeName,params,query){var isActive=routeIsActive(this.state.activeRoutes,routeName)&&paramsAreActive(this.state.activeParams,params);return query?isActive&&queryIsActive(this.state.activeQuery,query):isActive}};module.exports=ActiveDelegate},{"./ChangeEmitter":16}],14:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,ActiveState=(_dereq_("./ActiveDelegate"),{contextTypes:{activeDelegate:React.PropTypes.any.isRequired},componentWillMount:function(){this.updateActiveState&&this.updateActiveState()},componentDidMount:function(){this.context.activeDelegate.addChangeListener(this.handleActiveStateChange)},componentWillUnmount:function(){this.context.activeDelegate.removeChangeListener(this.handleActiveStateChange)},handleActiveStateChange:function(){this.isMounted()&&this.updateActiveState&&this.updateActiveState()},isActive:function(routeName,params,query){return this.context.activeDelegate.isActive(routeName,params,query)}});module.exports=ActiveState},{"./ActiveDelegate":13}],15:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,resolveAsyncState=_dereq_("../utils/resolveAsyncState"),AsyncState={propTypes:{initialAsyncState:React.PropTypes.object},getInitialState:function(){return this.props.initialAsyncState||null},updateAsyncState:function(state){this.isMounted()&&this.setState(state)},componentDidMount:function(){this.props.initialAsyncState||"function"!=typeof this.constructor.getInitialAsyncState||resolveAsyncState(this.constructor.getInitialAsyncState(this.props.params,this.props.query,this.updateAsyncState),this.updateAsyncState)}};module.exports=AsyncState},{"../utils/resolveAsyncState":31}],16:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,EventEmitter=_dereq_("events").EventEmitter,CHANGE_EVENT="change",ChangeEmitter={propTypes:{maxChangeListeners:React.PropTypes.number.isRequired},getDefaultProps:function(){return{maxChangeListeners:0}},componentWillMount:function(){this._events=new EventEmitter,this._events.setMaxListeners(this.props.maxChangeListeners)},componentWillReceiveProps:function(nextProps){this._events.setMaxListeners(nextProps.maxChangeListeners)},componentWillUnmount:function(){this._events.removeAllListeners()},addChangeListener:function(listener){this._events.addListener(CHANGE_EVENT,listener)},removeChangeListener:function(listener){this._events.removeListener(CHANGE_EVENT,listener)},emitChange:function(){this._events.emit(CHANGE_EVENT)}};module.exports=ChangeEmitter},{events:35}],17:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),PathState=_dereq_("./PathState"),RouteContainer=_dereq_("./RouteContainer"),LocationActions=_dereq_("../actions/LocationActions"),HashLocation=_dereq_("../locations/HashLocation"),Path=_dereq_("../utils/Path"),PathDelegate={mixins:[PathState,RouteContainer],childContextTypes:{pathDelegate:React.PropTypes.any.isRequired},getChildContext:function(){return{pathDelegate:this}},makePath:function(to,params,query){var path;if(Path.isAbsolute(to))path=Path.normalize(to);else{var route=this.getRouteByName(to);invariant(route,'Unable to find a route named "'+to+'". Make sure you have a <Route name="'+to+'"> defined somewhere in your <Routes>'),path=route.props.path}return Path.withQuery(Path.injectParams(path,params),query)},makeHref:function(to,params,query){var path=this.makePath(to,params,query);return this.getLocation()===HashLocation?"#"+path:path},transitionTo:function(to,params,query){var path=this.makePath(to,params,query),location=this.getLocation();location?location.push(path):this.updatePath&&this.updatePath(path,LocationActions.PUSH)},replaceWith:function(to,params,query){var path=this.makePath(to,params,query),location=this.getLocation();location?location.replace(path):this.updatePath&&this.updatePath(path,LocationActions.REPLACE)},goBack:function(){var location=this.getLocation();invariant(location,"You cannot goBack without a location"),location.pop()}};module.exports=PathDelegate},{"../actions/LocationActions":1,"../locations/HashLocation":10,"../utils/Path":26,"./PathState":18,"./RouteContainer":19,"react/lib/invariant":47}],18:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,HashLocation=_dereq_("../locations/HashLocation"),HistoryLocation=_dereq_("../locations/HistoryLocation"),RefreshLocation=_dereq_("../locations/RefreshLocation"),supportsHistory=_dereq_("../utils/supportsHistory"),PathStore=_dereq_("../stores/PathStore"),NAMED_LOCATIONS={none:null,hash:HashLocation,history:HistoryLocation,refresh:RefreshLocation},PathState={propTypes:{fixedPath:React.PropTypes.string,location:function(props,propName,componentName){var location=props[propName];return"string"!=typeof location||location in NAMED_LOCATIONS?void 0:new Error('Unknown location "'+location+'", see '+componentName)}},getDefaultProps:function(){return{fixedPath:null,location:canUseDOM?HashLocation:null}},getLocation:function(){var location=this.props.location;return"string"==typeof location&&(location=NAMED_LOCATIONS[location]),location!==HistoryLocation||supportsHistory()||(location=RefreshLocation),location},componentWillMount:function(){var location=this.getLocation();invariant(null==this.props.fixedPath||null==this.getLocation(),"You cannot use a fixed path with a location. Choose one or the other"),location&&location.setup&&location.setup(),this.updatePath&&this.updatePath(this.getCurrentPath(),this.getCurrentActionType())},componentDidMount:function(){PathStore.addChangeListener(this.handlePathChange)},componentWillUnmount:function(){PathStore.removeChangeListener(this.handlePathChange)},handlePathChange:function(){this.isMounted()&&this.updatePath&&this.updatePath(this.getCurrentPath(),this.getCurrentActionType())},getCurrentPath:function(){return this.props.fixedPath||PathStore.getCurrentPath()},getCurrentActionType:function(){return PathStore.getCurrentActionType()}};module.exports=PathState},{"../locations/HashLocation":10,"../locations/HistoryLocation":11,"../locations/RefreshLocation":12,"../stores/PathStore":25,"../utils/supportsHistory":33,"react/lib/ExecutionEnvironment":44,"react/lib/invariant":47}],19:[function(_dereq_,module){function processRoute(route,container,namedRoutes){var props=route.props;invariant(React.isValidClass(props.handler),'The handler for the "%s" route must be a valid React class',props.name||props.path);var parentPath=container&&container.props.path||"/";if(!props.path&&!props.name||props.isDefault||props.catchAll)props.path=parentPath,props.catchAll&&(props.path+="*");else{var path=props.path||props.name;Path.isAbsolute(path)||(path=Path.join(parentPath,path)),props.path=Path.normalize(path)}if(props.paramNames=Path.extractParamNames(props.path),container&&Array.isArray(container.props.paramNames)&&container.props.paramNames.forEach(function(paramName){invariant(-1!==props.paramNames.indexOf(paramName),'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',props.path,paramName,container.props.path)}),props.name){var existingRoute=namedRoutes[props.name];invariant(!existingRoute||route===existingRoute,'You cannot use the name "%s" for more than one route',props.name),namedRoutes[props.name]=route}return props.catchAll?(invariant(container,"<NotFoundRoute> must have a parent <Route>"),invariant(null==container.props.notFoundRoute,"You may not have more than one <NotFoundRoute> per <Route>"),container.props.notFoundRoute=route,null):props.isDefault?(invariant(container,"<DefaultRoute> must have a parent <Route>"),invariant(null==container.props.defaultRoute,"You may not have more than one <DefaultRoute> per <Route>"),container.props.defaultRoute=route,null):(props.children=processRoutes(props.children,route,namedRoutes),route)}function processRoutes(children,container,namedRoutes){var routes=[];return React.Children.forEach(children,function(child){(child=processRoute(child,container,namedRoutes))&&routes.push(child)}),routes}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),Path=_dereq_("../utils/Path"),RouteContainer={childContextTypes:{routeContainer:React.PropTypes.any.isRequired},getChildContext:function(){return{routeContainer:this}},getInitialState:function(){var namedRoutes={};return{namedRoutes:namedRoutes,routes:processRoutes(this.props.children,this,namedRoutes)}},getRoutes:function(){return this.state.routes},getNamedRoutes:function(){return this.state.namedRoutes},getRouteByName:function(routeName){return this.state.namedRoutes[routeName]||null}};module.exports=RouteContainer},{"../utils/Path":26,"react/lib/invariant":47}],20:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,RouteLookup={contextTypes:{routeContainer:React.PropTypes.any.isRequired},getRoutes:function(){return this.context.routeContainer.getRoutes()},getNamedRoutes:function(){return this.context.routeContainer.getNamedRoutes()},getRouteByName:function(routeName){return this.context.routeContainer.getRouteByName(routeName)}};module.exports=RouteLookup},{}],21:[function(_dereq_,module){var ScrollState=_dereq_("./ScrollState"),ScrollDelegate={mixins:[ScrollState],componentWillMount:function(){this.getScrollBehavior()&&(this._scrollPositions={})},recordScroll:function(path){this._scrollPositions&&(this._scrollPositions[path]=this.getCurrentScrollPosition())},updateScroll:function(path,actionType){if(this._scrollPositions){var behavior=this.getScrollBehavior(),position=this._scrollPositions[path];behavior&&position&&behavior.updateScrollPosition(position,actionType)}}};module.exports=ScrollDelegate},{"./ScrollState":22}],22:[function(_dereq_,module){var invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,LocationActions=_dereq_("../actions/LocationActions"),ImitateBrowserBehavior={updateScrollPosition:function(position,actionType){switch(actionType){case LocationActions.PUSH:case LocationActions.REPLACE:window.scrollTo(0,0);break;case LocationActions.POP:window.scrollTo(position.x,position.y)}}},ScrollToTopBehavior={updateScrollPosition:function(){window.scrollTo(0,0)}},NAMED_SCROLL_BEHAVIORS={none:null,imitateBrowser:ImitateBrowserBehavior,scrollToTop:ScrollToTopBehavior},ScrollState={propTypes:{scrollBehavior:function(props,propName,componentName){var behavior=props[propName];return"string"!=typeof behavior||behavior in NAMED_SCROLL_BEHAVIORS?void 0:new Error('Unknown scroll behavior "'+behavior+'", see '+componentName)}},getDefaultProps:function(){return{scrollBehavior:canUseDOM?ImitateBrowserBehavior:null}},getScrollBehavior:function(){var behavior=this.props.scrollBehavior;return"string"==typeof behavior&&(behavior=NAMED_SCROLL_BEHAVIORS[behavior]),behavior},componentWillMount:function(){var behavior=this.getScrollBehavior();invariant(null==behavior||canUseDOM,"Cannot use scroll behavior without a DOM")},getCurrentScrollPosition:function(){return invariant(canUseDOM,"Cannot get current scroll position without a DOM"),{x:window.scrollX,y:window.scrollY}}};module.exports=ScrollState},{"../actions/LocationActions":1,"react/lib/ExecutionEnvironment":44,"react/lib/invariant":47}],23:[function(_dereq_,module){function makeMatch(route,params){return{route:route,params:params}}function getRootMatch(matches){return matches[matches.length-1]}function findMatches(path,routes,defaultRoute,notFoundRoute){for(var route,params,matches=null,i=0,len=routes.length;len>i;++i){if(route=routes[i],matches=findMatches(path,route.props.children,route.props.defaultRoute,route.props.notFoundRoute),null!=matches){var rootParams=getRootMatch(matches).params;return params=route.props.paramNames.reduce(function(params,paramName){return params[paramName]=rootParams[paramName],params},{}),matches.unshift(makeMatch(route,params)),matches}if(params=Path.extractParams(route.props.path,path))return[makeMatch(route,params)]}return defaultRoute&&(params=Path.extractParams(defaultRoute.props.path,path))?[makeMatch(defaultRoute,params)]:notFoundRoute&&(params=Path.extractParams(notFoundRoute.props.path,path))?[makeMatch(notFoundRoute,params)]:matches}function hasMatch(matches,match){return matches.some(function(m){if(m.route!==match.route)return!1;for(var property in m.params)if(m.params[property]!==match.params[property])return!1;return!0})}function updateMatchComponents(matches,refs){for(var component,i=0;component=refs.__activeRoute__;)matches[i++].component=component,refs=component.refs}function computeNextState(component,transition,callback){if(component.state.path===transition.path)return callback();var currentMatches=component.state.matches,nextMatches=component.match(transition.path);warning(nextMatches,'No route matches path "'+transition.path+'". Make sure you have <Route path="'+transition.path+'"> somewhere in your routes'),nextMatches||(nextMatches=[]);var fromMatches,toMatches;currentMatches.length?(updateMatchComponents(currentMatches,component.refs),fromMatches=currentMatches.filter(function(match){return!hasMatch(nextMatches,match)}),toMatches=nextMatches.filter(function(match){return!hasMatch(currentMatches,match)})):(fromMatches=[],toMatches=nextMatches);var query=Path.extractQuery(transition.path)||{};runTransitionFromHooks(fromMatches,transition,function(error){return error||transition.isAborted?callback(error):void runTransitionToHooks(toMatches,transition,query,function(error){if(error||transition.isAborted)return callback(error);var matches=currentMatches.slice(0,currentMatches.length-fromMatches.length).concat(toMatches),rootMatch=getRootMatch(matches),params=rootMatch&&rootMatch.params||{},routes=matches.map(function(match){return match.route});callback(null,{path:transition.path,matches:matches,activeRoutes:routes,activeParams:params,activeQuery:query})})})}function runTransitionFromHooks(matches,transition,callback){var hooks=reversedArray(matches).map(function(match){return function(){var handler=match.route.props.handler;if(!transition.isAborted&&handler.willTransitionFrom)return handler.willTransitionFrom(transition,match.component);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runTransitionToHooks(matches,transition,query,callback){var hooks=matches.map(function(match){return function(){var handler=match.route.props.handler;!transition.isAborted&&handler.willTransitionTo&&handler.willTransitionTo(transition,match.params,query);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runHooks(hooks,callback){try{var promise=hooks.reduce(function(promise,hook){return promise?promise.then(hook):hook()},null)}catch(error){return callback(error)}promise?promise.then(function(){setTimeout(callback)},function(error){setTimeout(function(){callback(error)})}):callback()}function returnNull(){return null}function computeHandlerProps(matches,query){var handler=returnNull,props={ref:null,params:null,query:null,activeRouteHandler:handler,key:null};return reversedArray(matches).forEach(function(match){var route=match.route;props=Route.getUnreservedProps(route.props),props.ref="__activeRoute__",props.params=match.params,props.query=query,props.activeRouteHandler=handler,route.props.addHandlerKey&&(props.key=Path.injectParams(route.props.path,match.params)),handler=function(props,addedProps){if(arguments.length>2&&"undefined"!=typeof arguments[2])throw new Error("Passing children to a route handler is not supported");return route.props.handler(copyProperties(props,addedProps))}.bind(this,props)}),props}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,copyProperties=_dereq_("react/lib/copyProperties"),Route=_dereq_("../components/Route"),ActiveDelegate=_dereq_("./ActiveDelegate"),PathDelegate=_dereq_("./PathDelegate"),ScrollDelegate=_dereq_("./ScrollDelegate"),reversedArray=_dereq_("../utils/reversedArray"),Transition=_dereq_("../utils/Transition"),Redirect=_dereq_("../utils/Redirect"),Path=_dereq_("../utils/Path"),BrowserTransitionHandling={handleTransitionError:function(error){throw error},handleAbortedTransition:function(transition){var reason=transition.abortReason;reason instanceof Redirect?this.replaceWith(reason.to,reason.params,reason.query):this.goBack()}},ServerTransitionHandling={handleTransitionError:function(){},handleAbortedTransition:function(transition){transition.abortReason}},TransitionHandling=canUseDOM?BrowserTransitionHandling:ServerTransitionHandling,TransitionHandler={mixins:[ActiveDelegate,PathDelegate,ScrollDelegate],propTypes:{onTransitionError:React.PropTypes.func.isRequired,onAbortedTransition:React.PropTypes.func.isRequired},getDefaultProps:function(){return{onTransitionError:TransitionHandling.handleTransitionError,onAbortedTransition:TransitionHandling.handleAbortedTransition}},getInitialState:function(){return{matches:[]}},updatePath:function(path,actionType){if(this.state.path!==path){this.state.path&&this.recordScroll(this.state.path);var self=this;this.dispatch(path,function(error,transition){error?self.props.onTransitionError.call(self,error):transition.isAborted?self.props.onAbortedTransition.call(self,transition):(self.emitChange(),self.updateScroll(path,actionType))})}},match:function(path){return findMatches(Path.withoutQuery(path),this.getRoutes(),this.props.defaultRoute,this.props.notFoundRoute)},dispatch:function(path,callback){var transition=new Transition(this,path),self=this;computeNextState(this,transition,function(error,nextState){return error||null==nextState?callback(error,transition):void self.setState(nextState,function(){callback(null,transition)})})},getHandlerProps:function(){return computeHandlerProps(this.state.matches,this.state.activeQuery)},getActiveRoute:function(){return this.refs.__activeRoute__}};module.exports=TransitionHandler},{"../components/Route":6,"../utils/Path":26,"../utils/Redirect":28,"../utils/Transition":29,"../utils/reversedArray":32,"./ActiveDelegate":13,"./PathDelegate":17,"./ScrollDelegate":21,"react/lib/ExecutionEnvironment":44,"react/lib/copyProperties":45,"react/lib/warning":53}],24:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Transitions={contextTypes:{pathDelegate:React.PropTypes.any.isRequired},makePath:function(to,params,query){return this.context.pathDelegate.makePath(to,params,query)},makeHref:function(to,params,query){return this.context.pathDelegate.makeHref(to,params,query)},transitionTo:function(to,params,query){return this.context.pathDelegate.transitionTo(to,params,query)},replaceWith:function(to,params,query){return this.context.pathDelegate.replaceWith(to,params,query)},goBack:function(){return this.context.pathDelegate.goBack()}};module.exports=Transitions},{}],25:[function(_dereq_,module){function notifyChange(){_events.emit(CHANGE_EVENT)}var _currentPath,_currentActionType,EventEmitter=_dereq_("events").EventEmitter,LocationActions=_dereq_("../actions/LocationActions"),LocationDispatcher=_dereq_("../dispatchers/LocationDispatcher"),CHANGE_EVENT="change",_events=new EventEmitter,PathStore={addChangeListener:function(listener){_events.addListener(CHANGE_EVENT,listener)},removeChangeListener:function(listener){_events.removeListener(CHANGE_EVENT,listener)},removeAllChangeListeners:function(){_events.removeAllListeners(CHANGE_EVENT)},getCurrentPath:function(){return _currentPath},getCurrentActionType:function(){return _currentActionType},dispatchToken:LocationDispatcher.register(function(payload){var action=payload.action;switch(action.type){case LocationActions.SETUP:case LocationActions.PUSH:case LocationActions.REPLACE:case LocationActions.POP:_currentPath!==action.path&&(_currentPath=action.path,_currentActionType=action.type,notifyChange())}})};module.exports=PathStore},{"../actions/LocationActions":1,"../dispatchers/LocationDispatcher":8,events:35}],26:[function(_dereq_,module){function encodeURL(url){return encodeURIComponent(url).replace(/%20/g,"+")}function decodeURL(url){return decodeURIComponent(url.replace(/\+/g," "))}function encodeURLPath(path){return String(path).split("/").map(encodeURL).join("/") }function compilePattern(pattern){if(!(pattern in _compiledPatterns)){var paramNames=[],source=pattern.replace(paramMatcher,function(match,paramName){return paramName?(paramNames.push(paramName),"([^/?#]+)"):"*"===match?(paramNames.push("splat"),"(.*?)"):"\\"+match});_compiledPatterns[pattern]={matcher:new RegExp("^"+source+"$","i"),paramNames:paramNames}}return _compiledPatterns[pattern]}var invariant=_dereq_("react/lib/invariant"),merge=_dereq_("qs/lib/utils").merge,qs=_dereq_("qs"),paramMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,queryMatcher=/\?(.+)/,_compiledPatterns={},Path={extractParamNames:function(pattern){return compilePattern(pattern).paramNames},extractParams:function(pattern,path){var object=compilePattern(pattern),match=decodeURL(path).match(object.matcher);if(!match)return null;var params={};return object.paramNames.forEach(function(paramName,index){params[paramName]=match[index+1]}),params},injectParams:function(pattern,params){params=params||{};var splatIndex=0;return pattern.replace(paramMatcher,function(match,paramName){paramName=paramName||"splat",invariant(null!=params[paramName],'Missing "'+paramName+'" parameter for path "'+pattern+'"');var segment;return"splat"===paramName&&Array.isArray(params[paramName])?(segment=params[paramName][splatIndex++],invariant(null!=segment,"Missing splat # "+splatIndex+' for path "'+pattern+'"')):segment=params[paramName],encodeURLPath(segment)})},extractQuery:function(path){var match=decodeURL(path).match(queryMatcher);return match&&qs.parse(match[1])},withoutQuery:function(path){return path.replace(queryMatcher,"")},withQuery:function(path,query){var existingQuery=Path.extractQuery(path);existingQuery&&(query=query?merge(existingQuery,query):existingQuery);var queryString=query&&qs.stringify(query);return queryString?Path.withoutQuery(path)+"?"+queryString:path},isAbsolute:function(path){return"/"===path.charAt(0)},normalize:function(path){return path.replace(/^\/*/,"/")},join:function(a,b){return a.replace(/\/*$/,"/")+b}};module.exports=Path},{qs:39,"qs/lib/utils":43,"react/lib/invariant":47}],27:[function(_dereq_,module){var Promise=_dereq_("when/lib/Promise");module.exports=Promise},{"when/lib/Promise":54}],28:[function(_dereq_,module){function Redirect(to,params,query){this.to=to,this.params=params,this.query=query}module.exports=Redirect},{}],29:[function(_dereq_,module){function Transition(pathDelegate,path){this.pathDelegate=pathDelegate,this.path=path,this.abortReason=null,this.isAborted=!1}var mixInto=_dereq_("react/lib/mixInto"),Promise=_dereq_("./Promise"),Redirect=_dereq_("./Redirect");mixInto(Transition,{abort:function(reason){this.abortReason=reason,this.isAborted=!0},redirect:function(to,params,query){this.abort(new Redirect(to,params,query))},wait:function(value){this.promise=Promise.resolve(value)},retry:function(){this.pathDelegate.replaceWith(this.path)}}),module.exports=Transition},{"./Promise":27,"./Redirect":28,"react/lib/mixInto":52}],30:[function(_dereq_,module){function getWindowPath(){return window.location.pathname+window.location.search}module.exports=getWindowPath},{}],31:[function(_dereq_,module){function resolveAsyncState(asyncState,setState){if(null==asyncState)return Promise.resolve();var keys=Object.keys(asyncState);return Promise.all(keys.map(function(key){return Promise.resolve(asyncState[key]).then(function(value){var newState={};newState[key]=value,setState(newState)})}))}var Promise=_dereq_("when/lib/Promise");module.exports=resolveAsyncState},{"when/lib/Promise":54}],32:[function(_dereq_,module){function reversedArray(array){return array.slice(0).reverse()}module.exports=reversedArray},{}],33:[function(_dereq_,module){function supportsHistory(){var ua=navigator.userAgent;return-1===ua.indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")?window.history&&"pushState"in window.history:!1}module.exports=supportsHistory},{}],34:[function(_dereq_,module){function withoutProperties(object,properties){var result={};for(var property in object)object.hasOwnProperty(property)&&!properties[property]&&(result[property]=object[property]);return result}module.exports=withoutProperties},{}],35:[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length))throw er=arguments[1],er instanceof Error?er:TypeError('Uncaught, unspecified "error" event.');if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],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(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],36:[function(_dereq_,module){module.exports.Dispatcher=_dereq_("./lib/Dispatcher")},{"./lib/Dispatcher":37}],37:[function(_dereq_,module){"use strict";function Dispatcher(){this.$Dispatcher_callbacks={},this.$Dispatcher_isPending={},this.$Dispatcher_isHandled={},this.$Dispatcher_isDispatching=!1,this.$Dispatcher_pendingPayload=null}var invariant=_dereq_("./invariant"),_lastID=1,_prefix="ID_";Dispatcher.prototype.register=function(callback){var id=_prefix+_lastID++;return this.$Dispatcher_callbacks[id]=callback,id},Dispatcher.prototype.unregister=function(id){invariant(this.$Dispatcher_callbacks[id],"Dispatcher.unregister(...): `%s` does not map to a registered callback.",id),delete this.$Dispatcher_callbacks[id]},Dispatcher.prototype.waitFor=function(ids){invariant(this.$Dispatcher_isDispatching,"Dispatcher.waitFor(...): Must be invoked while dispatching.");for(var ii=0;ii<ids.length;ii++){var id=ids[ii];this.$Dispatcher_isPending[id]?invariant(this.$Dispatcher_isHandled[id],"Dispatcher.waitFor(...): Circular dependency detected while waiting for `%s`.",id):(invariant(this.$Dispatcher_callbacks[id],"Dispatcher.waitFor(...): `%s` does not map to a registered callback.",id),this.$Dispatcher_invokeCallback(id))}},Dispatcher.prototype.dispatch=function(payload){invariant(!this.$Dispatcher_isDispatching,"Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch."),this.$Dispatcher_startDispatching(payload);try{for(var id in this.$Dispatcher_callbacks)this.$Dispatcher_isPending[id]||this.$Dispatcher_invokeCallback(id)}finally{this.$Dispatcher_stopDispatching()}},Dispatcher.prototype.isDispatching=function(){return this.$Dispatcher_isDispatching},Dispatcher.prototype.$Dispatcher_invokeCallback=function(id){this.$Dispatcher_isPending[id]=!0,this.$Dispatcher_callbacks[id](this.$Dispatcher_pendingPayload),this.$Dispatcher_isHandled[id]=!0},Dispatcher.prototype.$Dispatcher_startDispatching=function(payload){for(var id in this.$Dispatcher_callbacks)this.$Dispatcher_isPending[id]=!1,this.$Dispatcher_isHandled[id]=!1;this.$Dispatcher_pendingPayload=payload,this.$Dispatcher_isDispatching=!0},Dispatcher.prototype.$Dispatcher_stopDispatching=function(){this.$Dispatcher_pendingPayload=null,this.$Dispatcher_isDispatching=!1},module.exports=Dispatcher},{"./invariant":38}],38:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],39:[function(_dereq_,module){module.exports=_dereq_("./lib")},{"./lib":40}],40:[function(_dereq_,module){var Stringify=_dereq_("./stringify"),Parse=_dereq_("./parse");module.exports={stringify:Stringify,parse:Parse}},{"./parse":41,"./stringify":42}],41:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};internals.parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,1/0===options.parameterLimit?void 0:options.parameterLimit),i=0,il=parts.length;il>i;++i){var part=parts[i],pos=-1===part.indexOf("]=")?part.indexOf("="):part.indexOf("]=")+1;if(-1===pos)obj[Utils.decode(part)]="";else{var key=Utils.decode(part.slice(0,pos)),val=Utils.decode(part.slice(pos+1));obj[key]=obj[key]?[].concat(obj[key]).concat(val):val}}return obj},internals.parseObject=function(chain,val,options){if(!chain.length)return val;var root=chain.shift(),obj={};if("[]"===root)obj=[],obj=obj.concat(internals.parseObject(chain,val,options));else{var cleanRoot="["===root[0]&&"]"===root[root.length-1]?root.slice(1,root.length-1):root,index=parseInt(cleanRoot,10);!isNaN(index)&&root!==cleanRoot&&index<=options.arrayLimit?(obj=[],obj[index]=internals.parseObject(chain,val,options)):obj[cleanRoot]=internals.parseObject(chain,val,options)}return obj},internals.parseKeys=function(key,val,options){if(key){var parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key);if(!Object.prototype.hasOwnProperty(segment[1])){var keys=[];segment[1]&&keys.push(segment[1]);for(var i=0;null!==(segment=child.exec(key))&&i<options.depth;)++i,Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))||keys.push(segment[1]);return segment&&keys.push("["+key.slice(segment.index)+"]"),internals.parseObject(keys,val,options)}}},module.exports=function(str,options){if(""===str||null===str||"undefined"==typeof str)return{};options=options||{},options.delimiter="string"==typeof options.delimiter||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter,options.depth="number"==typeof options.depth?options.depth:internals.depth,options.arrayLimit="number"==typeof options.arrayLimit?options.arrayLimit:internals.arrayLimit,options.parameterLimit="number"==typeof options.parameterLimit?options.parameterLimit:internals.parameterLimit;for(var tempObj="string"==typeof str?internals.parseValues(str,options):str,obj={},keys=Object.keys(tempObj),i=0,il=keys.length;il>i;++i){var key=keys[i],newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj)}return Utils.compact(obj)}},{"./utils":43}],42:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&"};internals.stringify=function(obj,prefix){if(Utils.isBuffer(obj)?obj=obj.toString():obj instanceof Date?obj=obj.toISOString():null===obj&&(obj=""),"string"==typeof obj||"number"==typeof obj||"boolean"==typeof obj)return[encodeURIComponent(prefix)+"="+encodeURIComponent(obj)];var values=[];for(var key in obj)obj.hasOwnProperty(key)&&(values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]")));return values},module.exports=function(obj,options){options=options||{};var delimiter="undefined"==typeof options.delimiter?internals.delimiter:options.delimiter,keys=[];for(var key in obj)obj.hasOwnProperty(key)&&(keys=keys.concat(internals.stringify(obj[key],key)));return keys.join(delimiter)}},{"./utils":43}],43:[function(_dereq_,module,exports){exports.arrayToObject=function(source){for(var obj={},i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(obj[i]=source[i]);return obj},exports.merge=function(target,source){if(!source)return target;if(Array.isArray(source)){for(var i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(target[i]="object"==typeof target[i]?exports.merge(target[i],source[i]):source[i]);return target}if(Array.isArray(target)){if("object"!=typeof source)return target.push(source),target;target=exports.arrayToObject(target)}for(var keys=Object.keys(source),k=0,kl=keys.length;kl>k;++k){var key=keys[k],value=source[key];target[key]=value&&"object"==typeof value&&target[key]?exports.merge(target[key],value):value}return target},exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}},exports.compact=function(obj,refs){if("object"!=typeof obj||null===obj)return obj;refs=refs||[];var lookup=refs.indexOf(obj);if(-1!==lookup)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0,l=obj.length;l>i;++i)"undefined"!=typeof obj[i]&&compacted.push(obj[i]);return compacted}for(var keys=Object.keys(obj),i=0,il=keys.length;il>i;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj},exports.isRegExp=function(obj){return"[object RegExp]"===Object.prototype.toString.call(obj)},exports.isBuffer=function(obj){return"undefined"!=typeof Buffer?Buffer.isBuffer(obj):!1}},{}],44:[function(_dereq_,module){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen,isInWorker:!canUseDOM};module.exports=ExecutionEnvironment},{}],45:[function(_dereq_,module){function copyProperties(obj,a,b,c,d,e,f){obj=obj||{};for(var v,args=[a,b,c,d,e],ii=0;args[ii];){v=args[ii++];for(var k in v)obj[k]=v[k];v.hasOwnProperty&&v.hasOwnProperty("toString")&&"undefined"!=typeof v.toString&&obj.toString!==v.toString&&(obj.toString=v.toString)}return obj}module.exports=copyProperties},{}],46:[function(_dereq_,module){function makeEmptyFunction(arg){return function(){return arg}}function emptyFunction(){}var copyProperties=_dereq_("./copyProperties");copyProperties(emptyFunction,{thatReturns:makeEmptyFunction,thatReturnsFalse:makeEmptyFunction(!1),thatReturnsTrue:makeEmptyFunction(!0),thatReturnsNull:makeEmptyFunction(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(arg){return arg}}),module.exports=emptyFunction},{"./copyProperties":45}],47:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],48:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=function(obj){var key,ret={};invariant(obj instanceof Object&&!Array.isArray(obj));for(key in obj)obj.hasOwnProperty(key)&&(ret[key]=key);return ret};module.exports=keyMirror},{"./invariant":47}],49:[function(_dereq_,module){"use strict";var mergeInto=_dereq_("./mergeInto"),merge=function(one,two){var result={};return mergeInto(result,one),mergeInto(result,two),result};module.exports=merge},{"./mergeInto":51}],50:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=_dereq_("./keyMirror"),MAX_MERGE_DEPTH=36,isTerminal=function(o){return"object"!=typeof o||null===o},mergeHelpers={MAX_MERGE_DEPTH:MAX_MERGE_DEPTH,isTerminal:isTerminal,normalizeMergeArg:function(arg){return void 0===arg||null===arg?{}:arg},checkMergeArrayArgs:function(one,two){invariant(Array.isArray(one)&&Array.isArray(two))},checkMergeObjectArgs:function(one,two){mergeHelpers.checkMergeObjectArg(one),mergeHelpers.checkMergeObjectArg(two)},checkMergeObjectArg:function(arg){invariant(!isTerminal(arg)&&!Array.isArray(arg))},checkMergeIntoObjectArg:function(arg){invariant(!(isTerminal(arg)&&"function"!=typeof arg||Array.isArray(arg)))},checkMergeLevel:function(level){invariant(MAX_MERGE_DEPTH>level)},checkArrayStrategy:function(strategy){invariant(void 0===strategy||strategy in mergeHelpers.ArrayStrategies)},ArrayStrategies:keyMirror({Clobber:!0,IndexByIndex:!0})};module.exports=mergeHelpers},{"./invariant":47,"./keyMirror":48}],51:[function(_dereq_,module){"use strict";function mergeInto(one,two){if(checkMergeIntoObjectArg(one),null!=two){checkMergeObjectArg(two);for(var key in two)two.hasOwnProperty(key)&&(one[key]=two[key])}}var mergeHelpers=_dereq_("./mergeHelpers"),checkMergeObjectArg=mergeHelpers.checkMergeObjectArg,checkMergeIntoObjectArg=mergeHelpers.checkMergeIntoObjectArg;module.exports=mergeInto},{"./mergeHelpers":50}],52:[function(_dereq_,module){"use strict";var mixInto=function(constructor,methodBag){var methodName;for(methodName in methodBag)methodBag.hasOwnProperty(methodName)&&(constructor.prototype[methodName]=methodBag[methodName])};module.exports=mixInto},{}],53:[function(_dereq_,module){"use strict";var emptyFunction=_dereq_("./emptyFunction"),warning=emptyFunction;module.exports=warning},{"./emptyFunction":46}],54:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var makePromise=_dereq_("./makePromise"),Scheduler=_dereq_("./Scheduler"),async=_dereq_("./async");return makePromise({scheduler:new Scheduler(async)})})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Scheduler":56,"./async":57,"./makePromise":58}],55:[function(_dereq_,module){!function(define){"use strict";define(function(){function Queue(capacityPow2){this.head=this.tail=this.length=0,this.buffer=new Array(1<<capacityPow2)}return Queue.prototype.push=function(x){return this.length===this.buffer.length&&this._ensureCapacity(2*this.length),this.buffer[this.tail]=x,this.tail=this.tail+1&this.buffer.length-1,++this.length,this.length},Queue.prototype.shift=function(){var x=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=this.head+1&this.buffer.length-1,--this.length,x},Queue.prototype._ensureCapacity=function(capacity){var len,head=this.head,buffer=this.buffer,newBuffer=new Array(capacity),i=0;if(0===head)for(len=this.length;len>i;++i)newBuffer[i]=buffer[i];else{for(capacity=buffer.length,len=this.tail;capacity>head;++i,++head)newBuffer[i]=buffer[head];for(head=0;len>head;++i,++head)newBuffer[i]=buffer[head]}this.buffer=newBuffer,this.head=0,this.tail=this.length},Queue})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}],56:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){function Scheduler(async){this._async=async,this._queue=new Queue(15),this._afterQueue=new Queue(5),this._running=!1;var self=this;this.drain=function(){self._drain()}}function runQueue(queue){for(;queue.length>0;)queue.shift().run()}var Queue=_dereq_("./Queue");return Scheduler.prototype.enqueue=function(task){this._add(this._queue,task)},Scheduler.prototype.afterQueue=function(task){this._add(this._afterQueue,task)},Scheduler.prototype._drain=function(){runQueue(this._queue),this._running=!1,runQueue(this._afterQueue)},Scheduler.prototype._add=function(queue,task){queue.push(task),this._running||(this._running=!0,this._async(this.drain))},Scheduler})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Queue":55}],57:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var nextTick,MutationObs;return nextTick="undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick?function(f){process.nextTick(f)}:(MutationObs="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)?function(document,MutationObserver){function run(){var f=scheduled;scheduled=void 0,f()}var scheduled,el=document.createElement("div"),o=new MutationObserver(run);return o.observe(el,{attributes:!0}),function(f){scheduled=f,el.setAttribute("class","x")}}(document,MutationObs):function(cjsRequire){var vertx;try{vertx=cjsRequire("vertx")}catch(ignore){}if(vertx){if("function"==typeof vertx.runOnLoop)return vertx.runOnLoop;if("function"==typeof vertx.runOnContext)return vertx.runOnContext}var capturedSetTimeout=setTimeout;return function(t){capturedSetTimeout(t,0)}}(_dereq_)})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{}],58:[function(_dereq_,module){!function(define){"use strict";define(function(){return function(environment){function Promise(resolver,handler){this._handler=resolver===Handler?handler:init(resolver)}function init(resolver){function promiseResolve(x){handler.resolve(x)}function promiseReject(reason){handler.reject(reason)}function promiseNotify(x){handler.notify(x)}var handler=new Pending;try{resolver(promiseResolve,promiseReject,promiseNotify)}catch(e){promiseReject(e)}return handler}function resolve(x){return isPromise(x)?x:new Promise(Handler,new Async(getHandler(x)))}function reject(x){return new Promise(Handler,new Async(new Rejected(x)))}function never(){return foreverPendingPromise}function defer(){return new Promise(Handler,new Pending)}function all(promises){function settleAt(i,x,resolver){this[i]=x,0===--pending&&resolver.become(new Fulfilled(this))}var i,h,x,s,resolver=new Pending,pending=promises.length>>>0,results=new Array(pending);for(i=0;i<promises.length;++i)if(x=promises[i],void 0!==x||i in promises)if(maybeThenable(x))if(h=getHandlerMaybeThenable(x),s=h.state(),0===s)h.fold(settleAt,i,results,resolver);else{if(!(s>0)){unreportRemaining(promises,i+1,h),resolver.become(h);break}results[i]=h.value,--pending}else results[i]=x,--pending;else--pending;return 0===pending&&resolver.become(new Fulfilled(results)),new Promise(Handler,resolver)}function unreportRemaining(promises,start,rejectedHandler){var i,h,x;for(i=start;i<promises.length;++i)x=promises[i],maybeThenable(x)&&(h=getHandlerMaybeThenable(x),h!==rejectedHandler&&h.visit(h,void 0,h._unreport))}function race(promises){if(Object(promises)===promises&&0===promises.length)return never();var i,x,h=new Pending;for(i=0;i<promises.length;++i)x=promises[i],void 0!==x&&i in promises&&getHandler(x).visit(h,h.resolve,h.reject);return new Promise(Handler,h)}function getHandler(x){return isPromise(x)?x._handler.join():maybeThenable(x)?getHandlerUntrusted(x):new Fulfilled(x)}function getHandlerMaybeThenable(x){return isPromise(x)?x._handler.join():getHandlerUntrusted(x)}function getHandlerUntrusted(x){try{var untrustedThen=x.then;return"function"==typeof untrustedThen?new Thenable(untrustedThen,x):new Fulfilled(x)}catch(e){return new Rejected(e)}}function Handler(){}function FailIfRejected(){}function Pending(receiver,inheritedContext){Promise.createContext(this,inheritedContext),this.consumers=void 0,this.receiver=receiver,this.handler=void 0,this.resolved=!1}function Async(handler){this.handler=handler}function Thenable(then,thenable){Pending.call(this),tasks.enqueue(new AssimilateTask(then,thenable,this))}function Fulfilled(x){Promise.createContext(this),this.value=x}function Rejected(x){Promise.createContext(this),this.id=++errorId,this.value=x,this.handled=!1,this.reported=!1,this._report()}function ReportTask(rejection,context){this.rejection=rejection,this.context=context}function UnreportTask(rejection){this.rejection=rejection}function cycle(){return new Rejected(new TypeError("Promise cycle"))}function ContinuationTask(continuation,handler){this.continuation=continuation,this.handler=handler}function ProgressTask(value,handler){this.handler=handler,this.value=value}function AssimilateTask(then,thenable,resolver){this._then=then,this.thenable=thenable,this.resolver=resolver}function tryAssimilate(then,thenable,resolve,reject,notify){try{then.call(thenable,resolve,reject,notify)}catch(e){reject(e)}}function isPromise(x){return x instanceof Promise}function maybeThenable(x){return("object"==typeof x||"function"==typeof x)&&null!==x}function runContinuation1(f,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject(f,h.value,receiver,next),void Promise.exitContext())}function runContinuation3(f,x,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject3(f,x,h.value,receiver,next),void Promise.exitContext())}function runNotify(f,x,h,receiver,next){return"function"!=typeof f?next.notify(x):(Promise.enterContext(h),tryCatchReturn(f,x,receiver,next),void Promise.exitContext())}function tryCatchReject(f,x,thisArg,next){try{next.become(getHandler(f.call(thisArg,x)))}catch(e){next.become(new Rejected(e))}}function tryCatchReject3(f,x,y,thisArg,next){try{f.call(thisArg,x,y,next)}catch(e){next.become(new Rejected(e))}}function tryCatchReturn(f,x,thisArg,next){try{next.notify(f.call(thisArg,x))}catch(e){next.notify(e)}}function inherit(Parent,Child){Child.prototype=objectCreate(Parent.prototype),Child.prototype.constructor=Child}function noop(){}var tasks=environment.scheduler,objectCreate=Object.create||function(proto){function Child(){}return Child.prototype=proto,new Child};Promise.resolve=resolve,Promise.reject=reject,Promise.never=never,Promise._defer=defer,Promise._handler=getHandler,Promise.prototype.then=function(onFulfilled,onRejected){var parent=this._handler,state=parent.join().state();if("function"!=typeof onFulfilled&&state>0||"function"!=typeof onRejected&&0>state)return new this.constructor(Handler,parent);var p=this._beget(),child=p._handler;return parent.chain(child,parent.receiver,onFulfilled,onRejected,arguments.length>2?arguments[2]:void 0),p},Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)},Promise.prototype._beget=function(){var parent=this._handler,child=new Pending(parent.receiver,parent.join().context);return new this.constructor(Handler,child)},Promise.all=all,Promise.race=race,Handler.prototype.when=Handler.prototype.become=Handler.prototype.notify=Handler.prototype.fail=Handler.prototype._unreport=Handler.prototype._report=noop,Handler.prototype._state=0,Handler.prototype.state=function(){return this._state},Handler.prototype.join=function(){for(var h=this;void 0!==h.handler;)h=h.handler;return h},Handler.prototype.chain=function(to,receiver,fulfilled,rejected,progress){this.when({resolver:to,receiver:receiver,fulfilled:fulfilled,rejected:rejected,progress:progress})},Handler.prototype.visit=function(receiver,fulfilled,rejected,progress){this.chain(failIfRejected,receiver,fulfilled,rejected,progress)},Handler.prototype.fold=function(f,z,c,to){this.visit(to,function(x){f.call(c,z,x,this)},to.reject,to.notify)},inherit(Handler,FailIfRejected),FailIfRejected.prototype.become=function(h){h.fail()};var failIfRejected=new FailIfRejected;inherit(Handler,Pending),Pending.prototype._state=0,Pending.prototype.resolve=function(x){this.become(getHandler(x))},Pending.prototype.reject=function(x){this.resolved||this.become(new Rejected(x))},Pending.prototype.join=function(){if(!this.resolved)return this;for(var h=this;void 0!==h.handler;)if(h=h.handler,h===this)return this.handler=cycle();return h},Pending.prototype.run=function(){var q=this.consumers,handler=this.join();this.consumers=void 0;for(var i=0;i<q.length;++i)handler.when(q[i])},Pending.prototype.become=function(handler){this.resolved||(this.resolved=!0,this.handler=handler,void 0!==this.consumers&&tasks.enqueue(this),void 0!==this.context&&handler._report(this.context))},Pending.prototype.when=function(continuation){this.resolved?tasks.enqueue(new ContinuationTask(continuation,this.handler)):void 0===this.consumers?this.consumers=[continuation]:this.consumers.push(continuation)},Pending.prototype.notify=function(x){this.resolved||tasks.enqueue(new ProgressTask(x,this))},Pending.prototype.fail=function(context){var c="undefined"==typeof context?this.context:context;this.resolved&&this.handler.join().fail(c)},Pending.prototype._report=function(context){this.resolved&&this.handler.join()._report(context)},Pending.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},inherit(Handler,Async),Async.prototype.when=function(continuation){tasks.enqueue(new ContinuationTask(continuation,this))},Async.prototype._report=function(context){this.join()._report(context)},Async.prototype._unreport=function(){this.join()._unreport()},inherit(Pending,Thenable),inherit(Handler,Fulfilled),Fulfilled.prototype._state=1,Fulfilled.prototype.fold=function(f,z,c,to){runContinuation3(f,z,this,c,to) },Fulfilled.prototype.when=function(cont){runContinuation1(cont.fulfilled,this,cont.receiver,cont.resolver)};var errorId=0;inherit(Handler,Rejected),Rejected.prototype._state=-1,Rejected.prototype.fold=function(f,z,c,to){to.become(this)},Rejected.prototype.when=function(cont){"function"==typeof cont.rejected&&this._unreport(),runContinuation1(cont.rejected,this,cont.receiver,cont.resolver)},Rejected.prototype._report=function(context){tasks.afterQueue(new ReportTask(this,context))},Rejected.prototype._unreport=function(){this.handled=!0,tasks.afterQueue(new UnreportTask(this))},Rejected.prototype.fail=function(context){Promise.onFatalRejection(this,void 0===context?this.context:context)},ReportTask.prototype.run=function(){this.rejection.handled||(this.rejection.reported=!0,Promise.onPotentiallyUnhandledRejection(this.rejection,this.context))},UnreportTask.prototype.run=function(){this.rejection.reported&&Promise.onPotentiallyUnhandledRejectionHandled(this.rejection)},Promise.createContext=Promise.enterContext=Promise.exitContext=Promise.onPotentiallyUnhandledRejection=Promise.onPotentiallyUnhandledRejectionHandled=Promise.onFatalRejection=noop;var foreverPendingHandler=new Handler,foreverPendingPromise=new Promise(Handler,foreverPendingHandler);return ContinuationTask.prototype.run=function(){this.handler.join().when(this.continuation)},ProgressTask.prototype.run=function(){var q=this.handler.consumers;if(void 0!==q)for(var c,i=0;i<q.length;++i)c=q[i],runNotify(c.progress,this.value,this.handler,c.receiver,c.resolver)},AssimilateTask.prototype.run=function(){function _resolve(x){h.resolve(x)}function _reject(x){h.reject(x)}function _notify(x){h.notify(x)}var h=this.resolver;tryAssimilate(this._then,this.thenable,_resolve,_reject,_notify)},Promise}})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}]},{},[9])(9)});
test/integration/css/fixtures/url-global/pages/_app.js
BlancheXu/test
import React from 'react' import App from 'next/app' import '../styles/global1.css' import '../styles/global2.css' class MyApp extends App { render () { const { Component, pageProps } = this.props return <Component {...pageProps} /> } } export default MyApp
src/js/components/ui/reduxForm/DropdownSelect.js
knowncitizen/tripleo-ui
/** * Copyright 2017 Red Hat Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ import { DropdownButton } from 'react-bootstrap'; import PropTypes from 'prop-types'; import React from 'react'; const DropdownSelect = props => { const { children, input: { name, onChange, value } } = props; return ( <DropdownButton id={name} title={value} onSelect={(evKey, ev) => onChange(evKey)} > {children} </DropdownButton> ); }; DropdownSelect.propTypes = { children: PropTypes.node, input: PropTypes.object.isRequired }; export default DropdownSelect;
src/js/main.js
TheFixers/node-honeypot-client
import App from './components/app' import React from 'react' import ReactDOM from 'react-dom' ReactDOM.render(<App />, document.getElementById('app'))
ajax/libs/ui-router-extras/0.0.10/ct-ui-router-extras.min.js
joeyparrish/cdnjs
/*! ui-router-extras - v0.0.10 - 2014-08-27 */!function(window,angular,undefined){function ancestors(first,second){var path=[];for(var n in first.path){if(first.path[n]!==second.path[n])break;path.push(first.path[n])}return path}function objectKeys(object){if(Object.keys)return Object.keys(object);var result=[];return angular.forEach(object,function(val,key){result.push(key)}),result}function arraySearch(array,value){if(Array.prototype.indexOf)return array.indexOf(value,Number(arguments[2])||0);var len=array.length>>>0,from=Number(arguments[2])||0;for(from=0>from?Math.ceil(from):Math.floor(from),0>from&&(from+=len);len>from;from++)if(from in array&&array[from]===value)return from;return-1}function inheritParams(currentParams,newParams,$current,$to){var parentParams,parents=ancestors($current,$to),inherited={},inheritList=[];for(var i in parents)if(parents[i].params&&(parentParams=isArray(parents[i].params)?parents[i].params:objectKeys(parents[i].params),parentParams.length))for(var j in parentParams)arraySearch(inheritList,parentParams[j])>=0||(inheritList.push(parentParams[j]),inherited[parentParams[j]]=currentParams[parentParams[j]]);return extend({},inherited,newParams)}function inherit(parent,extra){return extend(new(extend(function(){},{prototype:parent})),extra)}function resetIgnoreDsr(){ignoreDsr=undefined}function $StickyStateProvider(){var inactiveStates={},stickyStates={};this.registerStickyState=function(state){stickyStates[state.name]=state},this.enableDebug=function(enabled){DEBUG=enabled},this.$get=["$rootScope","$state","$stateParams","$injector","$log",function($rootScope,$state,$stateParams,$injector,$log){function mapInactives(){var mappedStates={};return angular.forEach(inactiveStates,function(state){for(var stickyAncestors=getStickyStateStack(state),i=0;i<stickyAncestors.length;i++){var parent=stickyAncestors[i].parent;mappedStates[parent.name]=mappedStates[parent.name]||[],mappedStates[parent.name].push(state)}mappedStates[""]&&(mappedStates.__inactives=mappedStates[""])}),mappedStates}function getStickyStateStack(state){var stack=[];if(!state)return stack;do state.sticky&&stack.push(state),state=state.parent;while(state);return stack.reverse(),stack}function getStickyTransitionType(fromPath,toPath,keep){if(fromPath[keep]===toPath[keep])return{from:!1,to:!1};var stickyFromState=keep<fromPath.length&&fromPath[keep].self.sticky,stickyToState=keep<toPath.length&&toPath[keep].self.sticky;return{from:stickyFromState,to:stickyToState}}function getEnterTransition(state,stateParams,ancestorParamsChanged){if(ancestorParamsChanged)return"updateStateParams";var inactiveState=inactiveStates[state.self.name];if(!inactiveState)return"enter";var paramsMatch=equalForKeys(stateParams,inactiveState.locals.globals.$stateParams,state.ownParams);return paramsMatch?"reactivate":"updateStateParams"}function getInactivatedState(state,stateParams){var inactiveState=inactiveStates[state.name];if(!inactiveState)return null;if(!stateParams)return inactiveState;var paramsMatch=equalForKeys(stateParams,inactiveState.locals.globals.$stateParams,state.ownParams);return paramsMatch?inactiveState:null}function equalForKeys(a,b,keys){if(!keys){keys=[];for(var n in a)keys.push(n)}for(var i=0;i<keys.length;i++){var k=keys[i];if(a[k]!=b[k])return!1}return!0}var stickySupport={getInactiveStates:function(){var states=[];return angular.forEach(inactiveStates,function(state){states.push(state)}),states},getInactiveStatesByParent:function(){return mapInactives()},processTransition:function(transition){var result={inactives:[],enter:[],exit:[],keep:0},fromPath=transition.fromState.path,fromParams=transition.fromParams,toPath=transition.toState.path,toParams=transition.toParams,options=transition.options,keep=0,state=toPath[keep];for(options.inherit&&(toParams=inheritParams($stateParams,toParams||{},$state.$current,transition.toState));state&&state===fromPath[keep]&&equalForKeys(toParams,fromParams,state.ownParams);)state=toPath[++keep];result.keep=keep;var idx,deepestUpdatedParams,deepestReactivate,reactivatedStatesByName={},pType=getStickyTransitionType(fromPath,toPath,keep),ancestorUpdated=!1;for(idx=keep;idx<toPath.length;idx++){var enterTrans=pType.to?getEnterTransition(toPath[idx],transition.toParams,ancestorUpdated):"enter";ancestorUpdated=ancestorUpdated||"updateStateParams"==enterTrans,result.enter[idx]=enterTrans,"reactivate"==enterTrans&&(deepestReactivate=reactivatedStatesByName[toPath[idx].name]=toPath[idx]),"updateStateParams"==enterTrans&&(deepestUpdatedParams=toPath[idx])}deepestReactivate=deepestReactivate?deepestReactivate.self.name+".":"",deepestUpdatedParams=deepestUpdatedParams?deepestUpdatedParams.self.name+".":"";var inactivesByParent=mapInactives(),keptStateNames=[""].concat(map(fromPath.slice(0,keep),function(state){return state.self.name}));for(angular.forEach(keptStateNames,function(name){for(var inactiveChildren=inactivesByParent[name],i=0;inactiveChildren&&i<inactiveChildren.length;i++){var child=inactiveChildren[i];reactivatedStatesByName[child.name]||deepestReactivate&&0===child.self.name.indexOf(deepestReactivate)||deepestUpdatedParams&&0===child.self.name.indexOf(deepestUpdatedParams)||result.inactives.push(child)}}),idx=keep;idx<fromPath.length;idx++){var exitTrans="exit";pType.from&&(result.inactives.push(fromPath[idx]),exitTrans="inactivate"),result.exit[idx]=exitTrans}return result},stateInactivated:function(state){inactiveStates[state.self.name]=state,state.self.status="inactive",state.self.onInactivate&&$injector.invoke(state.self.onInactivate,state.self,state.locals.globals)},stateReactivated:function(state){inactiveStates[state.self.name]&&delete inactiveStates[state.self.name],state.self.status="entered",state.self.onReactivate&&$injector.invoke(state.self.onReactivate,state.self,state.locals.globals)},stateExiting:function(exiting,exitQueue,onExit){var exitingNames={};angular.forEach(exitQueue,function(state){exitingNames[state.self.name]=!0}),angular.forEach(inactiveStates,function(inactiveExiting,name){!exitingNames[name]&&inactiveExiting.includes[exiting.name]&&(DEBUG&&$log.debug("Exiting "+name+" because it's a substate of "+exiting.name+" and wasn't found in ",exitingNames),inactiveExiting.self.onExit&&$injector.invoke(inactiveExiting.self.onExit,inactiveExiting.self,inactiveExiting.locals.globals),inactiveExiting.locals=null,inactiveExiting.self.status="exited",delete inactiveStates[name])}),onExit&&$injector.invoke(onExit,exiting.self,exiting.locals.globals),exiting.locals=null,exiting.self.status="exited",delete inactiveStates[exiting.self.name]},stateEntering:function(entering,params,onEnter){var inactivatedState=getInactivatedState(entering);if(inactivatedState&&!getInactivatedState(entering,params)){var savedLocals=entering.locals;this.stateExiting(inactivatedState),entering.locals=savedLocals}entering.self.status="entered",onEnter&&$injector.invoke(onEnter,entering.self,entering.locals.globals)}};return stickySupport}]}function SurrogateState(type){return{resolve:{},locals:{globals:root&&root.locals&&root.locals.globals},views:{},self:{},params:{},ownParams:[],surrogateType:type}}function debugTransition($log,currentTransition,stickyTransition){function message(path,index,state){return path[index]?path[index].toUpperCase()+": "+state.self.name:"("+state.self.name+")"}var inactiveLogVar=map(stickyTransition.inactives,function(state){return state.self.name}),enterLogVar=map(currentTransition.toState.path,function(state,index){return message(stickyTransition.enter,index,state)}),exitLogVar=map(currentTransition.fromState.path,function(state,index){return message(stickyTransition.exit,index,state)}),transitionMessage=currentTransition.fromState.self.name+": "+angular.toJson(currentTransition.fromParams)+": -> "+currentTransition.toState.self.name+": "+angular.toJson(currentTransition.toParams);$log.debug(" Current transition: ",transitionMessage),$log.debug("Before transition, inactives are: : ",map(_StickyState.getInactiveStates(),function(s){return s.self.name})),$log.debug("After transition, inactives will be: ",inactiveLogVar),$log.debug("Transition will exit: ",exitLogVar),$log.debug("Transition will enter: ",enterLogVar)}function debugViewsAfterSuccess($log,currentState,$state){$log.debug("Current state: "+currentState.self.name+", inactive states: ",map(_StickyState.getInactiveStates(),function(s){return s.self.name}));for(var viewMsg=function(local,name){return"'"+name+"' ("+local.$$state.name+")"},statesOnly=function(local,name){return"globals"!=name&&"resolve"!=name},viewsForState=function(state){var views=map(filterObj(state.locals,statesOnly),viewMsg).join(", ");return"("+(state.self.name?state.self.name:"root")+".locals"+(views.length?": "+views:"")+")"},message=viewsForState(currentState),parent=currentState.parent;parent&&parent!==currentState;)""===parent.self.name&&(message=viewsForState($state.$current.path[0])+" / "+message),message=viewsForState(parent)+" / "+message,currentState=parent,parent=currentState.parent;$log.debug("Views: "+message)}angular.module("ct.ui.router.extras",["ui.router"]);var ignoreDsr,DEBUG=!1,forEach=angular.forEach,extend=angular.extend,isArray=angular.isArray,map=function(collection,callback){"use strict";var result=[];return forEach(collection,function(item,index){result.push(callback(item,index))}),result},filterObj=function(collection,callback){"use strict";var result={};return forEach(collection,function(item,index){callback(item,index)&&(result[index]=item)}),result};angular.module("ct.ui.router.extras").config(["$provide",function($provide){var $state_transitionTo;$provide.decorator("$state",["$delegate","$q",function($state,$q){return $state_transitionTo=$state.transitionTo,$state.transitionTo=function(to,toParams,options){return options.ignoreDsr&&(ignoreDsr=options.ignoreDsr),$state_transitionTo.apply($state,arguments).then(function(result){return resetIgnoreDsr(),result},function(err){return resetIgnoreDsr(),$q.reject(err)})},$state}])}]),angular.module("ct.ui.router.extras").service("$deepStateRedirect",["$rootScope","$state","$injector",function($rootScope,$state,$injector){function computeDeepStateStatus(state){var name=state.name;return deepStateRedirectsByName.hasOwnProperty(name)?deepStateRedirectsByName[name]:void recordDeepStateRedirectStatus(name)}function recordDeepStateRedirectStatus(stateName){var state=$state.get(stateName);state&&state.deepStateRedirect&&(deepStateRedirectsByName[stateName]=REDIRECT,lastSubstate[stateName]===undefined&&(lastSubstate[stateName]=stateName));var lastDot=stateName.lastIndexOf(".");if(-1!=lastDot){var parentStatus=recordDeepStateRedirectStatus(stateName.substr(0,lastDot));parentStatus&&deepStateRedirectsByName[stateName]===undefined&&(deepStateRedirectsByName[stateName]=ANCESTOR_REDIRECT)}return deepStateRedirectsByName[stateName]||!1}var lastSubstate={},lastParams={},deepStateRedirectsByName={},REDIRECT="Redirect",ANCESTOR_REDIRECT="AncestorRedirect";return $rootScope.$on("$stateChangeStart",function(event,toState){function shouldRedirect(){if(ignoreDsr)return!1;var deepStateStatus=computeDeepStateStatus(toState),substate=lastSubstate[toState.name],isDSR=deepStateStatus===REDIRECT&&substate&&substate!=toState.name?!0:!1;return isDSR&&angular.isFunction(toState.deepStateRedirect)?$injector.invoke(toState.deepStateRedirect,toState):isDSR}shouldRedirect()&&(event.preventDefault(),$state.go(lastSubstate[toState.name],lastParams[toState.name]))}),$rootScope.$on("$stateChangeSuccess",function(event,toState,toParams){var deepStateStatus=computeDeepStateStatus(toState);if(deepStateStatus){var name=toState.name;angular.forEach(lastSubstate,function(deepState,redirectState){(name==redirectState||-1!=name.indexOf(redirectState+"."))&&(lastSubstate[redirectState]=name,lastParams[redirectState]=angular.copy(toParams))})}}),{}}]),angular.module("ct.ui.router.extras").run(["$deepStateRedirect",function(){}]),$StickyStateProvider.$inject=["$stateProvider"],angular.module("ct.ui.router.extras").provider("$stickyState",$StickyStateProvider);var _StickyState,root,pendingRestore,inactivePseudoState,internalStates={},pendingTransitions=[];angular.module("ct.ui.router.extras").run(["$stickyState",function($stickyState){_StickyState=$stickyState}]),angular.module("ct.ui.router.extras").config(["$provide","$stateProvider","$stickyStateProvider",function($provide,$stateProvider,$stickyStateProvider){inactivePseudoState=angular.extend(new SurrogateState("__inactives"),{self:{name:"__inactives"}}),root=pendingRestore=undefined,pendingTransitions=[],$stateProvider.decorator("parent",function(state,parentFn){return internalStates[state.self.name]=state,state.self.$$state=function(){return internalStates[state.self.name]},state.self.sticky===!0&&$stickyStateProvider.registerStickyState(state.self),parentFn(state)});var $state_transitionTo;$provide.decorator("$state",["$delegate","$log","$q",function($state,$log,$q){return root=$state.$current,root.parent=inactivePseudoState,inactivePseudoState.parent=undefined,root.locals=inherit(inactivePseudoState.locals,root.locals),delete inactivePseudoState.locals.globals,$state_transitionTo=$state.transitionTo,$state.transitionTo=function(to,toParams,options){function stateReactivatedSurrogatePhase1(state){var surrogate=angular.extend(new SurrogateState("reactivate_phase1"),{locals:state.locals});return surrogate.self=angular.extend({},state.self),surrogate}function stateReactivatedSurrogatePhase2(state){var surrogate=angular.extend(new SurrogateState("reactivate_phase2"),state),oldOnEnter=surrogate.self.onEnter;return surrogate.resolve={},surrogate.views={},surrogate.self.onEnter=function(){surrogate.locals=state.locals,_StickyState.stateReactivated(state)},restore.addRestoreFunction(function(){state.self.onEnter=oldOnEnter}),surrogate}function stateInactivatedSurrogate(state){var surrogate=new SurrogateState("inactivate");surrogate.self=state.self;var oldOnExit=state.self.onExit;return surrogate.self.onExit=function(){_StickyState.stateInactivated(state)},restore.addRestoreFunction(function(){state.self.onExit=oldOnExit}),surrogate}function stateEnteredSurrogate(state,toParams){var oldOnEnter=state.self.onEnter;return state.self.onEnter=function(){_StickyState.stateEntering(state,toParams,oldOnEnter)},restore.addRestoreFunction(function(){state.self.onEnter=oldOnEnter}),state}function stateExitedSurrogate(state){var oldOnExit=state.self.onExit;return state.self.onExit=function(){_StickyState.stateExiting(state,exited,oldOnExit)},restore.addRestoreFunction(function(){state.self.onExit=oldOnExit}),state}inactivePseudoState.locals||(inactivePseudoState.locals=root.locals);var idx=pendingTransitions.length;pendingRestore&&(pendingRestore(),DEBUG&&$log.debug("Restored paths from pending transition"));var savedToStatePath,savedFromStatePath,stickyTransitions,terminalReactivatedState,fromState=$state.$current,fromParams=$state.params,rel=options&&options.relative||$state.$current,toStateSelf=$state.get(to,rel),reactivated=[],exited=[],noop=function(){},restore=function(){savedToStatePath&&(toState.path=savedToStatePath,savedToStatePath=null),savedFromStatePath&&(fromState.path=savedFromStatePath,savedFromStatePath=null),angular.forEach(restore.restoreFunctions,function(restoreFunction){restoreFunction()}),restore=noop,pendingRestore=null,pendingTransitions.splice(idx,1)};if(restore.restoreFunctions=[],restore.addRestoreFunction=function(fn){this.restoreFunctions.push(fn)},toStateSelf){var toState=internalStates[toStateSelf.name];if(toState){savedToStatePath=toState.path,savedFromStatePath=fromState.path;var currentTransition={toState:toState,toParams:toParams||{},fromState:fromState,fromParams:fromParams||{},options:options};pendingTransitions.push(currentTransition),pendingRestore=restore,stickyTransitions=_StickyState.processTransition(currentTransition),DEBUG&&debugTransition($log,currentTransition,stickyTransitions);var surrogateToPath=toState.path.slice(0,stickyTransitions.keep),surrogateFromPath=fromState.path.slice(0,stickyTransitions.keep);angular.forEach(inactivePseudoState.locals,function(local,name){-1!=name.indexOf("@")&&delete inactivePseudoState.locals[name]});for(var i=0;i<stickyTransitions.inactives.length;i++){var iLocals=stickyTransitions.inactives[i].locals;angular.forEach(iLocals,function(view,name){iLocals.hasOwnProperty(name)&&-1!=name.indexOf("@")&&(inactivePseudoState.locals[name]=view)})}if(angular.forEach(stickyTransitions.enter,function(value,idx){var surrogate;"reactivate"===value?(surrogate=stateReactivatedSurrogatePhase1(toState.path[idx]),surrogateToPath.push(surrogate),surrogateFromPath.push(surrogate),reactivated.push(stateReactivatedSurrogatePhase2(toState.path[idx])),terminalReactivatedState=surrogate):"updateStateParams"===value?(surrogate=stateEnteredSurrogate(toState.path[idx]),surrogateToPath.push(surrogate),terminalReactivatedState=surrogate):"enter"===value&&surrogateToPath.push(stateEnteredSurrogate(toState.path[idx]))}),angular.forEach(stickyTransitions.exit,function(value,idx){var exiting=fromState.path[idx];"inactivate"===value?(surrogateFromPath.push(stateInactivatedSurrogate(exiting)),exited.push(exiting)):"exit"===value&&(surrogateFromPath.push(stateExitedSurrogate(exiting)),exited.push(exiting))}),reactivated.length&&angular.forEach(reactivated,function(surrogate){surrogateToPath.push(surrogate)}),terminalReactivatedState){var prefix=terminalReactivatedState.self.name+".",inactiveStates=_StickyState.getInactiveStates(),inactiveOrphans=[];inactiveStates.forEach(function(exiting){0===exiting.self.name.indexOf(prefix)&&inactiveOrphans.push(exiting)}),inactiveOrphans.sort(),inactiveOrphans.reverse(),surrogateFromPath=surrogateFromPath.concat(map(inactiveOrphans,function(exiting){return stateExitedSurrogate(exiting)})),exited=exited.concat(inactiveOrphans)}toState.path=surrogateToPath,fromState.path=surrogateFromPath;var pathMessage=function(state){return(state.surrogateType?state.surrogateType+":":"")+state.self.name};DEBUG&&$log.debug("SurrogateFromPath: ",map(surrogateFromPath,pathMessage)),DEBUG&&$log.debug("SurrogateToPath: ",map(surrogateToPath,pathMessage))}}var transitionPromise=$state_transitionTo.apply($state,arguments);return transitionPromise.then(function(state){return restore(),DEBUG&&debugViewsAfterSuccess($log,internalStates[state.name],$state),state.status="active",state},function(err){return restore(),DEBUG&&"transition prevented"!==err.message&&"transition aborted"!==err.message&&"transition superseded"!==err.message&&($log.debug("transition failed",err),console.log(err.stack)),$q.reject(err)})},$state}])}]),angular.module("ct.ui.router.extras").provider("$futureState",["$stateProvider","$urlRouterProvider",function($stateProvider,$urlRouterProvider){function findFutureState($state,options){if(options.name)for(var nameComponents=options.name.split(/\./);nameComponents.length;){var stateName=nameComponents.join(".");if($state.get(stateName))return null;if(futureStates[stateName])return futureStates[stateName];nameComponents.pop()}if(options.url)for(var urlComponents=options.url.split(/\//);urlComponents.length;){var urlPrefix=urlComponents.join("/");if(futureUrlPrefixes[urlPrefix])return futureUrlPrefixes[urlPrefix];urlComponents.pop()}}function lazyLoadState($injector,futureState){if(!futureState){var deferred=$q.defer();return deferred.reject("No lazyState passed in "+futureState),deferred.promise}var type=futureState.type,factory=stateFactories[type];if(!factory)throw Error("No state factory for futureState.type: "+(futureState&&futureState.type));return $injector.invoke(factory,factory,{futureState:futureState})}function futureState_otherwise($injector,$location){var resyncing=!1,$log=$injector.get("$log"),otherwiseFunc=["$state",function(){$log.debug("Unable to map "+$location.path()),$location.url("/")}],lazyLoadMissingState=["$rootScope","$urlRouter","$state",function($rootScope,$urlRouter,$state){if(!initDone)return initPromise().then(function(){resyncing=!0,$urlRouter.sync(),resyncing=!1}),void(initDone=!0);var futureState=findFutureState($state,{url:$location.path()});return futureState?(transitionPending=!0,void lazyLoadState($injector,futureState).then(function(state){state&&!$state.get(state)&&$stateProvider.state(state),resyncing=!0,$urlRouter.sync(),resyncing=!1,transitionPending=!1},function(){transitionPending=!1,$state.go("top")})):$injector.invoke(otherwiseFunc)}];if(!transitionPending){var nextFn=resyncing?otherwiseFunc:lazyLoadMissingState;return $injector.invoke(nextFn)}}var initPromise,stateFactories={},futureStates={},futureUrlPrefixes={},transitionPending=!1,resolveFunctions=[],initDone=!1,provider=this;this.addResolve=function(promiseFn){resolveFunctions.push(promiseFn)},this.stateFactory=function(futureStateType,factory){stateFactories[futureStateType]=factory},this.futureState=function(futureState){futureStates[futureState.stateName]=futureState,futureUrlPrefixes[futureState.urlPrefix]=futureState},this.get=function(){return angular.extend({},futureStates)},$urlRouterProvider.otherwise(futureState_otherwise);var serviceObject={getResolvePromise:function(){return initPromise()}};this.$get=["$injector","$state","$q","$rootScope","$urlRouter","$timeout","$log",function($injector,$state,$q,$rootScope,$urlRouter,$timeout,$log){function init(){if($rootScope.$on("$stateNotFound",function(event,unfoundState,fromState,fromParams){if(!transitionPending){$log.debug("event, unfoundState, fromState, fromParams",event,unfoundState,fromState,fromParams);var futureState=findFutureState($state,{name:unfoundState.to});if(futureState){event.preventDefault(),transitionPending=!0;var promise=lazyLoadState($injector,futureState);promise.then(function(state){state&&$stateProvider.state(state),$state.go(unfoundState.to,unfoundState.toParams),transitionPending=!1},function(error){console.log("failed to lazy load state ",error),$state.go(fromState,fromParams),transitionPending=!1})}}}),!initPromise){var promises=[];angular.forEach(resolveFunctions,function(promiseFn){promises.push($injector.invoke(promiseFn))}),initPromise=function(){return $q.all(promises)}}initPromise().then(function(){$timeout(function(){$state.transition?$state.transition.then($urlRouter.sync,$urlRouter.sync):$urlRouter.sync()})})}return init(),serviceObject.state=$stateProvider.state,serviceObject.futureState=provider.futureState,serviceObject.get=provider.get,serviceObject}]}]),angular.module("ct.ui.router.extras").run(["$futureState",function(){}]),angular.module("ct.ui.router.extras").service("$previousState",["$rootScope","$state",function($rootScope,$state){var previous=null,memos={},lastPrevious=null;$rootScope.$on("$stateChangeStart",function(evt,toState,toStateParams,fromState,fromStateParams){lastPrevious=previous,previous={state:fromState,params:fromStateParams}}),$rootScope.$on("$stateChangeError",function(){previous=lastPrevious,lastPrevious=null}),$rootScope.$on("$stateChangeSuccess",function(){lastPrevious=null});var $previousState={get:function(memoName){return memoName?memos[memoName]:previous},go:function(memoName,options){var to=$previousState.get(memoName);return $state.go(to.state,to.params,options)},memo:function(memoName){memos[memoName]=previous},forget:function(memoName){delete memos[memoName]}};return $previousState}]),angular.module("ct.ui.router.extras").run(["$previousState",function(){}]),angular.module("ct.ui.router.extras").config(["$provide",function($provide){$provide.decorator("$state",["$delegate","$rootScope","$q","$injector",function($state,$rootScope,$q,$injector){function decorateInjector(tData){var oldinvoke=$injector.invoke,oldinstantiate=$injector.instantiate;return $injector.invoke=function(fn,self,locals){return oldinvoke(fn,self,angular.extend({$transition$:tData},locals))},$injector.instantiate=function(fn,locals){return oldinstantiate(fn,angular.extend({$transition$:tData},locals))},function(){$injector.invoke=oldinvoke,$injector.instantiate=oldinstantiate}}function popStack(){restoreFnStack.pop()(),tDataStack.pop(),transitionDepth--}function transitionSuccess(deferred,tSuccess){return function(data){return popStack(),$rootScope.$broadcast("$transitionSuccess",tSuccess),deferred.resolve(data)}}function transitionFailure(deferred,tFail){return function(error){return popStack(),$rootScope.$broadcast("$transitionError",tFail,error),deferred.reject(error)}}var $state_transitionTo=$state.transitionTo,transitionDepth=-1,tDataStack=[],restoreFnStack=[];return $state.transitionTo=function(){var deferred=$q.defer(),tData=tDataStack[++transitionDepth]={promise:deferred.promise};restoreFnStack[transitionDepth]=function(){};var tPromise=$state_transitionTo.apply($state,arguments);return tPromise.then(transitionSuccess(deferred,tData),transitionFailure(deferred,tData))},$rootScope.$on("$stateChangeStart",function(evt,toState,toParams,fromState,fromParams){var depth=transitionDepth,tData=angular.extend(tDataStack[depth],{to:{state:toState,params:toParams},from:{state:fromState,params:fromParams}}),restoreFn=decorateInjector(tData);restoreFnStack[depth]=restoreFn,$rootScope.$broadcast("$transitionStart",tData)}),$state}])}])}(window,window.angular);
modules/IndexLink.js
yongxu/react-router
import React from 'react'; import { component } from './PropTypes'; import Link from './Link'; var IndexLink = React.createClass({ render() { return <Link {...this.props} onlyActiveOnIndex={true} /> } }); export default IndexLink;
packages/material-ui-icons/src/LocalShippingSharp.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M20 8h-3V4H1v13h2c0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h2v-5l-3-4zM6 18c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm13.5-8.5l1.96 2.5H17V9.5h2.5zM18 18c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /> , 'LocalShippingSharp');
src/front/app/features/auth/components/LoginButton.integration.spec.js
travel-and-help/start-kit
import React from 'react'; import { mount } from 'enzyme'; import LoginButton from './LoginButton'; describe('auth LoginButton', () => { let text, onClick, wrapper; beforeEach(() => { onClick = env.stub(); text = 'test Button Text'; wrapper = mount(<LoginButton text={text} onClick={ onClick } />); }); it('should render with text', () => { wrapper.find('.login-button').text().should.equal(`Continue with ${text}`); }); it('should trigger onClick method on category tile click', () => { const categoryTile = wrapper.find('.login-button').at(0); categoryTile.simulate('click'); onClick.should.callCount(1); }); });
app/containers/EntitiesList/index.js
chenhunghan/deleuzian-affection-image
/* * * EntitiesList * */ import React from 'react'; import { connect } from 'react-redux'; import { selectEntitiesList, selectCluster } from './selectors'; import styles from './styles.css'; import {changeHighlightEntity} from './actions' import {GET_EMOTION_REQUESTED} from '../EntitiesList/constants' import flatten from 'lodash/flatten'; import { createStructuredSelector } from 'reselect'; export const entitiesListData = [ { title: 'Battleship Potemkin', description: 'from the anger of the sailors to the revolutionary explosion; from the stone to the scream, as in the three postures of the marble lions ("and the stones have roared").', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118673cd4f02cb01_d20160704_m202838_c001_v0001029_t0025', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1115bb953866eaad_d20160704_m202849_c001_v0001029_t0018', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1108b907e93c43d1_d20160704_m202852_c001_v0001030_t0007', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1055a0b231fcffa4_d20160704_m202853_c001_v0001029_t0004', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f109b073ca91b843c_d20160704_m202855_c001_v0001030_t0035', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f10797dbc64d92ac1_d20160704_m202856_c001_v0001031_t0034', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f105da5286416ebea_d20160704_m202857_c001_v0001013_t0015', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1030aee800c025b4_d20160704_m202900_c001_v0001029_t0006', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118673cd4f02cb08_d20160704_m202901_c001_v0001029_t0034', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1055a0b231fcffc5_d20160704_m202914_c001_v0001029_t0008', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f100f49c35233bb00_d20160704_m202917_c001_v0001029_t0024', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118fc238428a9824_d20160704_m202920_c001_v0001018_t0035', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1159389410dfff9c_d20160704_m202927_c001_v0001030_t0020', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f114ee236b5951910_d20160704_m202928_c001_v0001029_t0030', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f117bc3c0d272eff7_d20160704_m202932_c001_v0001029_t0029', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f10387fb146b4c4c3_d20160704_m202936_c001_v0001009_t0019', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f114ee236b5951918_d20160704_m202937_c001_v0001029_t0020', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f109ffc049529a2fc_d20160704_m202940_c001_v0001031_t0037', ] }, { title: 'Broken Blossoms', description: 'The martyred girl nevertheless retains a petrified face, which, even in death still seems to reflect and ask why, whilst the Chinese lover, for his part, preserves on his face the stupor of opium and the reflection of Buddha. ', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f115c8f676cd80fbc_d20160704_m203018_c001_v0001029_t0015', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f119c74f63ad9b045_d20160704_m203021_c001_v0001022_t0044', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f10295809a65b05f2_d20160704_m203025_c001_v0001029_t0031' ] }, { title: 'Enoch Arden', description: 'A young woman thinks about her husband; young woman is thinking about her husband because we see the image of the husband immediately afterwards.', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106a62105d475410_d20160704_m203118_c001_v0001029_t0034', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f115c8f676cd80feb_d20160704_m203120_c001_v0001029_t0007', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118673cd4f02cb2d_d20160704_m203122_c001_v0001029_t0013', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1108b907e93c4415_d20160704_m203135_c001_v0001030_t0030', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f119685cb2dc5d7ed_d20160704_m203136_c001_v0001031_t0004', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f119c74f63ad9b047_d20160704_m203138_c001_v0001022_t0043' ] }, { title: 'Foolish Wives', description: 'The seducer hero moves from the maidservant to the society lady, to finish up with the sickly invalid, driven by the elemental force of a predatory impulse, which leads him to explore all milieux and to tear away what each one offers.', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f108f0f36ddbcbeaf_d20160705_m074045_c001_v0001029_t0008', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1114073772aedd8a_d20160705_m074052_c001_v0001013_t0041', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1141fcd145408dca_d20160705_m074054_c001_v0001031_t0005', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1004d8cc9b0c9996_d20160705_m074057_c001_v0001026_t0038', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11338648e291d46c_d20160705_m074058_c001_v0001031_t0024', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f103af9493fa08c3b_d20160705_m074048_c001_v0001004_t0034', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f114388b6b97d05f5_d20160705_m074059_c001_v0001030_t0035', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1195fe7f2de9e41b_d20160705_m074100_c001_v0001029_t0019', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f105e7d664630c485_d20160705_m074102_c001_v0001009_t0040', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f105e066c5eeeb192_d20160705_m074104_c001_v0001015_t0005' ] }, { title: 'Ivan the Terrible', description: 'The Tsarina Anastasia, when she has a foreboding of death.', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f109d78cebdadc14b_d20160704_m203218_c001_v0001029_t0007', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1115bb953866eb7d_d20160704_m203220_c001_v0001029_t0029', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1027df9f79129769_d20160704_m203221_c001_v0001000_t0018', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f10506fa1faa53dd0_d20160704_m203223_c001_v0001026_t0019', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f108f0f36ddbc704e_d20160704_m203225_c001_v0001029_t0003' ] }, { title: 'Orphans of the Storm', description: 'The reflecting faces of young women in Griffith can express white, but it is also the white of a snowflake caught on an eye- lash, the spiritual white of an internal innocence, the dissolved white of a moral degradation, the hostile and searing white of the iceberg where the heroine will wander.', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f109d78cebdadc274_d20160704_m203534_c001_v0001029_t0032', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f114011d148fbca65_d20160704_m203540_c001_v0001023_t0001', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1055a0b231fd0196_d20160704_m203541_c001_v0001029_t0021', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1195fe7f2de99a17_d20160704_m203354_c001_v0001029_t0022', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f109d78cebdadc1de_d20160704_m203355_c001_v0001029_t0037', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f112dee9b049e0bb9_d20160704_m203543_c001_v0001029_t0028', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f100f49c35233bc56_d20160704_m203400_c001_v0001029_t0011', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1003682ec2cb75f8_d20160704_m203544_c001_v0001022_t0020', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11141aa0dd53f02b_d20160704_m203401_c001_v0001031_t0016', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1030aee800c026f1_d20160704_m203402_c001_v0001029_t0009', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f101ee9a9762a3180_d20160704_m203404_c001_v0001029_t0043', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f108f174a243827e2_d20160704_m203406_c001_v0001030_t0034', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f10661bd2af4ffad8_d20160704_m203408_c001_v0001026_t0041', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106a62105d47549b_d20160704_m203409_c001_v0001029_t0011', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f105ffe2e887f03cb_d20160704_m203411_c001_v0001031_t0032', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f101ee9a9762a318b_d20160704_m203412_c001_v0001029_t0040', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11074c13e0b59653_d20160704_m203413_c001_v0001029_t0002', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f105e066c5eeeb0c1_d20160704_m203414_c001_v0001015_t0033', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f100f49c35233bc67_d20160704_m203416_c001_v0001029_t0000', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f115f2dc724df54f1_d20160704_m203418_c001_v0001009_t0032', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11074c13e0b59659_d20160704_m203420_c001_v0001029_t0006', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106a62105d4754a9_d20160704_m203423_c001_v0001029_t0018', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118673cd4f02cb66_d20160704_m203424_c001_v0001029_t0037', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118673cd4f02cb69_d20160704_m203438_c001_v0001029_t0017', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11604f0a65bbd355_d20160704_m203454_c001_v0001026_t0006', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118673cd4f02cb72_d20160704_m203456_c001_v0001029_t0043', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f101ee9a9762a31ea_d20160704_m203511_c001_v0001029_t0037', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118eba71a5f452c6_d20160704_m203513_c001_v0001031_t0029' ] }, { title: "Pandora's Box", description: 'The close-up of the knife prepares us for the terrible thought of Jack the Ripper.', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1172d424b46719c2_d20160704_m203658_c001_v0001001_t0016', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f10295809a65b0665_d20160704_m203702_c001_v0001029_t0024', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11503294bf6aee15_d20160704_m203715_c001_v0001031_t0006', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1016503cea8e2f95_d20160704_m203716_c001_v0001031_t0020', ] }, { title: 'Queen Kelly', description: 'the ingenuous girl is caught between two sources of light, that of the candles on the table before her which glisten on her face, and that of the fire in the fireplace behind her which surrounds her with a luminous halo (she will therefore be too hot and allow her coat to be removed).', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f103519f37947d3df_d20160704_m203747_c001_v0001011_t0015', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f114ee236b5951b81_d20160704_m203751_c001_v0001029_t0029', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f114ee236b5951b83_d20160704_m203752_c001_v0001029_t0035', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f102f4b86400a6a2d_d20160704_m203757_c001_v0001026_t0022', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f119f7b6b8931533b_d20160704_m203758_c001_v0001025_t0019' ] }, { title: 'The Birth of a Nation', description: 'Sometimes even on several faces, when the close-ups of the combatants punctuate the whole of the battle.', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f105082fc609098e1_d20160704_m203852_c001_v0001008_t0012', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1055a0b231fd0207_d20160704_m203910_c001_v0001029_t0023', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106463556cf6510e_d20160704_m203911_c001_v0001013_t0017', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1030aee800c027ff_d20160704_m203913_c001_v0001029_t0024', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f105ffe2e887f054b_d20160704_m203914_c001_v0001031_t0022', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11074c13e0b59705_d20160704_m203916_c001_v0001029_t0011' ] }, { title: 'The General Line ', description: "the handsome face of the priest is dissolved, giving way to a cheating look which links up with the narrow back of the head and the fleshy earlobe: it is as if the traits of faceity were escaping the outline, and testifying to the priest's ressentiment.", video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106a62105d475604_d20160704_m204303_c001_v0001029_t0016', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f101ee9a9762a360c_d20160704_m204308_c001_v0001029_t0043', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f109d78cebdadc4ea_d20160704_m204310_c001_v0001029_t0024', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f113833169cc8a41b_d20160704_m204312_c001_v0001005_t0039', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f114ee236b5951cd6_d20160704_m204313_c001_v0001029_t0025', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1100e672dc0ef542_d20160704_m204315_c001_v0001031_t0024', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f115c8f676cd812df_d20160704_m204316_c001_v0001029_t0020', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f117f4c13eef19c5c_d20160704_m204318_c001_v0001031_t0029' ] }, { title: 'The Murderer Lives at Number 21', description: 'The whirling groups of three objects make us understand that the heroine is thinking of the figure 3 as key to the mystery.', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f111aef3a2328a584_d20160704_m204542_c001_v0001009_t0030', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118fa298e31eb1f8_d20160704_m204529_c001_v0001030_t0035', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f116e714771d3c769_d20160704_m204544_c001_v0001029_t0016', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1092f3aa673f3be5_d20160704_m204531_c001_v0001013_t0037', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106a62105d47567b_d20160704_m204546_c001_v0001029_t0021', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f107afa90184f2fd8_d20160704_m204548_c001_v0001029_t0027', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f108f0f36ddbc7217_d20160704_m204532_c001_v0001029_t0007', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1195fe7f2de99ad7_d20160704_m204534_c001_v0001029_t0029', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1017ee7ed3ad81b7_d20160704_m204536_c001_v0001001_t0039' ] }, { title: 'The Scarlet Empress', description: 'A girl looks in all directions and is surprised by everything when the Russian envoys take her away', video: 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f11490650ad44f2f5_d20160705_m073420_c001_v0001026_t0031', img: [ 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f118eba71a5f4c923_d20160705_m073422_c001_v0001031_t0011', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f100f7763cd660fe6_d20160705_m073424_c001_v0001031_t0012', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f100f49c352341a21_d20160705_m073425_c001_v0001029_t0019', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106cf0b0fbe7cccb_d20160705_m073427_c001_v0001006_t0015', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106a62105d47b399_d20160705_m073428_c001_v0001029_t0033', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1195fe7f2de9e363_d20160705_m073430_c001_v0001029_t0027', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f102e86138b48f863_d20160705_m073432_c001_v0001021_t0016', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f108f0f36ddbcbe67_d20160705_m073500_c001_v0001029_t0016', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f1055a0b231fd74ec_d20160705_m073501_c001_v0001029_t0035', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f117d26c4169397cd_d20160705_m073503_c001_v0001030_t0033', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f106a62105d47b3b6_d20160705_m073504_c001_v0001029_t0042', 'https://f001.backblaze.com/b2api/v1/b2_download_file_by_id?fileId=4_z080d349613288577575e0416_f107cc3eeccd2afc8_d20160705_m073506_c001_v0001026_t0024' ] } ]; const imgUrlList = flatten(entitiesListData.map((film) => { return film.img.map((url) => { return { url, entity: film, } }) })) export class EntitiesList extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> </div> // <div className={styles.entitiesList}> // {entitiesListData.map((entity, key)=> { // return ( // <div key={entity.title} className={styles.entityCard} onClick={(event) => this.props.changeHighlightEntity(entity)}> // <h1>{entity.title}</h1> // <p>{entity.description}</p> // </div> // ) // })} // </div> ); } componentWillMount() { // this.props.changeHighlightEntity(entitiesListData[Math.floor(Math.random() * entitiesListData.length)]) } componentDidMount() { // console.log('start') // const dispatch = this.props.dispatch; // const that = this; // for (let [index, value] of imgUrlList.entries()) { // setTimeout(function(){ // dispatch({ // type: GET_EMOTION_REQUESTED, // payload: {'url': value.url, 'entity': value.entity }, // }) // if (index === imgUrlList.length - 1) { // console.log('done') // console.log(that.props.cluster) // } // }, 3000 * index) // } } } const mapStateToProps = createStructuredSelector({ cluster: selectCluster(), }); export default connect(mapStateToProps, null)(EntitiesList);
ajax/libs/yui/3.9.1/datatable-core/datatable-core-debug.js
hibrahimsafak/cdnjs
YUI.add('datatable-core', function (Y, NAME) { /** The core implementation of the `DataTable` and `DataTable.Base` Widgets. @module datatable @submodule datatable-core @since 3.5.0 **/ var INVALID = Y.Attribute.INVALID_VALUE, Lang = Y.Lang, isFunction = Lang.isFunction, isObject = Lang.isObject, isArray = Lang.isArray, isString = Lang.isString, isNumber = Lang.isNumber, toArray = Y.Array, keys = Y.Object.keys, Table; /** _API docs for this extension are included in the DataTable class._ Class extension providing the core API and structure for the DataTable Widget. Use this class extension with Widget or another Base-based superclass to create the basic DataTable model API and composing class structure. @class DataTable.Core @for DataTable @since 3.5.0 **/ Table = Y.namespace('DataTable').Core = function () {}; Table.ATTRS = { /** Columns to include in the rendered table. If omitted, the attributes on the configured `recordType` or the first item in the `data` collection will be used as a source. This attribute takes an array of strings or objects (mixing the two is fine). Each string or object is considered a column to be rendered. Strings are converted to objects, so `columns: ['first', 'last']` becomes `columns: [{ key: 'first' }, { key: 'last' }]`. DataTable.Core only concerns itself with a few properties of columns. These properties are: * `key` - Used to identify the record field/attribute containing content for this column. Also used to create a default Model if no `recordType` or `data` are provided during construction. If `name` is not specified, this is assigned to the `_id` property (with added incrementer if the key is used by multiple columns). * `children` - Traversed to initialize nested column objects * `name` - Used in place of, or in addition to, the `key`. Useful for columns that aren't bound to a field/attribute in the record data. This is assigned to the `_id` property. * `id` - For backward compatibility. Implementers can specify the id of the header cell. This should be avoided, if possible, to avoid the potential for creating DOM elements with duplicate IDs. * `field` - For backward compatibility. Implementers should use `name`. * `_id` - Assigned unique-within-this-instance id for a column. By order of preference, assumes the value of `name`, `key`, `id`, or `_yuid`. This is used by the rendering views as well as feature module as a means to identify a specific column without ambiguity (such as multiple columns using the same `key`. * `_yuid` - Guid stamp assigned to the column object. * `_parent` - Assigned to all child columns, referencing their parent column. @attribute columns @type {Object[]|String[]} @default (from `recordType` ATTRS or first item in the `data`) @since 3.5.0 **/ columns: { // TODO: change to setter to clone input array/objects validator: isArray, setter: '_setColumns', getter: '_getColumns' }, /** Model subclass to use as the `model` for the ModelList stored in the `data` attribute. If not provided, it will try really hard to figure out what to use. The following attempts will be made to set a default value: 1. If the `data` attribute is set with a ModelList instance and its `model` property is set, that will be used. 2. If the `data` attribute is set with a ModelList instance, and its `model` property is unset, but it is populated, the `ATTRS` of the `constructor of the first item will be used. 3. If the `data` attribute is set with a non-empty array, a Model subclass will be generated using the keys of the first item as its `ATTRS` (see the `_createRecordClass` method). 4. If the `columns` attribute is set, a Model subclass will be generated using the columns defined with a `key`. This is least desirable because columns can be duplicated or nested in a way that's not parsable. 5. If neither `data` nor `columns` is set or populated, a change event subscriber will listen for the first to be changed and try all over again. @attribute recordType @type {Function} @default (see description) @since 3.5.0 **/ recordType: { getter: '_getRecordType', setter: '_setRecordType' }, /** The collection of data records to display. This attribute is a pass through to a `data` property, which is a ModelList instance. If this attribute is passed a ModelList or subclass, it will be assigned to the property directly. If an array of objects is passed, a new ModelList will be created using the configured `recordType` as its `model` property and seeded with the array. Retrieving this attribute will return the ModelList stored in the `data` property. @attribute data @type {ModelList|Object[]} @default `new ModelList()` @since 3.5.0 **/ data: { valueFn: '_initData', setter : '_setData', lazyAdd: false }, /** Content for the `<table summary="ATTRIBUTE VALUE HERE">`. Values assigned to this attribute will be HTML escaped for security. @attribute summary @type {String} @default '' (empty string) @since 3.5.0 **/ //summary: {}, /** HTML content of an optional `<caption>` element to appear above the table. Leave this config unset or set to a falsy value to remove the caption. @attribute caption @type HTML @default '' (empty string) @since 3.5.0 **/ //caption: {}, /** Deprecated as of 3.5.0. Passes through to the `data` attribute. WARNING: `get('recordset')` will NOT return a Recordset instance as of 3.5.0. This is a break in backward compatibility. @attribute recordset @type {Object[]|Recordset} @deprecated Use the `data` attribute @since 3.5.0 **/ recordset: { setter: '_setRecordset', getter: '_getRecordset', lazyAdd: false }, /** Deprecated as of 3.5.0. Passes through to the `columns` attribute. WARNING: `get('columnset')` will NOT return a Columnset instance as of 3.5.0. This is a break in backward compatibility. @attribute columnset @type {Object[]} @deprecated Use the `columns` attribute @since 3.5.0 **/ columnset: { setter: '_setColumnset', getter: '_getColumnset', lazyAdd: false } }; Y.mix(Table.prototype, { // -- Instance properties ------------------------------------------------- /** The ModelList that manages the table's data. @property data @type {ModelList} @default undefined (initially unset) @since 3.5.0 **/ //data: null, // -- Public methods ------------------------------------------------------ /** Gets the column configuration object for the given key, name, or index. For nested columns, `name` can be an array of indexes, each identifying the index of that column in the respective parent's "children" array. If you pass a column object, it will be returned. For columns with keys, you can also fetch the column with `instance.get('columns.foo')`. @method getColumn @param {String|Number|Number[]} name Key, "name", index, or index array to identify the column @return {Object} the column configuration object @since 3.5.0 **/ getColumn: function (name) { var col, columns, i, len, cols; if (isObject(name) && !isArray(name)) { // TODO: support getting a column from a DOM node - this will cross // the line into the View logic, so it should be relayed // Assume an object passed in is already a column def col = name; } else { col = this.get('columns.' + name); } if (col) { return col; } columns = this.get('columns'); if (isNumber(name) || isArray(name)) { name = toArray(name); cols = columns; for (i = 0, len = name.length - 1; cols && i < len; ++i) { cols = cols[name[i]] && cols[name[i]].children; } return (cols && cols[name[i]]) || null; } return null; }, /** Returns the Model associated to the record `id`, `clientId`, or index (not row index). If none of those yield a Model from the `data` ModelList, the arguments will be passed to the `view` instance's `getRecord` method if it has one. If no Model can be found, `null` is returned. @method getRecord @param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or identifier for a row or child element @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var record = this.data.getById(seed) || this.data.getByClientId(seed); if (!record) { if (isNumber(seed)) { record = this.data.item(seed); } // TODO: this should be split out to base somehow if (!record && this.view && this.view.getRecord) { record = this.view.getRecord.apply(this.view, arguments); } } return record || null; }, // -- Protected and private properties and methods ------------------------ /** This tells `Y.Base` that it should create ad-hoc attributes for config properties passed to DataTable's constructor. This is useful for setting configurations on the DataTable that are intended for the rendering View(s). @property _allowAdHocAttrs @type Boolean @default true @protected @since 3.6.0 **/ _allowAdHocAttrs: true, /** A map of column key to column configuration objects parsed from the `columns` attribute. @property _columnMap @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_columnMap: null, /** The Node instance of the table containing the data rows. This is set when the table is rendered. It may also be set by progressive enhancement, though this extension does not provide the logic to parse from source. @property _tableNode @type {Node} @default undefined (initially unset) @protected @since 3.5.0 **/ //_tableNode: null, /** Updates the `_columnMap` property in response to changes in the `columns` attribute. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ _afterColumnsChange: function (e) { this._setColumnMap(e.newVal); }, /** Updates the `modelList` attributes of the rendered views in response to the `data` attribute being assigned a new ModelList. @method _afterDataChange @param {EventFacade} e the `dataChange` event @protected @since 3.5.0 **/ _afterDataChange: function (e) { var modelList = e.newVal; this.data = e.newVal; if (!this.get('columns') && modelList.size()) { // TODO: this will cause a re-render twice because the Views are // subscribed to columnsChange this._initColumns(); } }, /** Assigns to the new recordType as the model for the data ModelList @method _afterRecordTypeChange @param {EventFacade} e recordTypeChange event @protected @since 3.6.0 **/ _afterRecordTypeChange: function (e) { var data = this.data.toJSON(); this.data.model = e.newVal; this.data.reset(data); if (!this.get('columns') && data) { if (data.length) { this._initColumns(); } else { this.set('columns', keys(e.newVal.ATTRS)); } } }, /** Creates a Model subclass from an array of attribute names or an object of attribute definitions. This is used to generate a class suitable to represent the data passed to the `data` attribute if no `recordType` is set. @method _createRecordClass @param {String[]|Object} attrs Names assigned to the Model subclass's `ATTRS` or its entire `ATTRS` definition object @return {Model} @protected @since 3.5.0 **/ _createRecordClass: function (attrs) { var ATTRS, i, len; if (isArray(attrs)) { ATTRS = {}; for (i = 0, len = attrs.length; i < len; ++i) { ATTRS[attrs[i]] = {}; } } else if (isObject(attrs)) { ATTRS = attrs; } return Y.Base.create('record', Y.Model, [], null, { ATTRS: ATTRS }); }, /** Tears down the instance. @method destructor @protected @since 3.6.0 **/ destructor: function () { new Y.EventHandle(Y.Object.values(this._eventHandles)).detach(); }, /** The getter for the `columns` attribute. Returns the array of column configuration objects if `instance.get('columns')` is called, or the specific column object if `instance.get('columns.columnKey')` is called. @method _getColumns @param {Object[]} columns The full array of column objects @param {String} name The attribute name requested (e.g. 'columns' or 'columns.foo'); @protected @since 3.5.0 **/ _getColumns: function (columns, name) { // Workaround for an attribute oddity (ticket #2529254) // getter is expected to return an object if get('columns.foo') is called. // Note 'columns.' is 8 characters return name.length > 8 ? this._columnMap : columns; }, /** Relays the `get()` request for the deprecated `columnset` attribute to the `columns` attribute. THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will expect a Columnset instance returned from `get('columnset')`. @method _getColumnset @param {Object} ignored The current value stored in the `columnset` state @param {String} name The attribute name requested (e.g. 'columnset' or 'columnset.foo'); @deprecated This will be removed with the `columnset` attribute in a future version. @protected @since 3.5.0 **/ _getColumnset: function (_, name) { return this.get(name.replace(/^columnset/, 'columns')); }, /** Returns the Model class of the instance's `data` attribute ModelList. If not set, returns the explicitly configured value. @method _getRecordType @param {Model} val The currently configured value @return {Model} **/ _getRecordType: function (val) { // Prefer the value stored in the attribute because the attribute // change event defaultFn sets e.newVal = this.get('recordType') // before notifying the after() subs. But if this getter returns // this.data.model, then after() subs would get e.newVal === previous // model before _afterRecordTypeChange can set // this.data.model = e.newVal return val || (this.data && this.data.model); }, /** Initializes the `_columnMap` property from the configured `columns` attribute. If `columns` is not set, but there are records in the `data` ModelList, use `ATTRS` of that class. @method _initColumns @protected @since 3.5.0 **/ _initColumns: function () { var columns = this.get('columns') || [], item; // Default column definition from the configured recordType if (!columns.length && this.data.size()) { // TODO: merge superclass attributes up to Model? item = this.data.item(0); if (item.toJSON) { item = item.toJSON(); } this.set('columns', keys(item)); } this._setColumnMap(columns); }, /** Sets up the change event subscriptions to maintain internal state. @method _initCoreEvents @protected @since 3.6.0 **/ _initCoreEvents: function () { this._eventHandles.coreAttrChanges = this.after({ columnsChange : Y.bind('_afterColumnsChange', this), recordTypeChange: Y.bind('_afterRecordTypeChange', this), dataChange : Y.bind('_afterDataChange', this) }); }, /** Defaults the `data` attribute to an empty ModelList if not set during construction. Uses the configured `recordType` for the ModelList's `model` proeprty if set. @method _initData @protected @return {ModelList} @since 3.6.0 **/ _initData: function () { var recordType = this.get('recordType'), // TODO: LazyModelList if recordType doesn't have complex ATTRS modelList = new Y.ModelList(); if (recordType) { modelList.model = recordType; } return modelList; }, /** Initializes the instance's `data` property from the value of the `data` attribute. If the attribute value is a ModelList, it is assigned directly to `this.data`. If it is an array, a ModelList is created, its `model` property is set to the configured `recordType` class, and it is seeded with the array data. This ModelList is then assigned to `this.data`. @method _initDataProperty @param {Array|ModelList|ArrayList} data Collection of data to populate the DataTable @protected @since 3.6.0 **/ _initDataProperty: function (data) { var recordType; if (!this.data) { recordType = this.get('recordType'); if (data && data.each && data.toJSON) { this.data = data; if (recordType) { this.data.model = recordType; } } else { // TODO: customize the ModelList or read the ModelList class // from a configuration option? this.data = new Y.ModelList(); if (recordType) { this.data.model = recordType; } } // TODO: Replace this with an event relay for specific events. // Using bubbling causes subscription conflicts with the models' // aggregated change event and 'change' events from DOM elements // inside the table (via Widget UI event). this.data.addTarget(this); } }, /** Initializes the columns, `recordType` and data ModelList. @method initializer @param {Object} config Configuration object passed to constructor @protected @since 3.5.0 **/ initializer: function (config) { var data = config.data, columns = config.columns, recordType; // Referencing config.data to allow _setData to be more stringent // about its behavior this._initDataProperty(data); // Default columns from recordType ATTRS if recordType is supplied at // construction. If no recordType is supplied, but the data is // supplied as a non-empty array, use the keys of the first item // as the columns. if (!columns) { recordType = (config.recordType || config.data === this.data) && this.get('recordType'); if (recordType) { columns = keys(recordType.ATTRS); } else if (isArray(data) && data.length) { columns = keys(data[0]); } if (columns) { this.set('columns', columns); } } this._initColumns(); this._eventHandles = {}; this._initCoreEvents(); }, /** Iterates the array of column configurations to capture all columns with a `key` property. An map is built with column keys as the property name and the corresponding column object as the associated value. This map is then assigned to the instance's `_columnMap` property. @method _setColumnMap @param {Object[]|String[]} columns The array of column config objects @protected @since 3.6.0 **/ _setColumnMap: function (columns) { var map = {}; function process(cols) { var i, len, col, key; for (i = 0, len = cols.length; i < len; ++i) { col = cols[i]; key = col.key; // First in wins for multiple columns with the same key // because the first call to genId (in _setColumns) will // return the same key, which will then be overwritten by the // subsequent same-keyed column. So table.getColumn(key) would // return the last same-keyed column. if (key && !map[key]) { map[key] = col; } //TODO: named columns can conflict with keyed columns map[col._id] = col; if (col.children) { process(col.children); } } } process(columns); this._columnMap = map; }, /** Translates string columns into objects with that string as the value of its `key` property. All columns are assigned a `_yuid` stamp and `_id` property corresponding to the column's configured `name` or `key` property with any spaces replaced with dashes. If the same `name` or `key` appears in multiple columns, subsequent appearances will have their `_id` appended with an incrementing number (e.g. if column "foo" is included in the `columns` attribute twice, the first will get `_id` of "foo", and the second an `_id` of "foo1"). Columns that are children of other columns will have the `_parent` property added, assigned the column object to which they belong. @method _setColumns @param {null|Object[]|String[]} val Array of config objects or strings @return {null|Object[]} @protected **/ _setColumns: function (val) { var keys = {}, known = [], knownCopies = [], arrayIndex = Y.Array.indexOf; function copyObj(o) { var copy = {}, key, val, i; known.push(o); knownCopies.push(copy); for (key in o) { if (o.hasOwnProperty(key)) { val = o[key]; if (isArray(val)) { copy[key] = val.slice(); } else if (isObject(val, true)) { i = arrayIndex(val, known); copy[key] = i === -1 ? copyObj(val) : knownCopies[i]; } else { copy[key] = o[key]; } } } return copy; } function genId(name) { // Sanitize the name for use in generated CSS classes. // TODO: is there more to do for other uses of _id? name = name.replace(/\s+/, '-'); if (keys[name]) { name += (keys[name]++); } else { keys[name] = 1; } return name; } function process(cols, parent) { var columns = [], i, len, col, yuid; for (i = 0, len = cols.length; i < len; ++i) { columns[i] = // chained assignment col = isString(cols[i]) ? { key: cols[i] } : copyObj(cols[i]); yuid = Y.stamp(col); // For backward compatibility if (!col.id) { // Implementers can shoot themselves in the foot by setting // this config property to a non-unique value col.id = yuid; } if (col.field) { // Field is now known as "name" to avoid confusion with data // fields or schema.resultFields col.name = col.field; } if (parent) { col._parent = parent; } else { delete col._parent; } // Unique id based on the column's configured name or key, // falling back to the yuid. Duplicates will have a counter // added to the end. col._id = genId(col.name || col.key || col.id); if (isArray(col.children)) { col.children = process(col.children, col); } } return columns; } return val && process(val); }, /** Relays attribute assignments of the deprecated `columnset` attribute to the `columns` attribute. If a Columnset is object is passed, its basic object structure is mined. @method _setColumnset @param {Array|Columnset} val The columnset value to relay @deprecated This will be removed with the deprecated `columnset` attribute in a later version. @protected @since 3.5.0 **/ _setColumnset: function (val) { this.set('columns', val); return isArray(val) ? val : INVALID; }, /** Accepts an object with `each` and `getAttrs` (preferably a ModelList or subclass) or an array of data objects. If an array is passes, it will create a ModelList to wrap the data. In doing so, it will set the created ModelList's `model` property to the class in the `recordType` attribute, which will be defaulted if not yet set. If the `data` property is already set with a ModelList, passing an array as the value will call the ModelList's `reset()` method with that array rather than replacing the stored ModelList wholesale. Any non-ModelList-ish and non-array value is invalid. @method _setData @protected @since 3.5.0 **/ _setData: function (val) { if (val === null) { val = []; } if (isArray(val)) { this._initDataProperty(); // silent to prevent subscribers to both reset and dataChange // from reacting to the change twice. // TODO: would it be better to return INVALID to silence the // dataChange event, or even allow both events? this.data.reset(val, { silent: true }); // Return the instance ModelList to avoid storing unprocessed // data in the state and their vivified Model representations in // the instance's data property. Decreases memory consumption. val = this.data; } else if (!val || !val.each || !val.toJSON) { // ModelList/ArrayList duck typing val = INVALID; } return val; }, /** Relays the value assigned to the deprecated `recordset` attribute to the `data` attribute. If a Recordset instance is passed, the raw object data will be culled from it. @method _setRecordset @param {Object[]|Recordset} val The recordset value to relay @deprecated This will be removed with the deprecated `recordset` attribute in a later version. @protected @since 3.5.0 **/ _setRecordset: function (val) { var data; if (val && Y.Recordset && val instanceof Y.Recordset) { data = []; val.each(function (record) { data.push(record.get('data')); }); val = data; } this.set('data', val); return val; }, /** Accepts a Base subclass (preferably a Model subclass). Alternately, it will generate a custom Model subclass from an array of attribute names or an object defining attributes and their respective configurations (it is assigned as the `ATTRS` of the new class). Any other value is invalid. @method _setRecordType @param {Function|String[]|Object} val The Model subclass, array of attribute names, or the `ATTRS` definition for a custom model subclass @return {Function} A Base/Model subclass @protected @since 3.5.0 **/ _setRecordType: function (val) { var modelClass; // Duck type based on known/likely consumed APIs if (isFunction(val) && val.prototype.toJSON && val.prototype.setAttrs) { modelClass = val; } else if (isObject(val)) { modelClass = this._createRecordClass(val); } return modelClass || INVALID; } }); }, '@VERSION@', {"requires": ["escape", "model-list", "node-event-delegate"]});
src/example/target.js
react-entanglement/web-storage-adapter
import React from 'react' import { render } from 'react-dom' import Entanglement from 'react-entanglement' import adapter from '../index' import MagicForm from './components/MagicForm' const MaterializedMagicForm = Entanglement.materialize({ name: 'MagicForm', constructor: MagicForm }) render( <Entanglement adapter={adapter('web-storage-adapter-demo')}> <MaterializedMagicForm /> </Entanglement> , document.getElementById('main') )
src/main/webapp/static/jquery-validation/1.11.1/lib/jquery-1.7.2.js
linkaitao/toceanCRM
/*! * jQuery JavaScript Library v1.7.2 * 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: Wed Mar 21 12:46:34 2012 -0700 */ (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 // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) 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+$/, // 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.]+))?/, // Matches dashed string for camelizing rdashAlpha = /-([a-z]|[0-9])/ig, rmsPrefix = /^-ms-/, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // 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.7.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 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.add( 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( 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.fireWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).off( "ready" ); } } }, bindReady: function() { if ( readyList ) { return; } readyList = jQuery.Callbacks( "once memory" ); // 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"; }, 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[ 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 && !hasOwn.call(obj, "constructor") && !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 || hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { for ( var name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( 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 parseXML: function( data ) { if ( typeof data !== "string" || !data ) { return null; } var xml, tmp; 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 && 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.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' // 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, i ) { var len; if ( array ) { if ( indexOf ) { return indexOf.call( array, elem, i ); } len = array.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in array && 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 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(); }, // 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(); } return jQuery; })(); // String to Object flags format cache var flagsCache = {}; // Convert String-formatted flags into Object-formatted ones and store in cache function createFlags( flags ) { var object = flagsCache[ flags ] = {}, i, length; flags = flags.split( /\s+/ ); for ( i = 0, length = flags.length; i < length; i++ ) { object[ flags[i] ] = true; } return object; } /* * Create a callback list using the following parameters: * * flags: an optional list of space-separated flags that will change how * the callback list behaves * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible flags: * * 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( flags ) { // Convert flags from String-formatted to Object-formatted // (we check in cache first) flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; var // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = [], // 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, // Add one or several callbacks to the list add = function( args ) { var i, length, elem, type, actual; for ( i = 0, length = args.length; i < length; i++ ) { elem = args[ i ]; type = jQuery.type( elem ); if ( type === "array" ) { // Inspect recursively add( elem ); } else if ( type === "function" ) { // Add if not in unique mode and callback is not in if ( !flags.unique || !self.has( elem ) ) { list.push( elem ); } } } }, // Fire callbacks fire = function( context, args ) { args = args || []; memory = !flags.memory || [ context, args ]; fired = true; firing = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { memory = true; // Mark as halted break; } } firing = false; if ( list ) { if ( !flags.once ) { if ( stack && stack.length ) { memory = stack.shift(); self.fireWith( memory[ 0 ], memory[ 1 ] ); } } else if ( memory === true ) { self.disable(); } else { list = []; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { var length = list.length; add( 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, unless previous // firing was halted (stopOnFalse) } else if ( memory && memory !== true ) { firingStart = length; fire( memory[ 0 ], memory[ 1 ] ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { var args = arguments, argIndex = 0, argLength = args.length; for ( ; argIndex < argLength ; argIndex++ ) { for ( var i = 0; i < list.length; i++ ) { if ( args[ argIndex ] === list[ i ] ) { // Handle firingIndex and firingLength if ( firing ) { if ( i <= firingLength ) { firingLength--; if ( i <= firingIndex ) { firingIndex--; } } } // Remove the element list.splice( i--, 1 ); // If we have some unicity property then // we only need to do this once if ( flags.unique ) { break; } } } } } return this; }, // Control if a given callback is in the list has: function( fn ) { if ( list ) { var i = 0, length = list.length; for ( ; i < length; i++ ) { if ( fn === list[ i ] ) { return true; } } } return false; }, // 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 || memory === true ) { 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 ( stack ) { if ( firing ) { if ( !flags.once ) { stack.push( [ context, args ] ); } } else if ( !( flags.once && memory ) ) { fire( context, 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; }; var // Static reference to slice sliceDeferred = [].slice; jQuery.extend({ Deferred: function( func ) { var doneList = jQuery.Callbacks( "once memory" ), failList = jQuery.Callbacks( "once memory" ), progressList = jQuery.Callbacks( "memory" ), state = "pending", lists = { resolve: doneList, reject: failList, notify: progressList }, promise = { done: doneList.add, fail: failList.add, progress: progressList.add, state: function() { return state; }, // Deprecated isResolved: doneList.fired, isRejected: failList.fired, then: function( doneCallbacks, failCallbacks, progressCallbacks ) { deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); return this; }, always: function() { deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); return this; }, pipe: function( fnDone, fnFail, fnProgress ) { return jQuery.Deferred(function( newDefer ) { jQuery.each( { done: [ fnDone, "resolve" ], fail: [ fnFail, "reject" ], progress: [ fnProgress, "notify" ] }, 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, newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ 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 ) { obj = promise; } else { for ( var key in promise ) { obj[ key ] = promise[ key ]; } } return obj; } }, deferred = promise.promise({}), key; for ( key in lists ) { deferred[ key ] = lists[ key ].fire; deferred[ key + "With" ] = lists[ key ].fireWith; } // Handle state deferred.done( function() { state = "resolved"; }, failList.disable, progressList.lock ).fail( function() { state = "rejected"; }, doneList.disable, progressList.lock ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( firstParam ) { var args = sliceDeferred.call( arguments, 0 ), i = 0, length = args.length, pValues = new Array( length ), count = length, pCount = length, deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? firstParam : jQuery.Deferred(), promise = deferred.promise(); function resolveFunc( i ) { return function( value ) { args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; if ( !( --count ) ) { deferred.resolveWith( deferred, args ); } }; } function progressFunc( i ) { return function( value ) { pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; deferred.notifyWith( promise, pValues ); }; } if ( length > 1 ) { for ( ; i < length; i++ ) { if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); } else { --count; } } if ( !count ) { deferred.resolveWith( deferred, args ); } } else if ( deferred !== firstParam ) { deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); } return promise; } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, tds, events, eventName, i, isSupported, div = document.createElement( "div" ), documentElement = document.documentElement; // 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", // 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>", // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, pixelMargin: true }; // jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat"); // 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() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent( "onclick" ); } // 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: 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; } } fragment.removeChild( div ); // Null elements to avoid leaks in IE fragment = select = opt = div = input = null; // Run tests that need a body at doc ready jQuery(function() { var container, outer, inner, table, td, offsetSupport, marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight, paddingMarginBorderVisibility, paddingMarginBorder, body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } conMarginTop = 1; paddingMarginBorder = "padding:0;margin:0;border:"; positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;"; paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;"; style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;"; html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" + "<table " + style + "' cellpadding='0' cellspacing='0'>" + "<tr><td></td></tr></table>"; container = document.createElement("div"); container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; 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 style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>"; tds = div.getElementsByTagName( "td" ); 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 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 ( window.getComputedStyle ) { div.innerHTML = ""; marginDiv = document.createElement( "div" ); marginDiv.style.width = "0"; marginDiv.style.marginRight = "0"; div.style.width = "2px"; div.appendChild( marginDiv ); support.reliableMarginRight = ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; } 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.width = div.style.padding = "1px"; div.style.border = 0; div.style.overflow = "hidden"; div.style.display = "inline"; div.style.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 style='width:5px;'></div>"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); } div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility; div.innerHTML = html; outer = div.firstChild; inner = outer.firstChild; td = outer.nextSibling.firstChild.firstChild; offsetSupport = { doesNotAddBorder: ( inner.offsetTop !== 5 ), doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) }; inner.style.position = "fixed"; inner.style.top = "20px"; // safari subtracts parent border width here which is 5px offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); inner.style.position = inner.style.top = ""; outer.style.overflow = "hidden"; outer.style.position = "relative"; offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); if ( window.getComputedStyle ) { div.style.marginTop = "1%"; support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%"; } if ( typeof container.style.zoom !== "undefined" ) { container.style.zoom = 1; } body.removeChild( container ); marginDiv = div = container = null; jQuery.extend( support, offsetSupport ); }); return support; })(); var rbrace = /^(?:\{.*\}|\[.*\])$/, rmultiDash = /([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 privateCache, 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, isEvents = name === "events"; // 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] || (!isEvents && !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.uuid; } 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 ); } } privateCache = 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; } // Users should not attempt to inspect the internal events object using jQuery.data, // it is undocumented and subject to change. But does anyone listen? No. if ( isEvents && !thisCache[ name ] ) { return privateCache.events; } // 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, // Reference to internal data cache key 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[ internalKey ] : internalKey; // 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; } } // 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 // Ensure that `cache` is not a window object #10080 if ( jQuery.support.deleteExpando || !cache.setInterval ) { delete cache[ id ]; } else { cache[ id ] = null; } // We destroyed the cache and need to eliminate the expando on the node to avoid // false lookups in the cache for entries that no longer exist 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[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = 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 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-" ) === 0 ) { 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 : jQuery.isNumeric( 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 ) { for ( var 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; } function handleQueueMarkDefer( elem, type, src ) { var deferDataKey = type + "defer", queueDataKey = type + "queue", markDataKey = type + "mark", defer = jQuery._data( elem, deferDataKey ); if ( defer && ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { // 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 ) && !jQuery._data( elem, markDataKey ) ) { jQuery.removeData( elem, deferDataKey, true ); defer.fire(); } }, 0 ); } } jQuery.extend({ _mark: function( elem, type ) { if ( elem ) { type = ( type || "fx" ) + "mark"; jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); } }, _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 ) || 1) - 1 ); if ( count ) { jQuery._data( elem, key, count ); } else { jQuery.removeData( elem, key, true ); handleQueueMarkDefer( elem, type, "mark" ); } } }, queue: function( elem, type, data ) { var q; if ( elem ) { type = ( type || "fx" ) + "queue"; q = jQuery._data( elem, type ); // 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) ); } else { q.push( data ); } } return q || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), fn = queue.shift(), hooks = {}; // 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" ); } jQuery._data( elem, type + ".run", hooks ); fn.call( elem, function() { jQuery.dequeue( elem, type ); }, hooks ); } if ( !queue.length ) { jQuery.removeData( elem, type + "queue " + type + ".run", true ); handleQueueMarkDefer( elem, type, "queue" ); } } }); 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 ); 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, 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.Callbacks( "once memory" ), true ) )) { count++; tmp.add( resolve ); } } resolve(); return defer.promise( object ); } }); 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, getSetAttribute = jQuery.support.getSetAttribute, nodeHook, boolHook, fixSpecified; 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( 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 ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var classNames, i, l, elem, className, c, cl; 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 ) { classNames = ( value || "" ).split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { className = (" " + elem.className + " ").replace( rclass, " " ); for ( 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 ) { 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( 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 + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { 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 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.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; } } }, attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, 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 && name in jQuery.attrFn ) { 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, l, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.toLowerCase().split( rspace ); l = attrNames.length; for ( ; i < l; 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; } } } }); // Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; // 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.nodeValue !== "" : ret.specified ) ? ret.nodeValue : 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.nodeValue = value + "" ); } }; // Apply the nodeHook to tabindex jQuery.attrHooks.tabindex.set = nodeHook.set; // 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)$/, rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, quickParse = function( selector ) { var quick = rquickIs.exec( selector ); if ( quick ) { // 0 1 2 3 // [ _, tag, id, class ] quick[1] = ( quick[1] || "" ).toLowerCase(); quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); } return quick; }, quickIs = function( elem, m ) { var attrs = elem.attributes || {}; return ( (!m[1] || elem.nodeName.toLowerCase() === m[1]) && (!m[2] || (attrs.id || {}).value === m[2]) && (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) ); }, 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, quick, 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, quick: selector && quickParse( 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 elemData = jQuery.hasData( elem ) && jQuery._data( elem ), t, tns, type, origType, namespaces, origCount, j, events, special, handle, eventType, handleObj; 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 ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { handle = elemData.handle; if ( handle ) { handle.elem = null; } // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, [ "events", "handle" ], 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 type = event.type || event, namespaces = [], cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; // 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; old = null; for ( ; 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 && old === elem.ownerDocument ) { 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( 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 handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments, 0 ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = [], i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; // 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") ) { // Pregenerate a single jQuery object for reuse with .is() jqcur = jQuery(this); jqcur.context = this.ownerDocument || this; for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process events on disabled elements (#6911, #8165) if ( cur.disabled !== true ) { selMatch = {}; matches = []; jqcur[0] = cur; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = ( handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) ); } 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; add metaKey if it's not there (#3368, IE6/7/8) if ( event.metaKey === undefined ) { event.metaKey = event.ctrlKey; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady }, 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 ) { if ( elem.detachEvent ) { elem.detachEvent( "on" + type, 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 target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector, ret; // 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 && !form._submit_attached ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); 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; 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 ) && !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 ); } }); 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 ) { if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event var 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 ( var 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 ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } 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 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, expando = "sizcache" + (Math.random() + '').replace('.', ''), done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true, rBackslash = /\\/g, rReturn = /\r\n/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, seed ); } 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, seed ); } } } 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, i, len, match, type, left; if ( !expr ) { return []; } for ( i = 0, len = Expr.order.length; i < len; i++ ) { type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { 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, type, found, item, filter, left, i, pass, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { 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 ( i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); 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 new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Utility function for retreiving the text value of an array of DOM nodes * @param {Array|Element} elem */ var getText = Sizzle.getText = function( elem ) { var i, node, nodeType = elem.nodeType, ret = ""; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent || innerText for elements if ( typeof elem.textContent === 'string' ) { return elem.textContent; } else if ( typeof elem.innerText === 'string' ) { // Replace IE's carriage returns return elem.innerText.replace( rReturn, '' ); } else { // Traverse it's children for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } } else { // If no nodeType, this is expected to be an array for ( i = 0; (node = elem[i]); i++ ) { // Do not traverse comment nodes if ( node.nodeType !== 8 ) { ret += getText( node ); } } } return ret; }; 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 || 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 first, last, doneName, parent, cache, count, diff, 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; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; case "nth": first = match[2]; last = match[3]; if ( first === 1 && last === 0 ) { return true; } doneName = match[0]; parent = elem.parentNode; if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent[ expando ] = doneName; } 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 && 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 = Sizzle.attr ? Sizzle.attr( elem, name ) : 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 && Sizzle.attr ? result != null : 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) ); } // Expose origPOS // "global" as in regardless of relation to brackets/parens Expr.match.globalPOS = origPOS; 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; }; } // 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[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem[ expando ] = 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[ expando ] === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem[ expando ] = 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, seed ) { 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, seed ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; Sizzle.selectors.attrMap = {}; 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.globalPOS, // 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" ? // If this is a positional selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". POS.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 ret = [], i, l, cur = this[0]; // Array (deprecated as of jQuery 1.7) if ( jQuery.isArray( selectors ) ) { var level = 1; while ( cur && cur.ownerDocument && cur !== context ) { for ( i = 0; i < selectors.length; i++ ) { if ( jQuery( cur ).is( selectors[ i ] ) ) { ret.push({ selector: selectors[ i ], 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 ) { // 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 ) ); }, 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 ); 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, 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; }, 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; }); } 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+="(?:\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+;/, rnoInnerhtml = /<(?:script|style)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "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, "", "" ] }, safeFragment = createSafeFragment( document ); 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( 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.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.clean( arguments ); 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.clean(arguments) ); 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 ) { 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, "" ) : null; } if ( typeof value === "string" && !rnoInnerhtml.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 ( 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, function( i, elem ) { if ( elem.src ) { jQuery.ajax({ type: "GET", global: false, 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 ); } }); } } 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 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(); // 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; // 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 ); // Clear flags for bubbling special change/submit events, they must // be reattached when the newly cloned events are first activated dest.removeAttribute( "_submit_attached" ); dest.removeAttribute( "_change_attached" ); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc, first = args[ 0 ]; // nodes may contain either an explicit document object, // a jQuery collection or context object. // If nodes[0] contains a valid object to assign to doc if ( nodes && nodes[0] ) { doc = nodes[0].ownerDocument || nodes[0]; } // Ensure that an attr object doesn't incorrectly stand in as a document object // Chrome and Firefox seem to allow this to occur and will throw exception // Fixes #8950 if ( !doc.createDocumentFragment ) { doc = 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 // 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 && doc === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { cacheable = true; cacheresults = jQuery.fragments[ first ]; if ( cacheresults && cacheresults !== 1 ) { fragment = cacheresults; } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ first ] = 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 ( 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 ( elem.type === "checkbox" || elem.type === "radio" ) { elem.defaultChecked = elem.checked; } } // Finds all inputs and passes them to fixDefaultChecked function findInputs( elem ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "input" ) { fixDefaultChecked( elem ); // Skip scripts, get other children } else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } // Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js function shimCloneNode( elem ) { var div = document.createElement( "div" ); safeFragment.appendChild( div ); div.innerHTML = elem.outerHTML; return div.firstChild; } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, // IE<=8 does not properly clone detached, unknown element nodes clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ? elem.cloneNode( true ) : shimCloneNode( elem ); 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 checkScriptType, script, j, ret = []; 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; } 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"), safeChildNodes = safeFragment.childNodes, remove; // Append wrapper element to unknown element safe doc fragment if ( context === document ) { // Use the fragment we've already created for this document safeFragment.appendChild( div ); } else { // Use a fragment created with the owner document createSafeFragment( context ).appendChild( 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; // Clear elements from DocumentFragment (safeFragment or otherwise) // to avoid hoarding elements. Fixes #11356 if ( div ) { div.parentNode.removeChild( div ); // Guard against -1 index exceptions in FF3.6 if ( safeChildNodes.length > 0 ) { remove = safeChildNodes[ safeChildNodes.length - 1 ]; if ( remove && remove.parentNode ) { remove.parentNode.removeChild( remove ); } } } } } // 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++ ) { script = ret[i]; if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) { scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script ); } else { if ( script.nodeType === 1 ) { var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType ); ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); } fragment.appendChild( script ); } } } return ret; }, cleanData: function( elems ) { var data, id, cache = jQuery.cache, 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 ]; 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 ]; } } } }); var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, // fixed for IE9, see #8346 rupper = /([A-Z]|^ms)/g, rnum = /^[\-+]?(?:\d*\.)?\d+$/i, rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i, rrelNum = /^([\-+])=([\-+.\de]+)/, rmargin = /^margin/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, // order is important! cssExpand = [ "Top", "Right", "Bottom", "Left" ], curCSS, getComputedStyle, currentStyle; jQuery.fn.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 ); }; 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; } else { return elem.style.opacity; } } } }, // 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, 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; // 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 )) !== 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 = {}, ret, name; // 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; } }); // DEPRECATED in 1.3, Use jQuery.css() instead jQuery.curCSS = jQuery.css; if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, name ) { var ret, defaultView, computedStyle, width, style = elem.style; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( (defaultView = elem.ownerDocument.defaultView) && (computedStyle = defaultView.getComputedStyle( elem, null )) ) { ret = computedStyle.getPropertyValue( name ); if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { ret = jQuery.style( elem, name ); } } // A tribute to the "awesome hack by Dean Edwards" // WebKit uses "computed value (percentage if specified)" instead of "used value" for margins // which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) { width = style.width; style.width = ret; ret = computedStyle.width; style.width = width; } return ret; }; } if ( document.documentElement.currentStyle ) { currentStyle = function( elem, name ) { var left, rsLeft, uncomputed, 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 && (uncomputed = style[ name ]) ) { ret = uncomputed; } // 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 ( rnumnonpx.test( ret ) ) { // 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; }; } curCSS = getComputedStyle || currentStyle; function getWidthOrHeight( elem, name, extra ) { // Start with offset property var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, i = name === "width" ? 1 : 0, len = 4; if ( val > 0 ) { if ( extra !== "border" ) { for ( ; i < len; i += 2 ) { if ( !extra ) { val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0; } else { val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val + "px"; } // 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; } // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; // Add padding, border, margin if ( extra ) { for ( ; i < len; i += 2 ) { val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0; if ( extra !== "padding" ) { val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } if ( extra === "margin" ) { val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0; } } } return val + "px"; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { if ( elem.offsetWidth !== 0 ) { return getWidthOrHeight( elem, name, extra ); } else { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } } }, set: function( elem, value ) { return rnum.test( value ) ? value + "px" : 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, 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, "" ) ) === "" ) { // 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; } }; } 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 return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "margin-right" ); } else { return elem.style.marginRight; } }); } }; } }); 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 && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // 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; } }; }); 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|datetime-local|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|res|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, // 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 = "*"; } 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; } // 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.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.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, 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 // 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 || {}, // 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, nativeStatusText, 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 > 0 ? 4 : 0; var isSuccess, success, error, statusText = nativeStatusText, 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 = "" + ( 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.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 prefilter, 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; // #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 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 ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw 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" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( 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 = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType ); 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; } // 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 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; 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.contains( elem.ownerDocument.documentElement, elem ) ) { 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 { var elem, display, i = 0, j = this.length; for ( ; i < j; i++ ) { elem = this[i]; if ( elem.style ) { display = jQuery.css( elem, "display" ); if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) { jQuery._data( elem, "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 ); function doAnimation() { // 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, e, hooks, replace, parts, start, end, unit, method; // will store per property easing and be used to determine when an animation is complete opt.animatedProperties = {}; // first pass over propertys to expand / normalize for ( p in prop ) { name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; } if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) { replace = hooks.expand( prop[ name ] ); delete prop[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'p' from above because we have the correct "name" for ( p in replace ) { if ( ! ( p in prop ) ) { prop[ p ] = replace[ p ]; } } } } for ( name in prop ) { 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" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) { this.style.display = "inline-block"; } else { 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 ) ) { // Tracks whether to show or hide based on private // data attached to the element method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 ); if ( method ) { jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" ); e[ method ](); } else { e[ 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; } return optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var index, hadTimers = false, timers = jQuery.timers, data = jQuery._data( this ); // clear marker counters if we know they won't be if ( !gotoEnd ) { jQuery._unmark( true, this ); } function stopQueue( elem, data, index ) { var hooks = data[ index ]; jQuery.removeData( elem, index, true ); hooks.stop( gotoEnd ); } if ( type == null ) { for ( index in data ) { if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) { stopQueue( this, data, index ); } } } else if ( data[ index = type + ".run" ] && data[ index ].stop ){ stopQueue( this, data, index ); } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { if ( gotoEnd ) { // force the next step to be the last timers[ index ]( true ); } else { timers[ index ].saveState(); } hadTimers = true; 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 ( !( gotoEnd && hadTimers ) ) { jQuery.dequeue( this, type ); } }); } }); // 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; // 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( noUnmark ) { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } else if ( noUnmark !== false ) { jQuery._unmark( this ); } }; return opt; }, easing: { linear: function( p ) { return p; }, swing: function( p ) { return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5; } }, 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; this.startTime = fxNow || createFxNow(); this.end = to; this.now = this.start = from; this.pos = this.state = 0; this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" ); function t( gotoEnd ) { return self.step( gotoEnd ); } t.queue = this.options.queue; t.elem = this.elem; t.saveState = function() { if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) { if ( self.options.hide ) { jQuery._data( self.elem, "fxshow" + self.prop, self.start ); } else if ( self.options.show ) { jQuery._data( self.elem, "fxshow" + self.prop, self.end ); } } }; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval( fx.tick, fx.interval ); } }, // Simple 'show' function show: function() { var dataShow = jQuery._data( this.elem, "fxshow" + this.prop ); // Remember where we started, so that we can go back to it later this.options.orig[ this.prop ] = dataShow || 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 if ( dataShow !== undefined ) { // This show is picking up where a previous hide or show left off this.custom( this.cur(), dataShow ); } else { 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._data( this.elem, "fxshow" + 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 p, n, complete, t = fxNow || createFxNow(), done = true, elem = this.elem, options = this.options; if ( gotoEnd || t >= options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); options.animatedProperties[ this.prop ] = true; for ( p in options.animatedProperties ) { if ( options.animatedProperties[ p ] !== 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 ( p in options.animatedProperties ) { jQuery.style( elem, p, options.orig[ p ] ); jQuery.removeData( elem, "fxshow" + p, true ); // Toggle data is no longer needed jQuery.removeData( elem, "toggle" + p, true ); } } // Execute the complete function // in the event that the complete function throws an exception // we must ensure it won't be called twice. #5684 complete = options.complete; if ( complete ) { options.complete = false; 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() { 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(); } }, 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.now + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); // Ensure props that can't be negative don't go there on undershoot easing jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) { // exclude marginTop, marginLeft, marginBottom and marginRight from this list if ( prop.indexOf( "margin" ) ) { jQuery.fx.step[ prop ] = function( fx ) { jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit ); }; } }); 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 body = document.body, 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; } 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( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" ); iframeDoc.close(); } elem = iframeDoc.createElement( nodeName ); iframeDoc.body.appendChild( elem ); display = jQuery.css( elem, "display" ); body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; } return elemdisplay[ nodeName ]; } var getOffset, rtable = /^t(?:able|d|h)$/i, rroot = /^(?:body|html)$/i; if ( "getBoundingClientRect" in document.documentElement ) { getOffset = function( elem, doc, docElem, box ) { try { box = elem.getBoundingClientRect(); } catch(e) {} // 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 { getOffset = function( elem, doc, docElem ) { var computedStyle, offsetParent = elem.offsetParent, prevOffsetParent = elem, 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.support.fixedPosition && 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.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.support.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.support.fixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var elem = this[0], doc = elem && elem.ownerDocument; if ( !doc ) { return null; } if ( elem === doc.body ) { return jQuery.offset.bodyOffset( elem ); } return getOffset( elem, doc, doc.documentElement ); }; 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 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( {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 ] : jQuery.support.boxModel && win.document.documentElement[ method ] || win.document.body[ 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 width, height, innerHeight, innerWidth, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { var clientProp = "client" + name, scrollProp = "scroll" + name, offsetProp = "offset" + name; // innerHeight and innerWidth jQuery.fn[ "inner" + name ] = function() { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, "padding" ) ) : this[ type ]() : null; }; // outerHeight and outerWidth jQuery.fn[ "outer" + name ] = function( margin ) { var elem = this[0]; return elem ? elem.style ? parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) : this[ type ]() : null; }; jQuery.fn[ type ] = function( value ) { return jQuery.access( this, function( elem, type, value ) { var doc, docElemProp, orig, ret; if ( jQuery.isWindow( elem ) ) { // 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat doc = elem.document; docElemProp = doc.documentElement[ clientProp ]; return jQuery.support.boxModel && docElemProp || doc.body && doc.body[ clientProp ] || docElemProp; } // Get document width or height if ( elem.nodeType === 9 ) { // Either scroll[Width/Height] or offset[Width/Height], whichever is greater doc = elem.documentElement; // when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height] // so we can't use max, as it'll choose the incorrect offset[Width/Height] // instead we use the correct client[Width/Height] // support:IE6 if ( doc[ clientProp ] >= doc[ scrollProp ] ) { return doc[ clientProp ]; } return Math.max( elem.body[ scrollProp ], doc[ scrollProp ], elem.body[ offsetProp ], doc[ offsetProp ] ); } // Get width or height on the element if ( value === undefined ) { orig = jQuery.css( elem, type ); ret = parseFloat( orig ); return jQuery.isNumeric( ret ) ? ret : orig; } // Set the width or height on the element jQuery( elem ).css( type, value ); }, type, value, arguments.length, 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 );
src/Task/TaskList.js
mkermani144/wanna
import React, { Component } from 'react'; import Subheader from 'material-ui/Subheader'; import Divider from 'material-ui/Divider'; import Snackbar from 'material-ui/Snackbar'; import CSSTransitionGroup from 'react-addons-css-transition-group'; import { red500, green500, blue500, purple500, } from 'material-ui/styles/colors'; import Task from './Task'; import EditTaskDialog from './EditTaskDialog'; import classify from './lib/classify'; import cumulate from './lib/cumulate'; import './TaskList.css'; import './Animations.css'; import { navMiniWidth, navExpandedWidth, transitionEnterTimeout, transitionLeaveTimeout, } from '../lib/constants'; class TaskList extends Component { state = { taskDialogOpen: false, snackbarOpen: false, snackbarMessage: '', index: -1, current: 5, }; componentDidMount = () => { this.interval = setInterval(() => this.renderMore(), 0); } componentWillUnmount = () => { clearInterval(this.interval); } handleRequestTaskDialogClose = () => { this.setState({ taskDialogOpen: false, }); } handleRequestTaskDialogOpen = (index) => { this.setState({ taskDialogOpen: true, index, }); } handleRequestTaskEdit = (taskInfo) => { this.props.editTask(this.state.index, { task: taskInfo.task, }); this.handleRequestTaskDialogClose(); } handleRequestTaskDelete = (index) => { this.props.deleteTask(index); } handleRequestTaskDo = (index) => { this.props.doTask(index); } handleRequestSnackbarOpen = (message) => { this.setState({ snackbarOpen: true, snackbarMessage: message, }); this.props.raiseFab(); } handleRequestSnackbarClose = () => { this.setState({ snackbarOpen: false, snackbarMessage: '', }); this.props.lowerFab(); } handleUndo = () => { this.props.undo(); this.handleRequestSnackbarClose(); } renderMore = () => { if (this.state.current === this.props.tasks.length - 1) { clearInterval(this.interval); } else { this.setState(prev => ({ current: prev.current + 1 })); } } render() { const styles = { overdue: { color: red500, marginTop: 20, cursor: 'default', }, open: { color: green500, marginTop: 20, cursor: 'default', }, notYet: { color: blue500, marginTop: 20, cursor: 'default', }, done: { color: purple500, marginTop: 20, cursor: 'default', }, }; const classifiedTasks = classify(this.props.tasks); const marginStyles = { expanded: { marginLeft: navExpandedWidth, }, mini: { marginLeft: navMiniWidth, }, }; const dividerStyle = { marginTop: 12, }; const cumulativeFrequencies = cumulate(classifiedTasks); return ( <div className="TaskList" style={ this.props.sidebarExpanded ? marginStyles.expanded : marginStyles.mini } > <CSSTransitionGroup className="transition-container" transitionName="tasks-empty-state" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {!this.props.tasks.length && <div className="tasks-empty-state" > <h1> All done </h1> <h4> You have no tasks </h4> </div> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-header" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && <Subheader style={styles.overdue}>Overdue ({classifiedTasks.overdue.length})</Subheader> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > { classifiedTasks.overdue.map((task, index) => (index > this.state.current ? <div key={task.id} className="Task" /> : <Task color={task.color} signal={task.signal} text={task.task} estimation={task.estimation} repeat={`${task.repetition} days`} key={task.id} index={task.index} onRequestEditTaskOpen={this.handleRequestTaskDialogOpen} onRequestDelete={this.handleRequestTaskDelete} onRequestDo={this.handleRequestTaskDo} onRequestSnackbar={this.handleRequestSnackbarOpen} /> )) } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-divider" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && <Divider style={dividerStyle} /> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-header" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && <Subheader style={styles.open}>Open ({classifiedTasks.open.length})</Subheader> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > { classifiedTasks.open.map((task, index) => (index > this.state.current + cumulativeFrequencies.open ? <div key={task.id} className="Task" /> : <Task color={task.color} signal={task.signal} text={task.task} estimation={task.estimation} due={task.due} repeat={`${task.repetition} days`} key={task.id} index={task.index} onRequestEditTaskOpen={this.handleRequestTaskDialogOpen} onRequestDelete={this.handleRequestTaskDelete} onRequestDo={this.handleRequestTaskDo} onRequestSnackbar={this.handleRequestSnackbarOpen} /> )) } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-divider" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && <Divider style={dividerStyle} /> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-header" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && this.props.showNotYetTasks && <Subheader style={styles.notYet}>Not Yet ({classifiedTasks.notYet.length})</Subheader> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.showNotYetTasks && classifiedTasks.notYet.map((task, index) => (index > this.state.current + cumulativeFrequencies.notYet ? <div key={task.id} className="Task" /> : <Task color={task.color} signal={task.signal} text={task.task} estimation={task.estimation} due={task.due} repeat={`${task.repetition} days`} key={task.id} index={task.index} onRequestEditTaskOpen={this.handleRequestTaskDialogOpen} onRequestDelete={this.handleRequestTaskDelete} onRequestDo={this.handleRequestTaskDo} onRequestSnackbar={this.handleRequestSnackbarOpen} /> )) } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-divider" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && this.props.showNotYetTasks && <Divider style={dividerStyle} /> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-header" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && <Subheader style={styles.done}>Done ({classifiedTasks.done.length})</Subheader> } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > { classifiedTasks.done.map((task, index) => (index > this.state.current + cumulativeFrequencies.done ? <div key={task.id} className="Task" /> : <Task color={task.color} signal={task.signal} text={task.task} estimation={task.estimation} repeat={`${task.repetition} days`} key={task.id} index={task.index} onRequestDelete={this.handleRequestTaskDelete} onRequestSnackbar={this.handleRequestSnackbarOpen} done /> )) } </CSSTransitionGroup> <CSSTransitionGroup transitionName="task-divider" transitionEnterTimeout={transitionEnterTimeout} transitionLeaveTimeout={transitionLeaveTimeout} > {this.props.tasks.length && <Divider style={dividerStyle} /> } </CSSTransitionGroup> <EditTaskDialog onRequestClose={this.handleRequestTaskDialogClose} onRequestEdit={this.handleRequestTaskEdit} task={this.props.tasks[this.state.index] ? this.props.tasks[this.state.index].task : null } open={this.state.taskDialogOpen} /> <Snackbar open={this.state.snackbarOpen} message={this.state.snackbarMessage} autoHideDuration={3000} action="undo" onActionClick={this.handleUndo} onRequestClose={this.handleRequestSnackbarClose} /> </div> ); } } export default TaskList;
src/main.js
maxigimenez/figme
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import SearchReducer from './reducers/search'; import Search from './components/search/search'; import List from './components/list/list'; import Pagination from './components/pagination/pagination'; class Figme extends Component { render () { return <div> <Search store={store} /> <List store={store} /> <Pagination store={store} /> </div> } } const store = createStore(SearchReducer, applyMiddleware(thunk)); ReactDOM.render( <Provider store={store}> <Figme /> </Provider>, document.getElementById('figme-app') );
src/interface/news/Page.js
ronaldpereira/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import articles from 'articles'; import DocumentTitle from 'interface/DocumentTitle'; import ArticleLoader from './ArticleLoader'; import './News.scss'; class Page extends React.PureComponent { static propTypes = { articleId: PropTypes.string.isRequired, }; renderBreadcrumbs(breadcrumbs) { return breadcrumbs.map((item, index) => ( <React.Fragment key={index}> {item} {index !== (breadcrumbs.length - 1) && ( <> {' '}&gt;{' '} </> )} </React.Fragment> )); } render() { const fileName = articles[this.props.articleId]; const breadcrumbs = [ <Link to="/"> Home </Link>, <Link to="/#Announcements"> Announcements </Link>, ]; return ( <div className="container news"> <ArticleLoader key={fileName} fileName={fileName} > {({ article, showLoader }) => showLoader ? ( <> {this.renderBreadcrumbs(breadcrumbs)}<br /><br /> <div className="spinner" style={{ fontSize: 5 }} /> <DocumentTitle title="News" /> </> ) : ( <> {this.renderBreadcrumbs([ ...breadcrumbs, article.props.title, ])}<br /><br /> {article} <DocumentTitle title={article.props.title} /> </> )} </ArticleLoader> </div> ); } } export default Page;
src/error/index.js
crosslandwa/chippanfire-site
import React from 'react' import PageTemplate from '../PageTemplate' const Error = props => ( <PageTemplate> <h1 className="cpf-header">Not Found</h1> <p>Oh no! What you're looking for is not here. Maybe you followed an old link.</p> <p>Try using the navigation above to find what you were after...</p> <p id="redirect-suggestion"></p> <script dangerouslySetInnerHTML={{ __html: staticJs }}></script> </PageTemplate> ) const staticJs = ` const contains = path => tests => !!tests.filter(function(t) { return path.indexOf(t) != -1 }).length function lookingFor(href) { var urlContains = contains(href.toLowerCase()); var suggestedName; var suggestHref; switch (true) { case urlContains(['carson', 'brent', 'kilc', 'socco', 'chico', 'music']): suggestHref = 'index.html#music' suggestedName = 'music' break; case urlContains(['device', 'kmk', 'metro', 'midi', 'miniak', 'modulo', 'push', 'snap', 'soft', 'where']): suggestHref = 'index.html#software' suggestedName = 'software' break; case urlContains(['cont']): suggestHref = 'index.html#contact' suggestedName = 'contact' break; } if (suggestHref) { document.getElementById('redirect-suggestion').innerHTML = '...or were looking for <a class="cpf-link" href="' + suggestHref + '">' + suggestedName + '</a>?'; } } window.addEventListener('load', function () { lookingFor(window.location.href); })` export default Error
src/destinations/Slides.js
RoyalIcing/gateau
import R from 'ramda' import React from 'react' import seeds, { Seed } from 'react-seeds' import { Spectacle, Deck, Slide, Text } from 'spectacle' import * as Vanilla from './Vanilla' import { renderTreeUsing } from './render' const text = (tag, mentions, text) => ( <Text children={ text } /> ) const elementRendererForTags = R.cond([ // [ R.has('field'), R.curry(Vanilla.field) ], // [ R.has('button'), R.curry(Vanilla.button) ], // [ R.has('cta'), R.curry(Vanilla.cta) ], // [ R.has('image'), R.curry(Vanilla.image) ], // [ R.has('video'), R.curry(Vanilla.video) ], [ R.has('text'), R.curry(text) ], // [ R.has('swatch'), R.curry(Vanilla.swatch) ], // [ R.has('nav'), R.curry(Vanilla.nav) ], // [ R.has('columns'), R.curry(Vanilla.columns) ], // [ R.has('list'), R.curry(Vanilla.list) ], [ R.T, R.curry(text) ] ]) const Section = React.createClass({ getDefaultProps() { return { transition: [ 'zoom' ] } }, render() { return ( <Slide { ...this.props } /> ) } }) const Master = ({ children }) => ( <Spectacle> <Deck children={ children } transition={[ 'zoom' ]} /> </Spectacle> ) export const Preview = R.pipe( renderTreeUsing({ elementRendererForTags, Section: Slide, Master: Master }) ) export const title = 'Slides' export function head() { return ( <head> </head> ) }
frontend/src/javascripts/stores/TrashStore.js
funaota/notee
import React from 'react'; import assign from 'object-assign'; import request from 'superagent'; var EventEmitter = require('events').EventEmitter; // notee import NoteeDispatcher from '../dispatcher/NoteeDispatcher'; import Constants from '../constants/NoteeConstants'; // utils import EventUtil from '../utils/EventUtil'; var TrashStore = assign({}, EventEmitter.prototype, { loadTrashes: function(model_name, callback) { request.get('/notee/api/trashes?model=' + model_name, (err, res) => { if(err){return;} if(!res.body){return;} callback(res.body.trashes); }); } }); function trash_update(id, model_name) { request .put("/notee/api/trashes/" + id) .send({model: model_name}) .end(function(err, res){ if(err || !res.body){ EventUtil.emitChange(Constants.TRASH_UPDATE_FAILED); return false; } EventUtil.emitChange(Constants.TRASH_UPDATE); }) } NoteeDispatcher.register(function(action) { switch(action.type) { case Constants.TRASH_UPDATE: trash_update(action.content_id, action.model_name); break; } }); module.exports = TrashStore;
sites/default/files/js/simplemenu-d9256fda96c0b8eaa8e20bcfad057096.js
condesan/camino
var simplemenu="\x3cdiv class=\"simplemenu-block\"\x3e\x3cul class=\"menu clear-block\" id=\"simplemenu\"\x3e\x3cli class=\"expanded first\" id=\"simplemenu-li-0\"\x3e\x3ca name=\"menu-id-1\"\x3eDevel module\x3c/a\x3e\x3cul class=\"menu\"0\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-146\"\x3e\x3ca href=\"/camino/admin/settings/devel\"\x3eDevel settings\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-145\"\x3e\x3ca href=\"/camino/admin/reports/status/run-cron\"\x3eEjecutar cron\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-172\"\x3e\x3ca href=\"/camino/devel/cache/clear?destination=calendar%2F2010-10-24\" title=\"Clear the CSS cache and all database cache tables which store page, node, theme and variable caches.\"\x3eEmpty cache\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-153\"\x3e\x3ca href=\"/camino/devel/php\" title=\"Execute some PHP code\"\x3eExecute PHP Code\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-154\"\x3e\x3ca href=\"/camino/devel/reference\" title=\"View a list of currently defined user functions with documentation links.\"\x3eFunction reference\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-156\"\x3e\x3ca href=\"/camino/devel/elements\" title=\"View the active form/render elements for this site.\"\x3eHook_elements()\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-180\"\x3e\x3ca href=\"/camino/devel/node_access/summary\"\x3eNode_access summary\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-158\"\x3e\x3ca href=\"/camino/devel/phpinfo\" title=\"View your server\x26#039;s PHP configuration\"\x3ePHPinfo()\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-184\"\x3e\x3ca href=\"/camino/devel/menu/reset?destination=calendar%2F2010-10-24\" title=\"Rebuild menu based on hook_menu() and revert any custom changes. All menu items return to their default settings.\"\x3eRebuild menus\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-160\"\x3e\x3ca href=\"/camino/devel/reinstall?destination=calendar%2F2010-10-24\" title=\"Run hook_uninstall() and then hook_install() for a given module.\"\x3eReinstall modules\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-161\"\x3e\x3ca href=\"/camino/devel/session\" title=\"List the contents of $_SESSION.\"\x3eSession viewer\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-187\"\x3e\x3ca href=\"/camino/devel/theme/registry\" title=\"View a list of available theme functions across the whole site.\"\x3eTheme registry\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-164\"\x3e\x3ca href=\"/camino/devel/variable?destination=calendar%2F2010-10-24\" title=\"Edit and delete site variables.\"\x3eVariable editor\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-372\"\x3e\x3ca href=\"/camino/geonames/docs\"\x3eGeonames Docs\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-21\"\x3e\x3ca href=\"/camino/user/me\"\x3eMi cuenta\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-11\"\x3e\x3ca name=\"menu-id-2\"\x3eCrear contenido\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-11\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-112\"\x3e\x3ca href=\"/camino/node/add/story\" title=\"Un artículo, con estructura similar a una página, es ideal para crear y mostrar contenido que informa a los visitantes del sitio. Notas de prensa, anuncios del sitio, y entradas informales de un blog pueden ser creadas con un artículo. Por defecto, un artículo aparece automáticamente en la página inicial del sitio, y permite recibir comentarios.\"\x3eArtículo\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-235\"\x3e\x3ca href=\"/camino/node/add/caminos\"\x3eCaminos\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-254\"\x3e\x3ca href=\"/camino/node/add/etapas\"\x3eEtapas\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-355\"\x3e\x3ca href=\"/camino/node/add/experiencias\"\x3eExperiencias\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-271\"\x3e\x3ca href=\"/camino/node/add/galeria\"\x3eGalería de Fotos\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-610\"\x3e\x3ca href=\"/camino/node/add/logos\" title=\"Agregar logo\"\x3eLogos\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-430\"\x3e\x3ca href=\"/camino/node/add/panel\" title=\"A panel layout broken up into rows and columns.\"\x3ePanel\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-261\"\x3e\x3ca href=\"/camino/node/add/usuarios\"\x3ePerfil\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-276\"\x3e\x3ca href=\"/camino/node/add/pizarra\"\x3ePizarra\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-114\"\x3e\x3ca href=\"/camino/node/add/page\" title=\"Una página, similar en forma y contenido a un artículo, es un método sencillo de crear y mostrar información que no suele cambiar, como una sección \x26quot;Acerca de\x26quot; en un sitio web. Por defecto, una página no permite comentarios de visitantes y no es promovida a la portada del sitio.\"\x3ePágina\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-266\"\x3e\x3ca href=\"/camino/node/add/recursos\"\x3eRecursos\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-2\"\x3e\x3ca name=\"menu-id-3\"\x3eAdministrar\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-2\"\x3e\x3cli class=\"expanded first\" id=\"simplemenu-li-10\"\x3e\x3ca name=\"menu-id-4\"\x3eAdministración de contenido\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-10\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-480\"\x3e\x3ca href=\"/camino/admin/content/backup_migrate\" title=\"Backup/restore your database or migrate data to or from another Drupal site.\"\x3eBackup and Migrate\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-27\"\x3e\x3ca href=\"/camino/admin/content/comment\" title=\"Lista y edita los comentarios del sitio y la cola de moderación de comentarios.\"\x3eComentarios\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-28\"\x3e\x3ca href=\"/camino/admin/content/node\" title=\"Ver, editar y borrar el contenido de su sitio.\"\x3eContenido\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-245\"\x3e\x3ca href=\"/camino/admin/content/date/tools\" title=\"Herramientas para importar y autocrear fechas y calendarios.\"\x3eDate Tools\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-324\"\x3e\x3ca href=\"/camino/admin/content/emfield\" title=\"Configure Embedded Media Field: Allow content types to use various 3rd party providers, enter API keys, etc.\"\x3eEmbedded Media Field configuration\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-42\"\x3e\x3ca href=\"/camino/admin/content/node-settings\" title=\"Controla el comportamiento del envío, como la longitud del avance, la necesidad de una vista preliminar antes de enviar y el número de envíos en la página principal.\"\x3eOpciones de envío\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-43\"\x3e\x3ca href=\"/camino/admin/content/rss-publishing\" title=\"Configura el número de ítems por origen y si los orígenes deben contener los títulos, los avances o el texto completo.\"\x3ePublicación RSS\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-514\"\x3e\x3ca href=\"/camino/admin/content/taxonomy_manager\" title=\"Administer vocabularies with the Taxonomy Manager\"\x3eTaxonomy Manager\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-95\"\x3e\x3ca href=\"/camino/admin/content/taxonomy\" title=\"Gestionar el etiquetado, categorización y clasificación de su contenido\"\x3eTaxonomía\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-29\"\x3e\x3ca href=\"/camino/admin/content/types\" title=\"Gestiona los envíos por tipo de contenido, incluyendo el estado predefinido, la promoción a la página principal, etc.\"\x3eTipos de contenido\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-17\"\x3e\x3ca name=\"menu-id-5\"\x3eConstrucción del sitio\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-17\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-127\"\x3e\x3ca href=\"/camino/admin/build/path\" title=\"Cambia las rutas de URLs del sitio mediante alias.\"\x3eAlias de URL\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-25\"\x3e\x3ca href=\"/camino/admin/build/block\" title=\"Configura qué bloques de contenido aparecen en las zonas laterales del sitio y de otras regiones.\"\x3eBloques\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-426\"\x3e\x3ca href=\"/camino/admin/build/ctools-rulesets\" title=\"Add, edit or delete custom access rulesets for use with Panels and other systems that utilize CTools content plugins.\"\x3eCustom access rulesets\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-693\"\x3e\x3ca href=\"/camino/admin/build/custom_breadcrumbs\" title=\"Add custom breadcrumb trails for content types.\"\x3eCustom breadcrumbs\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-427\"\x3e\x3ca href=\"/camino/admin/build/ctools-content\" title=\"Add, edit or delete custom content panes.\"\x3eCustom content panes\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-491\"\x3e\x3ca href=\"/camino/admin/build/features\" title=\"Manage features.\"\x3eFeatures\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-170\"\x3e\x3ca href=\"/camino/admin/build/contact\" title=\"Crea un formulario de contacto del sistema y configura categorías para que las utilice el formulario.\"\x3eFormulario de contacto\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-179\"\x3e\x3ca href=\"/camino/admin/build/imagecache\" title=\"Administer imagecache presets and actions.\"\x3eImageCache\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-38\"\x3e\x3ca name=\"menu-id-6\"\x3eMenús\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-38\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-90\"\x3e\x3ca href=\"/camino/admin/build/menu-customize/primary-links\"\x3eEnlaces primarios\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-91\"\x3e\x3ca href=\"/camino/admin/build/menu-customize/secondary-links\"\x3eEnlaces secundarios\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-629\"\x3e\x3ca href=\"/camino/admin/build/menu-customize/menu-mi-menu\"\x3eMi menu\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-89\"\x3e\x3ca href=\"/camino/admin/build/menu-customize/navigation\"\x3eNavegación\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-428\"\x3e\x3ca href=\"/camino/admin/build/mini-panels\" title=\"Add, edit or delete mini panels, which can be used as blocks or content panes in other panels.\"\x3eMini panels\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-39\"\x3e\x3ca href=\"/camino/admin/build/modules\" title=\"Habilitar o deshabilitar módulos adicionales para su sitio.\"\x3eMódulos\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-431\"\x3e\x3ca href=\"/camino/admin/build/panels\" title=\"Get a bird\x26#039;s eye view of items related to Panels.\"\x3ePanels\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-429\"\x3e\x3ca href=\"/camino/admin/build/pages\" title=\"Add, edit and remove overridden system pages and user defined pages from the system.\"\x3ePáginas\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-432\"\x3e\x3ca href=\"/camino/admin/build/stylizer\" title=\"Add, edit or delete stylizer styles.\"\x3eStylizer\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-49\"\x3e\x3ca href=\"/camino/admin/build/themes\" title=\"Cambia el tema que usa el sitio o permite que los usuarios lo elijan.\"\x3eTemas\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-99\"\x3e\x3ca href=\"/camino/admin/build/translate\" title=\"Traduce la interfaz interna y opcionalmente otro texto.\"\x3eTraducir interfaz\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-197\"\x3e\x3ca href=\"/camino/admin/build/views\" title=\"Views are customized lists of content on your system; they are highly configurable and give you control over how lists of content are presented.\"\x3eViews\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-373\"\x3e\x3ca name=\"menu-id-7\"\x3eGoogle Maps Tools\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-373\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-378\"\x3e\x3ca href=\"/camino/admin/gmaps/icons\" title=\"Manage the icons defined for your site.\"\x3eIcons\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-380\"\x3e\x3ca href=\"/camino/admin/gmaps/maps\" title=\"Manage the map presets defined for your site.\"\x3eMap presets\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-381\"\x3e\x3ca href=\"/camino/admin/gmaps/static-maps\" title=\"Manage the static map presets defined for your site.\"\x3eStatic map presets\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-18\"\x3e\x3ca name=\"menu-id-8\"\x3eConfiguración del sitio\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-18\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-634\"\x3e\x3ca href=\"/camino/admin/settings/me\" title=\"Configure the \x26#039;me\x26#039; aliases, and how they\x26#039;re matched.\"\x3e\x26#039;Me\x26#039; Aliases\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-23\"\x3e\x3ca href=\"/camino/admin/settings/actions\" title=\"Gestionar las acciones definidas para su sitio.\"\x3eAcciones\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-327\"\x3e\x3ca href=\"/camino/admin/settings/audiofield\" title=\"Configure Audiofield.\"\x3eAudio Field\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-241\"\x3e\x3ca href=\"/camino/admin/settings/date_popup\" title=\"Allows the user to configure the Date Popup settings.\"\x3eDate Popup Configuration\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-171\"\x3e\x3ca href=\"/camino/admin/settings/devel\" title=\"Helper functions, pages, and blocks to assist Drupal developers. The devel blocks can be managed via the block administration page.\"\x3eDevel settings\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-30\"\x3e\x3ca href=\"/camino/admin/settings/date-time\" title=\"Opciones para la visualización de la fecha y de la hora, así como la zona horaria predefinida del sistema.\"\x3eFecha y hora\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-36\"\x3e\x3ca href=\"/camino/admin/settings/filters\" title=\"Configurar cómo se procesa el contenido introducido por los usuarios, incluidas las etiquetas HTML permitidas. También permite activar formatos de entrada proporcionados por módulos.\"\x3eFormatos de entrada\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-376\"\x3e\x3ca href=\"/camino/admin/settings/geonames\" title=\"GeoNames Configuration.\"\x3eGeoNames\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-377\"\x3e\x3ca href=\"/camino/admin/settings/gmaps\" title=\"Configure GMaps Core settings.\"\x3eGoogle Maps Tools\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-93\"\x3e\x3ca href=\"/camino/admin/settings/language\" title=\"Configurar los idiomas para el contenido y la interfaz de usuario.\"\x3eIdiomas\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-178\"\x3e\x3ca href=\"/camino/admin/settings/imageapi\" title=\"Configure ImageAPI.\"\x3eImageAPI\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-46\"\x3e\x3ca href=\"/camino/admin/settings/site-information\" title=\"Cambiar la información básica del sitio, tal como el nombre del sitio, eslogan, dirección de correo electrónico, misión, portada y más.\"\x3eInformación del sitio\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-33\"\x3e\x3ca href=\"/camino/admin/settings/error-reporting\" title=\"Controla cómo gestiona Drupal los errores como los 403/404, así como los informes de error de PHP.\"\x3eInformar de errores\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-35\"\x3e\x3ca href=\"/camino/admin/settings/image-toolkit\" title=\"Elija qué juego de herramientas de imágenes quiere usar, si ha instalado otros juegos de herramientas de imágenes.\"\x3eJuego de herramientas de imágenes\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-47\"\x3e\x3ca href=\"/camino/admin/settings/site-maintenance\" title=\"Desactivar el sitio por cuestiones de mantenimiento o reactivarlo.\"\x3eMantenimiento del sitio\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-542\"\x3e\x3ca href=\"/camino/admin/settings/media_youtube\" title=\"Administer the Media: YouTube module.\"\x3eMedia: YouTube\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-368\"\x3e\x3ca href=\"/camino/admin/settings/module_filter\" title=\"Configure settings for Module Filter.\"\x3eModule filter\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-304\"\x3e\x3ca href=\"/camino/admin/settings/search\" title=\"Configura las opciones de relevancia para la búsqueda y otras opciones de indexación\"\x3eOpciones de búsqueda\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-183\"\x3e\x3ca name=\"menu-id-9\"\x3ePerformance logging\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-183\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-200\"\x3e\x3ca href=\"/camino/admin/settings/performance_logging/apc_clear\" title=\"Clears performance statistics collected in APC.\"\x3eClear APC\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-202\"\x3e\x3ca href=\"/camino/admin/settings/performance_logging/memcache_clear\" title=\"Clears performance statistics collected in Memcache.\"\x3eClear Memcache\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-37\"\x3e\x3ca name=\"menu-id-10\"\x3eRegistro y alertas\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-37\"\x3e\x3cli class=\"leaf first last\" id=\"simplemenu-li-103\"\x3e\x3ca href=\"/camino/admin/settings/logging/dblog\" title=\"Configuración para registrar los mensajes de Drupal en la base de datos. Este es el método más común para los pequeños y medianos sitios de alojamiento compartido. Los registros se pueden ver desde las páginas de administrar.\"\x3eRegistro en base de datos\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-40\"\x3e\x3ca href=\"/camino/admin/settings/performance\" title=\"Activar o desactivar la caché de páginas para los usuarios anónimos y establecer las opciones de optimización del ancho de banda para CSS y JS.\"\x3eRendimiento\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-186\"\x3e\x3ca href=\"/camino/admin/settings/simplemenu\" title=\"Select the menu to display.\"\x3eSimpleMenu\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-34\"\x3e\x3ca href=\"/camino/admin/settings/file-system\" title=\"Le dice a Drupal dónde se deben almacenar los archivos y cómo debe accederse a ellos.\"\x3eSistema de archivos\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-488\"\x3e\x3ca href=\"/camino/admin/settings/tabs\" title=\"Configuration for tabs\"\x3eTabs\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-515\"\x3e\x3ca href=\"/camino/admin/settings/taxonomy_manager\" title=\"Advanced settings for the Taxonomy Manager\"\x3eTaxonomy Manager\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-24\"\x3e\x3ca href=\"/camino/admin/settings/admin\" title=\"Opciones de apariencia de las páginas de administración.\"\x3eTema de administración\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-26\"\x3e\x3ca href=\"/camino/admin/settings/clean-urls\" title=\"Activa o desactiva URLs limpias en su sitio.\"\x3eURLs limpios\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-379\"\x3e\x3ca href=\"/camino/admin/settings/location\" title=\"Settings for Location module\"\x3eUbicación\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-691\"\x3e\x3ca href=\"/camino/admin/settings/wysiwyg\" title=\"Configure client-side editors.\"\x3eWysiwyg\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-685\"\x3e\x3ca href=\"/camino/admin/settings/jquery_update\" title=\"Configure settings for jQuery Update module.\"\x3ejQuery Update\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-20\"\x3e\x3ca name=\"menu-id-11\"\x3eAdministración de usuario\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-20\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-50\"\x3e\x3ca href=\"/camino/admin/user/settings\" title=\"Configura el comportamiento predefinido de los usuarios, incluyendo los requisitos del registro, los correos y las imágenes.\"\x3eOpciones de usuario\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-126\"\x3e\x3ca href=\"/camino/admin/user/profile\" title=\"Crea campos personalizables para sus usuarios.\"\x3ePerfiles\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-41\"\x3e\x3ca href=\"/camino/admin/user/permissions\" title=\"Determina el acceso a las características mediante selección de permisos para roles.\"\x3ePermisos\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-22\"\x3e\x3ca href=\"/camino/admin/user/rules\" title=\"Enliste y cree reglas para prohibir nombres de usuario, direcciones de correo y direcciones de IP.\"\x3eReglas de acceso\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-45\"\x3e\x3ca href=\"/camino/admin/user/roles\" title=\"Lista, edita o añade roles de usuarios.\"\x3eRoles\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-51\"\x3e\x3ca href=\"/camino/admin/user/user\" title=\"Lista, añade y edita usuarios.\"\x3eUsuarios\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-155\"\x3e\x3ca name=\"menu-id-12\"\x3eGenerate items\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-155\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-175\"\x3e\x3ca href=\"/camino/admin/generate/taxonomy\" title=\"Generate a given number of vocabularies and terms. Optionally delete current categories.\"\x3eGenerate categories\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-176\"\x3e\x3ca href=\"/camino/admin/generate/content\" title=\"Generate a given number of nodes and comments. Optionally delete current items.\"\x3eGenerate content\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-177\"\x3e\x3ca href=\"/camino/admin/generate/user\" title=\"Generate a given number of users. Optionally delete current users.\"\x3eGenerate users\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-16\"\x3e\x3ca name=\"menu-id-13\"\x3eInformes\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-16\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-94\"\x3e\x3ca href=\"/camino/admin/reports/dblog\" title=\"Ver los eventos registrados recientemente.\"\x3eEntradas recientes del registro\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-305\"\x3e\x3ca href=\"/camino/admin/reports/search\" title=\"Ver las frases más populares en las búsquedas.\"\x3eFrases principales en las búsquedas\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-181\"\x3e\x3ca href=\"/camino/admin/reports/performance_logging_details\" title=\"View detailed, per page, performance logs: page generation times and memory usage.\"\x3ePerformance Logs: Details\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-182\"\x3e\x3ca href=\"/camino/admin/reports/performance_logging_summary\" title=\"View summary performance logs: page generation times and memory usage.\"\x3ePerformance Logs: Summary\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-97\"\x3e\x3ca href=\"/camino/admin/reports/access-denied\" title=\"Ver los errores de \x26quot;acceso denegado\x26quot; (403).\"\x3ePrincipales errores de \x26quot;acceso denegado\x26quot;\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-98\"\x3e\x3ca href=\"/camino/admin/reports/page-not-found\" title=\"Ver los errores de \x26quot;página no encontrada\x26quot; (404).\"\x3ePrincipales errores de \x26quot;página no encontrada\x26quot;\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-189\"\x3e\x3ca href=\"/camino/admin/reports/referrers\" title=\"Ve los referentes principales.\"\x3eReferentes principales\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-185\"\x3e\x3ca href=\"/camino/admin/reports/hits\" title=\"Ve las páginas que se han visitado recientemente.\"\x3eVisitas recientes\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-188\"\x3e\x3ca href=\"/camino/admin/reports/pages\" title=\"Ve las páginas que se visitan con frecuencia.\"\x3ePáginas principales\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-190\"\x3e\x3ca href=\"/camino/admin/reports/visitors\" title=\"Ver los visitantes que visitan muchas páginas.\"\x3eVisitantes principales\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-169\"\x3e\x3ca href=\"/camino/admin/reports/settings\" title=\"Controla los detalles de qué se registra y cómo se hace en el sitio.\"\x3eOpciones del registro de acceso\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-113\"\x3e\x3ca href=\"/camino/admin/reports/updates\" title=\"Obtenga un informe de estado acerca de las actualizaciones disponibles de los módulos y temas visuales instalados.\"\x3eActualizaciones disponibles\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-48\"\x3e\x3ca href=\"/camino/admin/reports/status\" title=\"Obtiene un informe del estado de operación de su sitio y de cualquier problema detectado.\"\x3eInforme de estado\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"expanded\" id=\"simplemenu-li-588\"\x3e\x3ca name=\"menu-id-14\"\x3eRules\x3c/a\x3e\x3cul class=\"menu\" id=\"simplemenu-ul-588\"\x3e\x3cli class=\"leaf first\" id=\"simplemenu-li-594\"\x3e\x3ca href=\"/camino/admin/rules/trigger\" title=\"Customize your site by configuring rules that are evaluated on events.\"\x3eTriggered rules\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-592\"\x3e\x3ca href=\"/camino/admin/rules/rule_sets\" title=\"Create and manage rule sets.\"\x3eRule sets\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-591\"\x3e\x3ca href=\"/camino/admin/rules/ie\" title=\"Export your rules as text or import rules.\"\x3eImport / Export\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-590\"\x3e\x3ca href=\"/camino/admin/rules/forms\" title=\"Configure Rules forms events.\"\x3eForm events\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-593\"\x3e\x3ca href=\"/camino/admin/rules/settings\" title=\"Set display options, show/hide Rules messages.\"\x3eOpciones\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"leaf\" id=\"simplemenu-li-297\"\x3e\x3ca href=\"/camino/admin/advanced_help\"\x3eAdvanced help\x3c/a\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-15\"\x3e\x3ca href=\"/camino/admin/help\"\x3eAyuda\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/li\x3e\n\x3cli class=\"leaf last\" id=\"simplemenu-li-4\"\x3e\x3ca href=\"/camino/logout\"\x3eTerminar sesión\x3c/a\x3e\x3c/li\x3e\n\x3c/ul\x3e\x3c/div\x3e";
src/components/SidebarMenuProfile/SidebarMenuProfile.js
dialogs/dialog-web-components
/* * Copyright 2019 dialog LLC <info@dlg.im> * @flow */ import type { AvatarPlaceholder, UserStatusType } from '@dlghq/dialog-types'; import React, { PureComponent } from 'react'; import classNames from 'classnames'; import Avatar from '../Avatar/Avatar'; import { PeerInfoTitle } from '../PeerInfoTitle/PeerInfoTitle'; import UserStatus from '../UserStatus/UserStatus'; import styles from './SidebarMenuProfile.css'; type Props = { className?: string, name: string, avatar: ?string, placeholder: AvatarPlaceholder, status: UserStatusType, }; class SidebarMenuProfile extends PureComponent<Props> { render() { const { name, avatar, placeholder, status } = this.props; const className = classNames(styles.container, this.props.className); return ( <div className={className}> <Avatar size={42} title={name} image={avatar} placeholder={placeholder} className={styles.avatar} /> <div className={styles.info}> <PeerInfoTitle title={name} className={styles.title} emojiSize={16} /> <UserStatus status={status} className={styles.status} dotClassName={styles.dot} statusClassName={styles.status} /> </div> </div> ); } } export default SidebarMenuProfile;
src/index.js
tomvej/redux-starter
import React from 'react'; import {render} from 'react-dom'; import {hot} from 'react-hot-loader'; import Root from './Root'; const App = hot(module)(Root); render( <App />, document.getElementById('content'), );
src/svg-icons/action/settings-input-svideo.js
andrejunges/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSettingsInputSvideo = (props) => ( <SvgIcon {...props}> <path d="M8 11.5c0-.83-.67-1.5-1.5-1.5S5 10.67 5 11.5 5.67 13 6.5 13 8 12.33 8 11.5zm7-5c0-.83-.67-1.5-1.5-1.5h-3C9.67 5 9 5.67 9 6.5S9.67 8 10.5 8h3c.83 0 1.5-.67 1.5-1.5zM8.5 15c-.83 0-1.5.67-1.5 1.5S7.67 18 8.5 18s1.5-.67 1.5-1.5S9.33 15 8.5 15zM12 1C5.93 1 1 5.93 1 12s4.93 11 11 11 11-4.93 11-11S18.07 1 12 1zm0 20c-4.96 0-9-4.04-9-9s4.04-9 9-9 9 4.04 9 9-4.04 9-9 9zm5.5-11c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm-2 5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5z"/> </SvgIcon> ); ActionSettingsInputSvideo = pure(ActionSettingsInputSvideo); ActionSettingsInputSvideo.displayName = 'ActionSettingsInputSvideo'; ActionSettingsInputSvideo.muiName = 'SvgIcon'; export default ActionSettingsInputSvideo;
src/svg-icons/av/games.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvGames = (props) => ( <SvgIcon {...props}> <path d="M15 7.5V2H9v5.5l3 3 3-3zM7.5 9H2v6h5.5l3-3-3-3zM9 16.5V22h6v-5.5l-3-3-3 3zM16.5 9l-3 3 3 3H22V9h-5.5z"/> </SvgIcon> ); AvGames = pure(AvGames); AvGames.displayName = 'AvGames'; AvGames.muiName = 'SvgIcon'; export default AvGames;
ajax/libs/vkui/4.25.2/cjs/components/Epic/ScrollSaver.min.js
cdnjs/cdnjs
"use strict";var _interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard").default;Object.defineProperty(exports,"__esModule",{value:!0}),exports.ScrollSaver=void 0;var _jsxRuntime=require("../../lib/jsxRuntime"),React=_interopRequireWildcard(require("react")),_ScrollContext=require("../AppRoot/ScrollContext"),_useIsomorphicLayoutEffect=require("../../lib/useIsomorphicLayoutEffect"),ScrollSaver=function(e){var r=e.children,t=e.initialScroll,o=e.saveScroll,e=React.useContext(_ScrollContext.ScrollContext),l=e.getScroll,c=e.scrollTo;return(0,_useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function(){return"number"==typeof t&&c(0,t),function(){return o(l().y)}},[]),(0,_jsxRuntime.createScopedElement)(React.Fragment,null,r)};exports.ScrollSaver=ScrollSaver;
examples/huge-apps/routes/Course/routes/Grades/components/Grades.js
barretts/react-router
import React from 'react'; class Grades extends React.Component { render () { var assignments = COURSES[this.props.params.courseId].assignments; return ( <div> <h3>Grades</h3> <ul> {assignments.map(assignment => ( <li key={assignment.id}>{assignment.grade} - {assignment.title}</li> ))} </ul> </div> ); } } export default Grades;
app/containers/PrimaryBlock/EditBlock.js
klpdotorg/tada-frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import get from 'lodash.get'; import isEmpty from 'lodash.isempty'; import FRC from 'formsy-react-components'; import Formsy from 'formsy-react'; import { Confirm } from '../Modal'; import { modifyBoundary, enableSubmitForm, disableSubmitForm, deleteBoundary, openDeleteBoundaryModal, toggleCreateClusterModal, } from '../../actions'; import { hasChildren, checkPermissions } from '../../utils'; const { Input } = FRC; class EditBlockForm extends Component { constructor() { super(); this.onClickSaveBlock = this.onClickSaveBlock.bind(this); this.onClickDeleteBlock = this.onClickDeleteBlock.bind(this); } onClickSaveBlock() { const myform = this.myform.getModel(); this.props.saveBlock(this.props.block.id, myform.BlockName); } onClickDeleteBlock() { const { blockNodeId, block, districtNodeId } = this.props; const params = { boundaryNodeId: blockNodeId, boundaryId: block.id, parentId: districtNodeId, }; this.props.deleteBlock(params); } render() { const { canDelete, block, hasPermissions, error } = this.props; return ( <div> {!hasPermissions ? ( <div className="alert alert-danger"> <i className="fa fa-lock fa-lg" aria-hidden="true" /> Insufficient Privileges. Only administrators can modify boundary details. </div> ) : ( <div /> )} {hasPermissions && !canDelete ? ( <div className="alert alert-info"> <i className="fa fa-info-circle fa-lg" aria-hidden="true" /> You cannot delete this boundary until its children are deleted </div> ) : ( <div /> )} <h4 className="text-primary col-md-10">Modify Details</h4> <button className="btn btn-orange pull-right" title="Add Cluster" onClick={this.props.toggleClusterModal} disabled={!hasPermissions} > Add Cluster </button> <div className="base-spacing-mid border-base" /> <Formsy.Form onValidSubmit={this.onClickSaveBlock} onValid={this.props.enableSubmitForm} onInvalid={this.props.disableSubmitForm} ref={(ref) => { this.myform = ref; }} disabled={!hasPermissions} > <div className="base-spacing-sm" /> {!isEmpty(error) ? ( <div className="alert alert-danger"> {Object.keys(error).map((key) => { const value = error[key]; return ( <p key={key}> <strong>{key}:</strong> {value[0]} </p> ); })} </div> ) : ( <span /> )} <Input name="BlockName" id="BlockName" value={block.name} label="Block :" type="text" placeholder="Please enter the block name" className="form-control" required validations="minLength:1" /> </Formsy.Form> <div className="col-md-8"> <button type="submit" disabled={!hasPermissions || !this.props.canSubmit} className="btn btn-primary padded-btn" onClick={this.onClickSaveBlock} > Save </button> <button type="submit" className="btn btn-primary padded-btn" disabled={!canDelete} onClick={() => { this.props.showConfirmModal(block.name); }} > Delete </button> <Confirm onYes={this.onClickDeleteBlock} /> </div> </div> ); } } EditBlockForm.propTypes = { error: PropTypes.object, hasPermissions: PropTypes.bool, block: PropTypes.object, districtNodeId: PropTypes.string, blockNodeId: PropTypes.string, canDelete: PropTypes.bool, canSubmit: PropTypes.bool, saveBlock: PropTypes.func, toggleClusterModal: PropTypes.func, deleteBlock: PropTypes.func, enableSubmitForm: PropTypes.func, disableSubmitForm: PropTypes.func, showConfirmModal: PropTypes.func, }; const mapStateToProps = (state, ownProps) => { const { blockNodeId } = ownProps; const { boundaries } = state; const { isAdmin } = state.profile; const block = get(boundaries.boundaryDetails, blockNodeId, {}); const hasPermissions = checkPermissions(isAdmin, state.userPermissions, [block.id]); return { block, canDelete: isAdmin && hasChildren(blockNodeId, boundaries), openConfirmModal: state.appstate.confirmModal, canSubmit: state.appstate.enableSubmitForm, hasPermissions, error: boundaries.editError, }; }; const EditBlock = connect(mapStateToProps, { toggleClusterModal: toggleCreateClusterModal, saveBlock: modifyBoundary, deleteBlock: deleteBoundary, enableSubmitForm, disableSubmitForm, showConfirmModal: openDeleteBoundaryModal, })(EditBlockForm); export { EditBlock };
app/javascript/mastodon/components/avatar_composite.js
NS-Kazuki/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { autoPlayGif } from '../initial_state'; export default class AvatarComposite extends React.PureComponent { static propTypes = { accounts: ImmutablePropTypes.list.isRequired, animate: PropTypes.bool, size: PropTypes.number.isRequired, }; static defaultProps = { animate: autoPlayGif, }; renderItem (account, size, index) { const { animate } = this.props; let width = 50; let height = 100; let top = 'auto'; let left = 'auto'; let bottom = 'auto'; let right = 'auto'; if (size === 1) { width = 100; } if (size === 4 || (size === 3 && index > 0)) { height = 50; } if (size === 2) { if (index === 0) { right = '2px'; } else { left = '2px'; } } else if (size === 3) { if (index === 0) { right = '2px'; } else if (index > 0) { left = '2px'; } if (index === 1) { bottom = '2px'; } else if (index > 1) { top = '2px'; } } else if (size === 4) { if (index === 0 || index === 2) { right = '2px'; } if (index === 1 || index === 3) { left = '2px'; } if (index < 2) { bottom = '2px'; } else { top = '2px'; } } const style = { left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%`, backgroundSize: 'cover', backgroundImage: `url(${account.get(animate ? 'avatar' : 'avatar_static')})`, }; return ( <div key={account.get('id')} style={style} /> ); } render() { const { accounts, size } = this.props; return ( <div className='account__avatar-composite' style={{ width: `${size}px`, height: `${size}px` }}> {accounts.take(4).map((account, i) => this.renderItem(account, accounts.size, i))} </div> ); } }
test/components/Test.js
loggur/provide-id-gen
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TestItem from './TestItem'; export default class Test extends Component { static propTypes = { genTestId: PropTypes.func.isRequired }; render() { return ( <div className="test"> <button onClick={this.props.genTestId}> Click me </button> <TestItem/> </div> ); } }
app/javascript/flavours/glitch/features/generic_not_found/index.js
im-in-space/mastodon
import React from 'react'; import Column from 'flavours/glitch/features/ui/components/column'; import MissingIndicator from 'flavours/glitch/components/missing_indicator'; const GenericNotFound = () => ( <Column> <MissingIndicator fullPage /> </Column> ); export default GenericNotFound;
src/Grid/GridItem.spec.js
collegepulse/material-react-components
/* eslint-env mocha */ import assert from 'assert'; import React from 'react'; import {createMount, createTest} from '../../test/utils'; import variables from '../variables'; import GridItem from './GridItem'; describe('GridItem', () => { let mount; beforeEach(() => { mount = createMount(); }); afterEach(() => { mount.cleanUp(); }); it('should render a GridItem', createTest(() => { const component = ( <GridItem xs={12}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100px', backgroundColor: variables.$black54, color: variables.$white }} > xs=12 </div> </GridItem> ); const wrapper = mount(component); assert(wrapper); })); });
app/javascript/flavours/glitch/features/domain_blocks/index.js
glitch-soc/mastodon
import React from 'react'; import { connect } from 'react-redux'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { debounce } from 'lodash'; import PropTypes from 'prop-types'; import LoadingIndicator from '../../components/loading_indicator'; import Column from '../ui/components/column'; import ColumnBackButtonSlim from '../../components/column_back_button_slim'; import DomainContainer from '../../containers/domain_container'; import { fetchDomainBlocks, expandDomainBlocks } from '../../actions/domain_blocks'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import ImmutablePureComponent from 'react-immutable-pure-component'; import ScrollableList from 'flavours/glitch/components/scrollable_list'; const messages = defineMessages({ heading: { id: 'column.domain_blocks', defaultMessage: 'Blocked domains' }, unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' }, }); const mapStateToProps = state => ({ domains: state.getIn(['domain_lists', 'blocks', 'items']), hasMore: !!state.getIn(['domain_lists', 'blocks', 'next']), }); export default @connect(mapStateToProps) @injectIntl class Blocks extends ImmutablePureComponent { static propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, hasMore: PropTypes.bool, domains: ImmutablePropTypes.list, intl: PropTypes.object.isRequired, multiColumn: PropTypes.bool, }; componentWillMount () { this.props.dispatch(fetchDomainBlocks()); } handleLoadMore = debounce(() => { this.props.dispatch(expandDomainBlocks()); }, 300, { leading: true }); render () { const { intl, domains, hasMore, multiColumn } = this.props; if (!domains) { return ( <Column> <LoadingIndicator /> </Column> ); } const emptyMessage = <FormattedMessage id='empty_column.domain_blocks' defaultMessage='There are no blocked domains yet.' />; return ( <Column bindToDocument={!multiColumn} icon='minus-circle' heading={intl.formatMessage(messages.heading)}> <ColumnBackButtonSlim /> <ScrollableList scrollKey='domain_blocks' onLoadMore={this.handleLoadMore} hasMore={hasMore} emptyMessage={emptyMessage} bindToDocument={!multiColumn} > {domains.map(domain => <DomainContainer key={domain} domain={domain} />, )} </ScrollableList> </Column> ); } }
ReactFlux/node_modules/react/lib/cx.js
wandarkaf/React-Bible
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule cx */ /** * This function is used to mark string literals representing CSS class names * so that they can be transformed statically. This allows for modularization * and minification of CSS class names. * * In static_upstream, this function is actually implemented, but it should * eventually be replaced with something more descriptive, and the transform * that is used in the main stack should be ported for use elsewhere. * * @param string|object className to modularize, or an object of key/values. * In the object case, the values are conditions that * determine if the className keys should be included. * @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ 'use strict'; var warning = require("./warning"); var warned = false; function cx(classNames) { if ("production" !== process.env.NODE_ENV) { ("production" !== process.env.NODE_ENV ? warning( warned, 'React.addons.classSet will be deprecated in a future version. See ' + 'http://fb.me/react-addons-classset' ) : null); warned = true; } if (typeof classNames == 'object') { return Object.keys(classNames).filter(function(className) { return classNames[className]; }).join(' '); } else { return Array.prototype.join.call(arguments, ' '); } } module.exports = cx;
app/javascript/mastodon/main.js
ambition-vietnam/mastodon
import * as registerPushNotifications from './actions/push_notifications'; import { default as Mastodon, store } from './containers/mastodon'; import React from 'react'; import ReactDOM from 'react-dom'; import ready from './ready'; const perf = require('./performance'); function main() { perf.start('main()'); if (window.history && history.replaceState) { const { pathname, search, hash } = window.location; const path = pathname + search + hash; if (!(/^\/web[$/]/).test(path)) { history.replaceState(null, document.title, `/web${path}`); } } ready(() => { const mountNode = document.getElementById('mastodon'); const props = JSON.parse(mountNode.getAttribute('data-props')); ReactDOM.render(<Mastodon {...props} />, mountNode); if (process.env.NODE_ENV === 'production') { // avoid offline in dev mode because it's harder to debug require('offline-plugin/runtime').install(); store.dispatch(registerPushNotifications.register()); } perf.stop('main()'); }); } export default main;
src/pages/404.js
prodigygod0209/prodigygod0209.github.io
import React from 'react' const NotFoundPage = () => ( <div> <h1>NOT FOUND</h1> <p>You just hit a route that doesn&#39;t exist... the sadness.</p> </div> ) export default NotFoundPage
ajax/libs/yui/3.7.1/datatable-body/datatable-body-coverage.js
chriszarate/cdnjs
if (typeof _yuitest_coverage == "undefined"){ _yuitest_coverage = {}; _yuitest_coverline = function(src, line){ var coverage = _yuitest_coverage[src]; if (!coverage.lines[line]){ coverage.calledLines++; } coverage.lines[line]++; }; _yuitest_coverfunc = function(src, name, line){ var coverage = _yuitest_coverage[src], funcId = name + ":" + line; if (!coverage.functions[funcId]){ coverage.calledFunctions++; } coverage.functions[funcId]++; }; } _yuitest_coverage["build/datatable-body/datatable-body.js"] = { lines: {}, functions: {}, coveredLines: 0, calledLines: 0, coveredFunctions: 0, calledFunctions: 0, path: "build/datatable-body/datatable-body.js", code: [] }; _yuitest_coverage["build/datatable-body/datatable-body.js"].code=["YUI.add('datatable-body', function (Y, NAME) {","","/**","View class responsible for rendering the `<tbody>` section of a table. Used as","the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.","","@module datatable","@submodule datatable-body","@since 3.5.0","**/","var Lang = Y.Lang,"," isArray = Lang.isArray,"," isNumber = Lang.isNumber,"," isString = Lang.isString,"," fromTemplate = Lang.sub,"," htmlEscape = Y.Escape.html,"," toArray = Y.Array,"," bind = Y.bind,"," YObject = Y.Object;","","/**","View class responsible for rendering the `<tbody>` section of a table. Used as","the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.","","Translates the provided `modelList` into a rendered `<tbody>` based on the data","in the constituent Models, altered or ammended by any special column","configurations.","","The `columns` configuration, passed to the constructor, determines which","columns will be rendered.","","The rendering process involves constructing an HTML template for a complete row","of data, built by concatenating a customized copy of the instance's","`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is","then populated with values from each Model in the `modelList`, aggregating a","complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.","","Supported properties of the column objects include:",""," * `key` - Used to link a column to an attribute in a Model."," * `name` - Used for columns that don't relate to an attribute in the Model"," (`formatter` or `nodeFormatter` only) if the implementer wants a"," predictable name to refer to in their CSS."," * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this"," column only."," * `formatter` - Used to customize or override the content value from the"," Model. These do not have access to the cell or row Nodes and should"," return string (HTML) content."," * `nodeFormatter` - Used to provide content for a cell as well as perform any"," custom modifications on the cell or row Node that could not be performed by"," `formatter`s. Should be used sparingly for better performance."," * `emptyCellValue` - String (HTML) value to use if the Model data for a"," column, or the content generated by a `formatter`, is the empty string,"," `null`, or `undefined`."," * `allowHTML` - Set to `true` if a column value, `formatter`, or"," `emptyCellValue` can contain HTML. This defaults to `false` to protect"," against XSS."," * `className` - Space delimited CSS classes to add to all `<td>`s in a column.","","Column `formatter`s are passed an object (`o`) with the following properties:",""," * `value` - The current value of the column's associated attribute, if any."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `className` - Initially empty string to allow `formatter`s to add CSS "," classes to the cell's `<td>`."," * `rowIndex` - The zero-based row number."," * `rowClass` - Initially empty string to allow `formatter`s to add CSS"," classes to the cell's containing row `<tr>`.","","They may return a value or update `o.value` to assign specific HTML content. A","returned value has higher precedence.","","Column `nodeFormatter`s are passed an object (`o`) with the following","properties:",""," * `value` - The current value of the column's associated attribute, if any."," * `td` - The `<td>` Node instance."," * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`."," When adding content to the cell, prefer appending into this property."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `rowIndex` - The zero-based row number.","","They are expected to inject content into the cell's Node directly, including","any \"empty\" cell content. Each `nodeFormatter` will have access through the","Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as","it will not be attached yet.","","If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be","`destroy()`ed to remove them from the Node cache and free up memory. The DOM","elements will remain as will any content added to them. _It is highly","advisable to always return `false` from your `nodeFormatter`s_.","","@class BodyView","@namespace DataTable","@extends View","@since 3.5.0","**/","Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {"," // -- Instance properties -------------------------------------------------",""," /**"," HTML template used to create table cells.",""," @property CELL_TEMPLATE"," @type {HTML}"," @default '<td {headers} class=\"{className}\">{content}</td>'"," @since 3.5.0"," **/"," CELL_TEMPLATE: '<td {headers} class=\"{className}\">{content}</td>',",""," /**"," CSS class applied to even rows. This is assigned at instantiation."," "," For DataTable, this will be `yui3-datatable-even`.",""," @property CLASS_EVEN"," @type {String}"," @default 'yui3-table-even'"," @since 3.5.0"," **/"," //CLASS_EVEN: null",""," /**"," CSS class applied to odd rows. This is assigned at instantiation."," "," When used by DataTable instances, this will be `yui3-datatable-odd`.",""," @property CLASS_ODD"," @type {String}"," @default 'yui3-table-odd'"," @since 3.5.0"," **/"," //CLASS_ODD: null",""," /**"," HTML template used to create table rows.",""," @property ROW_TEMPLATE"," @type {HTML}"," @default '<tr id=\"{rowId}\" data-yui3-record=\"{clientId}\" class=\"{rowClass}\">{content}</tr>'"," @since 3.5.0"," **/"," ROW_TEMPLATE : '<tr id=\"{rowId}\" data-yui3-record=\"{clientId}\" class=\"{rowClass}\">{content}</tr>',",""," /**"," The object that serves as the source of truth for column and row data."," This property is assigned at instantiation from the `host` property of"," the configuration object passed to the constructor.",""," @property host"," @type {Object}"," @default (initially unset)"," @since 3.5.0"," **/"," //TODO: should this be protected?"," //host: null,",""," /**"," HTML templates used to create the `<tbody>` containing the table rows.",""," @property TBODY_TEMPLATE"," @type {HTML}"," @default '<tbody class=\"{className}\">{content}</tbody>'"," @since 3.6.0"," **/"," TBODY_TEMPLATE: '<tbody class=\"{className}\"></tbody>',",""," // -- Public methods ------------------------------------------------------",""," /**"," Returns the `<td>` Node from the given row and column index. Alternately,"," the `seed` can be a Node. If so, the nearest ancestor cell is returned."," If the `seed` is a cell, it is returned. If there is no cell at the given"," coordinates, `null` is returned.",""," Optionally, include an offset array or string to return a cell near the"," cell identified by the `seed`. The offset can be an array containing the"," number of rows to shift followed by the number of columns to shift, or one"," of \"above\", \"below\", \"next\", or \"previous\".",""," <pre><code>// Previous cell in the previous row"," var cell = table.getCell(e.target, [-1, -1]);",""," // Next cell"," var cell = table.getCell(e.target, 'next');"," var cell = table.getCell(e.taregt, [0, 1];</pre></code>",""," @method getCell"," @param {Number[]|Node} seed Array of row and column indexes, or a Node that"," is either the cell itself or a descendant of one."," @param {Number[]|String} [shift] Offset by which to identify the returned"," cell Node"," @return {Node}"," @since 3.5.0"," **/"," getCell: function (seed, shift) {"," var tbody = this.tbodyNode,"," row, cell, index, rowIndexOffset;",""," if (seed && tbody) {"," if (isArray(seed)) {"," row = tbody.get('children').item(seed[0]);"," cell = row && row.get('children').item(seed[1]);"," } else if (Y.instanceOf(seed, Y.Node)) {"," cell = seed.ancestor('.' + this.getClassName('cell'), true);"," }",""," if (cell && shift) {"," rowIndexOffset = tbody.get('firstChild.rowIndex');"," if (isString(shift)) {"," // TODO this should be a static object map"," switch (shift) {"," case 'above' : shift = [-1, 0]; break;"," case 'below' : shift = [1, 0]; break;"," case 'next' : shift = [0, 1]; break;"," case 'previous': shift = [0, -1]; break;"," }"," }",""," if (isArray(shift)) {"," index = cell.get('parentNode.rowIndex') +"," shift[0] - rowIndexOffset;"," row = tbody.get('children').item(index);",""," index = cell.get('cellIndex') + shift[1];"," cell = row && row.get('children').item(index);"," }"," }"," }"," "," return cell || null;"," },",""," /**"," Returns the generated CSS classname based on the input. If the `host`"," attribute is configured, it will attempt to relay to its `getClassName`"," or use its static `NAME` property as a string base."," "," If `host` is absent or has neither method nor `NAME`, a CSS classname"," will be generated using this class's `NAME`.",""," @method getClassName"," @param {String} token* Any number of token strings to assemble the"," classname from."," @return {String}"," @protected"," @since 3.5.0"," **/"," getClassName: function () {"," var host = this.host,"," args;",""," if (host && host.getClassName) {"," return host.getClassName.apply(host, arguments);"," } else {"," args = toArray(arguments);"," args.unshift(this.constructor.NAME);"," return Y.ClassNameManager.getClassName"," .apply(Y.ClassNameManager, args);"," }"," },",""," /**"," Returns the Model associated to the row Node or id provided. Passing the"," Node or id for a descendant of the row also works.",""," If no Model can be found, `null` is returned.",""," @method getRecord"," @param {String|Node} seed Row Node or `id`, or one for a descendant of a row"," @return {Model}"," @since 3.5.0"," **/"," getRecord: function (seed) {"," var modelList = this.get('modelList'),"," tbody = this.tbodyNode,"," row = null,"," record;",""," if (tbody) {"," if (isString(seed)) {"," seed = tbody.one('#' + seed);"," }",""," if (Y.instanceOf(seed, Y.Node)) {"," row = seed.ancestor(function (node) {"," return node.get('parentNode').compareTo(tbody);"," }, true);",""," record = row &&"," modelList.getByClientId(row.getData('yui3-record'));"," }"," }",""," return record || null;"," },",""," /**"," Returns the `<tr>` Node from the given row index, Model, or Model's"," `clientId`. If the rows haven't been rendered yet, or if the row can't be"," found by the input, `null` is returned.",""," @method getRow"," @param {Number|String|Model} id Row index, Model instance, or clientId"," @return {Node}"," @since 3.5.0"," **/"," getRow: function (id) {"," var tbody = this.tbodyNode,"," row = null;",""," if (tbody) {"," if (id) {"," id = this._idMap[id.get ? id.get('clientId') : id] || id;"," }",""," row = isNumber(id) ?"," tbody.get('children').item(id) :"," tbody.one('#' + id);"," }",""," return row;"," },",""," /**"," Creates the table's `<tbody>` content by assembling markup generated by"," populating the `ROW\\_TEMPLATE`, and `CELL\\_TEMPLATE` templates with content"," from the `columns` and `modelList` attributes.",""," The rendering process happens in three stages:",""," 1. A row template is assembled from the `columns` attribute (see"," `_createRowTemplate`)",""," 2. An HTML string is built up by concatening the application of the data in"," each Model in the `modelList` to the row template. For cells with"," `formatter`s, the function is called to generate cell content. Cells"," with `nodeFormatter`s are ignored. For all other cells, the data value"," from the Model attribute for the given column key is used. The"," accumulated row markup is then inserted into the container.",""," 3. If any column is configured with a `nodeFormatter`, the `modelList` is"," iterated again to apply the `nodeFormatter`s.",""," Supported properties of the column objects include:",""," * `key` - Used to link a column to an attribute in a Model."," * `name` - Used for columns that don't relate to an attribute in the Model"," (`formatter` or `nodeFormatter` only) if the implementer wants a"," predictable name to refer to in their CSS."," * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in"," this column only."," * `formatter` - Used to customize or override the content value from the"," Model. These do not have access to the cell or row Nodes and should"," return string (HTML) content."," * `nodeFormatter` - Used to provide content for a cell as well as perform"," any custom modifications on the cell or row Node that could not be"," performed by `formatter`s. Should be used sparingly for better"," performance."," * `emptyCellValue` - String (HTML) value to use if the Model data for a"," column, or the content generated by a `formatter`, is the empty string,"," `null`, or `undefined`."," * `allowHTML` - Set to `true` if a column value, `formatter`, or"," `emptyCellValue` can contain HTML. This defaults to `false` to protect"," against XSS."," * `className` - Space delimited CSS classes to add to all `<td>`s in a"," column.",""," Column `formatter`s are passed an object (`o`) with the following"," properties:",""," * `value` - The current value of the column's associated attribute, if"," any."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `className` - Initially empty string to allow `formatter`s to add CSS "," classes to the cell's `<td>`."," * `rowIndex` - The zero-based row number."," * `rowClass` - Initially empty string to allow `formatter`s to add CSS"," classes to the cell's containing row `<tr>`.",""," They may return a value or update `o.value` to assign specific HTML"," content. A returned value has higher precedence.",""," Column `nodeFormatter`s are passed an object (`o`) with the following"," properties:",""," * `value` - The current value of the column's associated attribute, if"," any."," * `td` - The `<td>` Node instance."," * `cell` - The `<div>` liner Node instance if present, otherwise, the"," `<td>`. When adding content to the cell, prefer appending into this"," property."," * `data` - An object map of Model keys to their current values."," * `record` - The Model instance."," * `column` - The column configuration object for the current column."," * `rowIndex` - The zero-based row number.",""," They are expected to inject content into the cell's Node directly, including"," any \"empty\" cell content. Each `nodeFormatter` will have access through the"," Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,"," as it will not be attached yet.",""," If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be"," `destroy()`ed to remove them from the Node cache and free up memory. The"," DOM elements will remain as will any content added to them. _It is highly"," advisable to always return `false` from your `nodeFormatter`s_.",""," @method render"," @return {BodyView} The instance"," @chainable"," @since 3.5.0"," **/"," render: function () {"," var table = this.get('container'),"," data = this.get('modelList'),"," columns = this.get('columns'),"," tbody = this.tbodyNode ||"," (this.tbodyNode = this._createTBodyNode());"," "," // Needed for mutation"," this._createRowTemplate(columns);",""," if (data) {"," tbody.setHTML(this._createDataHTML(columns));",""," this._applyNodeFormatters(tbody, columns);"," }",""," if (tbody.get('parentNode') !== table) {"," table.appendChild(tbody);"," }",""," this.bindUI();",""," return this;"," },",""," // -- Protected and private methods ---------------------------------------"," /**"," Handles changes in the source's columns attribute. Redraws the table data.",""," @method _afterColumnsChange"," @param {EventFacade} e The `columnsChange` event object"," @protected"," @since 3.5.0"," **/"," // TODO: Preserve existing DOM"," // This will involve parsing and comparing the old and new column configs"," // and reacting to four types of changes:"," // 1. formatter, nodeFormatter, emptyCellValue changes"," // 2. column deletions"," // 3. column additions"," // 4. column moves (preserve cells)"," _afterColumnsChange: function (e) {"," this.render();"," },",""," /**"," Handles modelList changes, including additions, deletions, and updates.",""," Modifies the existing table DOM accordingly.",""," @method _afterDataChange"," @param {EventFacade} e The `change` event from the ModelList"," @protected"," @since 3.5.0"," **/"," _afterDataChange: function (e) {"," //var type = e.type.slice(e.type.lastIndexOf(':') + 1);",""," // TODO: Isolate changes"," this.render();"," },",""," /**"," Handles replacement of the modelList.",""," Rerenders the `<tbody>` contents.",""," @method _afterModelListChange"," @param {EventFacade} e The `modelListChange` event"," @protected"," @since 3.6.0"," **/"," _afterModelListChange: function (e) {"," var handles = this._eventHandles;",""," if (handles.dataChange) {"," handles.dataChange.detach();"," delete handles.dataChange;"," this.bindUI();"," }",""," if (this.tbodyNode) {"," this.render();"," }"," },",""," /**"," Iterates the `modelList`, and calls any `nodeFormatter`s found in the"," `columns` param on the appropriate cell Nodes in the `tbody`.",""," @method _applyNodeFormatters"," @param {Node} tbody The `<tbody>` Node whose columns to update"," @param {Object[]} columns The column configurations"," @protected"," @since 3.5.0"," **/"," _applyNodeFormatters: function (tbody, columns) {"," var host = this.host,"," data = this.get('modelList'),"," formatters = [],"," linerQuery = '.' + this.getClassName('liner'),"," rows, i, len;",""," // Only iterate the ModelList again if there are nodeFormatters"," for (i = 0, len = columns.length; i < len; ++i) {"," if (columns[i].nodeFormatter) {"," formatters.push(i);"," }"," }",""," if (data && formatters.length) {"," rows = tbody.get('childNodes');",""," data.each(function (record, index) {"," var formatterData = {"," data : record.toJSON(),"," record : record,"," rowIndex : index"," },"," row = rows.item(index),"," i, len, col, key, cells, cell, keep;","",""," if (row) {"," cells = row.get('childNodes');"," for (i = 0, len = formatters.length; i < len; ++i) {"," cell = cells.item(formatters[i]);",""," if (cell) {"," col = formatterData.column = columns[formatters[i]];"," key = col.key || col.id;",""," formatterData.value = record.get(key);"," formatterData.td = cell;"," formatterData.cell = cell.one(linerQuery) || cell;",""," keep = col.nodeFormatter.call(host,formatterData);",""," if (keep === false) {"," // Remove from the Node cache to reduce"," // memory footprint. This also purges events,"," // which you shouldn't be scoping to a cell"," // anyway. You've been warned. Incidentally,"," // you should always return false. Just sayin."," cell.destroy(true);"," }"," }"," }"," }"," });"," }"," },",""," /**"," Binds event subscriptions from the UI and the host (if assigned).",""," @method bindUI"," @protected"," @since 3.5.0"," **/"," bindUI: function () {"," var handles = this._eventHandles,"," modelList = this.get('modelList'),"," changeEvent = modelList.model.NAME + ':change';",""," if (!handles.columnsChange) {"," handles.columnsChange = this.after('columnsChange',"," bind('_afterColumnsChange', this));"," }",""," if (modelList && !handles.dataChange) {"," handles.dataChange = modelList.after("," ['add', 'remove', 'reset', changeEvent],"," bind('_afterDataChange', this));"," }"," },",""," /**"," Iterates the `modelList` and applies each Model to the `_rowTemplate`,"," allowing any column `formatter` or `emptyCellValue` to override cell"," content for the appropriate column. The aggregated HTML string is"," returned.",""," @method _createDataHTML"," @param {Object[]} columns The column configurations to customize the"," generated cell content or class names"," @return {HTML} The markup for all Models in the `modelList`, each applied"," to the `_rowTemplate`"," @protected"," @since 3.5.0"," **/"," _createDataHTML: function (columns) {"," var data = this.get('modelList'),"," html = '';",""," if (data) {"," data.each(function (model, index) {"," html += this._createRowHTML(model, index, columns);"," }, this);"," }",""," return html;"," },",""," /**"," Applies the data of a given Model, modified by any column formatters and"," supplemented by other template values to the instance's `_rowTemplate` (see"," `_createRowTemplate`). The generated string is then returned.",""," The data from Model's attributes is fetched by `toJSON` and this data"," object is appended with other properties to supply values to {placeholders}"," in the template. For a template generated from a Model with 'foo' and 'bar'"," attributes, the data object would end up with the following properties"," before being used to populate the `_rowTemplate`:",""," * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute."," * `foo` - The value to populate the 'foo' column cell content. This"," value will be the value stored in the Model's `foo` attribute, or the"," result of the column's `formatter` if assigned. If the value is '', "," `null`, or `undefined`, and the column's `emptyCellValue` is assigned,"," that value will be used."," * `bar` - Same for the 'bar' column cell content."," * `foo-className` - String of CSS classes to apply to the `<td>`."," * `bar-className` - Same."," * `rowClass` - String of CSS classes to apply to the `<tr>`. This"," will be the odd/even class per the specified index plus any additional"," classes assigned by column formatters (via `o.rowClass`).",""," Because this object is available to formatters, any additional properties"," can be added to fill in custom {placeholders} in the `_rowTemplate`.",""," @method _createRowHTML"," @param {Model} model The Model instance to apply to the row template"," @param {Number} index The index the row will be appearing"," @param {Object[]} columns The column configurations"," @return {HTML} The markup for the provided Model, less any `nodeFormatter`s"," @protected"," @since 3.5.0"," **/"," _createRowHTML: function (model, index, columns) {"," var data = model.toJSON(),"," clientId = model.get('clientId'),"," values = {"," rowId : this._getRowId(clientId),"," clientId: clientId,"," rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN"," },"," host = this.host || this,"," i, len, col, token, value, formatterData;",""," for (i = 0, len = columns.length; i < len; ++i) {"," col = columns[i];"," value = data[col.key];"," token = col._id || col.key;",""," values[token + '-className'] = '';",""," if (col.formatter) {"," formatterData = {"," value : value,"," data : data,"," column : col,"," record : model,"," className: '',"," rowClass : '',"," rowIndex : index"," };",""," if (typeof col.formatter === 'string') {"," if (value !== undefined) {"," // TODO: look for known formatters by string name"," value = fromTemplate(col.formatter, formatterData);"," }"," } else {"," // Formatters can either return a value"," value = col.formatter.call(host, formatterData);",""," // or update the value property of the data obj passed"," if (value === undefined) {"," value = formatterData.value;"," }",""," values[token + '-className'] = formatterData.className;"," values.rowClass += ' ' + formatterData.rowClass;"," }"," }",""," if (value === undefined || value === null || value === '') {"," value = col.emptyCellValue || '';"," }",""," values[token] = col.allowHTML ? value : htmlEscape(value);",""," values.rowClass = values.rowClass.replace(/\\s+/g, ' ');"," }",""," return fromTemplate(this._rowTemplate, values);"," },",""," /**"," Creates a custom HTML template string for use in generating the markup for"," individual table rows with {placeholder}s to capture data from the Models"," in the `modelList` attribute or from column `formatter`s.",""," Assigns the `_rowTemplate` property.",""," @method _createRowTemplate"," @param {Object[]} columns Array of column configuration objects"," @protected"," @since 3.5.0"," **/"," _createRowTemplate: function (columns) {"," var html = '',"," cellTemplate = this.CELL_TEMPLATE,"," i, len, col, key, token, headers, tokenValues;",""," for (i = 0, len = columns.length; i < len; ++i) {"," col = columns[i];"," key = col.key;"," token = col._id || key;"," // Only include headers if there are more than one"," headers = (col._headers || []).length > 1 ?"," 'headers=\"' + col._headers.join(' ') + '\"' : '';",""," tokenValues = {"," content : '{' + token + '}',"," headers : headers,"," className: this.getClassName('col', token) + ' ' +"," (col.className || '') + ' ' +"," this.getClassName('cell') +"," ' {' + token + '-className}'"," };",""," if (col.nodeFormatter) {"," // Defer all node decoration to the formatter"," tokenValues.content = '';"," }",""," html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);"," }",""," this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {"," content: html"," });"," },",""," /**"," Creates the `<tbody>` node that will store the data rows.",""," @method _createTBodyNode"," @return {Node}"," @protected"," @since 3.6.0"," **/"," _createTBodyNode: function () {"," return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, {"," className: this.getClassName('data')"," }));"," },",""," /**"," Destroys the instance.",""," @method destructor"," @protected"," @since 3.5.0"," **/"," destructor: function () {"," (new Y.EventHandle(YObject.values(this._eventHandles))).detach();"," },",""," /**"," Holds the event subscriptions needing to be detached when the instance is"," `destroy()`ed.",""," @property _eventHandles"," @type {Object}"," @default undefined (initially unset)"," @protected"," @since 3.5.0"," **/"," //_eventHandles: null,",""," /**"," Returns the row ID associated with a Model's clientId.",""," @method _getRowId"," @param {String} clientId The Model clientId"," @return {String}"," @protected"," **/"," _getRowId: function (clientId) {"," return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());"," },",""," /**"," Map of Model clientIds to row ids.",""," @property _idMap"," @type {Object}"," @protected"," **/"," //_idMap,",""," /**"," Initializes the instance. Reads the following configuration properties in"," addition to the instance attributes:",""," * `columns` - (REQUIRED) The initial column information"," * `host` - The object to serve as source of truth for column info and"," for generating class names",""," @method initializer"," @param {Object} config Configuration data"," @protected"," @since 3.5.0"," **/"," initializer: function (config) {"," this.host = config.host;",""," this._eventHandles = {"," modelListChange: this.after('modelListChange',"," bind('_afterModelListChange', this))"," };"," this._idMap = {};",""," this.CLASS_ODD = this.getClassName('odd');"," this.CLASS_EVEN = this.getClassName('even');",""," }",""," /**"," The HTML template used to create a full row of markup for a single Model in"," the `modelList` plus any customizations defined in the column"," configurations.",""," @property _rowTemplate"," @type {HTML}"," @default (initially unset)"," @protected"," @since 3.5.0"," **/"," //_rowTemplate: null","});","","","}, '@VERSION@', {\"requires\": [\"datatable-core\", \"view\", \"classnamemanager\"]});"]; _yuitest_coverage["build/datatable-body/datatable-body.js"].lines = {"1":0,"11":0,"102":0,"201":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"212":0,"213":0,"214":0,"216":0,"217":0,"218":0,"219":0,"220":0,"224":0,"225":0,"227":0,"229":0,"230":0,"235":0,"254":0,"257":0,"258":0,"260":0,"261":0,"262":0,"279":0,"284":0,"285":0,"286":0,"289":0,"290":0,"291":0,"294":0,"299":0,"313":0,"316":0,"317":0,"318":0,"321":0,"326":0,"420":0,"427":0,"429":0,"430":0,"432":0,"435":0,"436":0,"439":0,"441":0,"461":0,"478":0,"492":0,"494":0,"495":0,"496":0,"497":0,"500":0,"501":0,"516":0,"523":0,"524":0,"525":0,"529":0,"530":0,"532":0,"533":0,"542":0,"543":0,"544":0,"545":0,"547":0,"548":0,"549":0,"551":0,"552":0,"553":0,"555":0,"557":0,"563":0,"580":0,"584":0,"585":0,"589":0,"590":0,"611":0,"614":0,"615":0,"616":0,"620":0,"659":0,"669":0,"670":0,"671":0,"672":0,"674":0,"676":0,"677":0,"687":0,"688":0,"690":0,"694":0,"697":0,"698":0,"701":0,"702":0,"706":0,"707":0,"710":0,"712":0,"715":0,"731":0,"735":0,"736":0,"737":0,"738":0,"740":0,"743":0,"752":0,"754":0,"757":0,"760":0,"774":0,"787":0,"811":0,"837":0,"839":0,"843":0,"845":0,"846":0}; _yuitest_coverage["build/datatable-body/datatable-body.js"].functions = {"getCell:200":0,"getClassName:253":0,"(anonymous 2):290":0,"getRecord:278":0,"getRow:312":0,"render:419":0,"_afterColumnsChange:460":0,"_afterDataChange:474":0,"_afterModelListChange:491":0,"(anonymous 3):532":0,"_applyNodeFormatters:515":0,"bindUI:579":0,"(anonymous 4):615":0,"_createDataHTML:610":0,"_createRowHTML:658":0,"_createRowTemplate:730":0,"_createTBodyNode:773":0,"destructor:786":0,"_getRowId:810":0,"initializer:836":0,"(anonymous 1):1":0}; _yuitest_coverage["build/datatable-body/datatable-body.js"].coveredLines = 134; _yuitest_coverage["build/datatable-body/datatable-body.js"].coveredFunctions = 21; _yuitest_coverline("build/datatable-body/datatable-body.js", 1); YUI.add('datatable-body', function (Y, NAME) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 1)", 1); _yuitest_coverline("build/datatable-body/datatable-body.js", 11); var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or ammended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ _yuitest_coverline("build/datatable-body/datatable-body.js", 102); Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {HTML} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {HTML} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {HTML} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.taregt, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getCell", 200); _yuitest_coverline("build/datatable-body/datatable-body.js", 201); var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; _yuitest_coverline("build/datatable-body/datatable-body.js", 204); if (seed && tbody) { _yuitest_coverline("build/datatable-body/datatable-body.js", 205); if (isArray(seed)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 206); row = tbody.get('children').item(seed[0]); _yuitest_coverline("build/datatable-body/datatable-body.js", 207); cell = row && row.get('children').item(seed[1]); } else {_yuitest_coverline("build/datatable-body/datatable-body.js", 208); if (Y.instanceOf(seed, Y.Node)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 209); cell = seed.ancestor('.' + this.getClassName('cell'), true); }} _yuitest_coverline("build/datatable-body/datatable-body.js", 212); if (cell && shift) { _yuitest_coverline("build/datatable-body/datatable-body.js", 213); rowIndexOffset = tbody.get('firstChild.rowIndex'); _yuitest_coverline("build/datatable-body/datatable-body.js", 214); if (isString(shift)) { // TODO this should be a static object map _yuitest_coverline("build/datatable-body/datatable-body.js", 216); switch (shift) { case 'above' : _yuitest_coverline("build/datatable-body/datatable-body.js", 217); shift = [-1, 0]; break; case 'below' : _yuitest_coverline("build/datatable-body/datatable-body.js", 218); shift = [1, 0]; break; case 'next' : _yuitest_coverline("build/datatable-body/datatable-body.js", 219); shift = [0, 1]; break; case 'previous': _yuitest_coverline("build/datatable-body/datatable-body.js", 220); shift = [0, -1]; break; } } _yuitest_coverline("build/datatable-body/datatable-body.js", 224); if (isArray(shift)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 225); index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; _yuitest_coverline("build/datatable-body/datatable-body.js", 227); row = tbody.get('children').item(index); _yuitest_coverline("build/datatable-body/datatable-body.js", 229); index = cell.get('cellIndex') + shift[1]; _yuitest_coverline("build/datatable-body/datatable-body.js", 230); cell = row && row.get('children').item(index); } } } _yuitest_coverline("build/datatable-body/datatable-body.js", 235); return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getClassName", 253); _yuitest_coverline("build/datatable-body/datatable-body.js", 254); var host = this.host, args; _yuitest_coverline("build/datatable-body/datatable-body.js", 257); if (host && host.getClassName) { _yuitest_coverline("build/datatable-body/datatable-body.js", 258); return host.getClassName.apply(host, arguments); } else { _yuitest_coverline("build/datatable-body/datatable-body.js", 260); args = toArray(arguments); _yuitest_coverline("build/datatable-body/datatable-body.js", 261); args.unshift(this.constructor.NAME); _yuitest_coverline("build/datatable-body/datatable-body.js", 262); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getRecord", 278); _yuitest_coverline("build/datatable-body/datatable-body.js", 279); var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; _yuitest_coverline("build/datatable-body/datatable-body.js", 284); if (tbody) { _yuitest_coverline("build/datatable-body/datatable-body.js", 285); if (isString(seed)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 286); seed = tbody.one('#' + seed); } _yuitest_coverline("build/datatable-body/datatable-body.js", 289); if (Y.instanceOf(seed, Y.Node)) { _yuitest_coverline("build/datatable-body/datatable-body.js", 290); row = seed.ancestor(function (node) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 2)", 290); _yuitest_coverline("build/datatable-body/datatable-body.js", 291); return node.get('parentNode').compareTo(tbody); }, true); _yuitest_coverline("build/datatable-body/datatable-body.js", 294); record = row && modelList.getByClientId(row.getData('yui3-record')); } } _yuitest_coverline("build/datatable-body/datatable-body.js", 299); return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "getRow", 312); _yuitest_coverline("build/datatable-body/datatable-body.js", 313); var tbody = this.tbodyNode, row = null; _yuitest_coverline("build/datatable-body/datatable-body.js", 316); if (tbody) { _yuitest_coverline("build/datatable-body/datatable-body.js", 317); if (id) { _yuitest_coverline("build/datatable-body/datatable-body.js", 318); id = this._idMap[id.get ? id.get('clientId') : id] || id; } _yuitest_coverline("build/datatable-body/datatable-body.js", 321); row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } _yuitest_coverline("build/datatable-body/datatable-body.js", 326); return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatening the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @return {BodyView} The instance @chainable @since 3.5.0 **/ render: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "render", 419); _yuitest_coverline("build/datatable-body/datatable-body.js", 420); var table = this.get('container'), data = this.get('modelList'), columns = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation _yuitest_coverline("build/datatable-body/datatable-body.js", 427); this._createRowTemplate(columns); _yuitest_coverline("build/datatable-body/datatable-body.js", 429); if (data) { _yuitest_coverline("build/datatable-body/datatable-body.js", 430); tbody.setHTML(this._createDataHTML(columns)); _yuitest_coverline("build/datatable-body/datatable-body.js", 432); this._applyNodeFormatters(tbody, columns); } _yuitest_coverline("build/datatable-body/datatable-body.js", 435); if (tbody.get('parentNode') !== table) { _yuitest_coverline("build/datatable-body/datatable-body.js", 436); table.appendChild(tbody); } _yuitest_coverline("build/datatable-body/datatable-body.js", 439); this.bindUI(); _yuitest_coverline("build/datatable-body/datatable-body.js", 441); return this; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function (e) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_afterColumnsChange", 460); _yuitest_coverline("build/datatable-body/datatable-body.js", 461); this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { //var type = e.type.slice(e.type.lastIndexOf(':') + 1); // TODO: Isolate changes _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_afterDataChange", 474); _yuitest_coverline("build/datatable-body/datatable-body.js", 478); this.render(); }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function (e) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_afterModelListChange", 491); _yuitest_coverline("build/datatable-body/datatable-body.js", 492); var handles = this._eventHandles; _yuitest_coverline("build/datatable-body/datatable-body.js", 494); if (handles.dataChange) { _yuitest_coverline("build/datatable-body/datatable-body.js", 495); handles.dataChange.detach(); _yuitest_coverline("build/datatable-body/datatable-body.js", 496); delete handles.dataChange; _yuitest_coverline("build/datatable-body/datatable-body.js", 497); this.bindUI(); } _yuitest_coverline("build/datatable-body/datatable-body.js", 500); if (this.tbodyNode) { _yuitest_coverline("build/datatable-body/datatable-body.js", 501); this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} columns The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_applyNodeFormatters", 515); _yuitest_coverline("build/datatable-body/datatable-body.js", 516); var host = this.host, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters _yuitest_coverline("build/datatable-body/datatable-body.js", 523); for (i = 0, len = columns.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 524); if (columns[i].nodeFormatter) { _yuitest_coverline("build/datatable-body/datatable-body.js", 525); formatters.push(i); } } _yuitest_coverline("build/datatable-body/datatable-body.js", 529); if (data && formatters.length) { _yuitest_coverline("build/datatable-body/datatable-body.js", 530); rows = tbody.get('childNodes'); _yuitest_coverline("build/datatable-body/datatable-body.js", 532); data.each(function (record, index) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 3)", 532); _yuitest_coverline("build/datatable-body/datatable-body.js", 533); var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; _yuitest_coverline("build/datatable-body/datatable-body.js", 542); if (row) { _yuitest_coverline("build/datatable-body/datatable-body.js", 543); cells = row.get('childNodes'); _yuitest_coverline("build/datatable-body/datatable-body.js", 544); for (i = 0, len = formatters.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 545); cell = cells.item(formatters[i]); _yuitest_coverline("build/datatable-body/datatable-body.js", 547); if (cell) { _yuitest_coverline("build/datatable-body/datatable-body.js", 548); col = formatterData.column = columns[formatters[i]]; _yuitest_coverline("build/datatable-body/datatable-body.js", 549); key = col.key || col.id; _yuitest_coverline("build/datatable-body/datatable-body.js", 551); formatterData.value = record.get(key); _yuitest_coverline("build/datatable-body/datatable-body.js", 552); formatterData.td = cell; _yuitest_coverline("build/datatable-body/datatable-body.js", 553); formatterData.cell = cell.one(linerQuery) || cell; _yuitest_coverline("build/datatable-body/datatable-body.js", 555); keep = col.nodeFormatter.call(host,formatterData); _yuitest_coverline("build/datatable-body/datatable-body.js", 557); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. _yuitest_coverline("build/datatable-body/datatable-body.js", 563); cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "bindUI", 579); _yuitest_coverline("build/datatable-body/datatable-body.js", 580); var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; _yuitest_coverline("build/datatable-body/datatable-body.js", 584); if (!handles.columnsChange) { _yuitest_coverline("build/datatable-body/datatable-body.js", 585); handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } _yuitest_coverline("build/datatable-body/datatable-body.js", 589); if (modelList && !handles.dataChange) { _yuitest_coverline("build/datatable-body/datatable-body.js", 590); handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} columns The column configurations to customize the generated cell content or class names @return {HTML} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createDataHTML", 610); _yuitest_coverline("build/datatable-body/datatable-body.js", 611); var data = this.get('modelList'), html = ''; _yuitest_coverline("build/datatable-body/datatable-body.js", 614); if (data) { _yuitest_coverline("build/datatable-body/datatable-body.js", 615); data.each(function (model, index) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "(anonymous 4)", 615); _yuitest_coverline("build/datatable-body/datatable-body.js", 616); html += this._createRowHTML(model, index, columns); }, this); } _yuitest_coverline("build/datatable-body/datatable-body.js", 620); return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} columns The column configurations @return {HTML} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createRowHTML", 658); _yuitest_coverline("build/datatable-body/datatable-body.js", 659); var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; _yuitest_coverline("build/datatable-body/datatable-body.js", 669); for (i = 0, len = columns.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 670); col = columns[i]; _yuitest_coverline("build/datatable-body/datatable-body.js", 671); value = data[col.key]; _yuitest_coverline("build/datatable-body/datatable-body.js", 672); token = col._id || col.key; _yuitest_coverline("build/datatable-body/datatable-body.js", 674); values[token + '-className'] = ''; _yuitest_coverline("build/datatable-body/datatable-body.js", 676); if (col.formatter) { _yuitest_coverline("build/datatable-body/datatable-body.js", 677); formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; _yuitest_coverline("build/datatable-body/datatable-body.js", 687); if (typeof col.formatter === 'string') { _yuitest_coverline("build/datatable-body/datatable-body.js", 688); if (value !== undefined) { // TODO: look for known formatters by string name _yuitest_coverline("build/datatable-body/datatable-body.js", 690); value = fromTemplate(col.formatter, formatterData); } } else { // Formatters can either return a value _yuitest_coverline("build/datatable-body/datatable-body.js", 694); value = col.formatter.call(host, formatterData); // or update the value property of the data obj passed _yuitest_coverline("build/datatable-body/datatable-body.js", 697); if (value === undefined) { _yuitest_coverline("build/datatable-body/datatable-body.js", 698); value = formatterData.value; } _yuitest_coverline("build/datatable-body/datatable-body.js", 701); values[token + '-className'] = formatterData.className; _yuitest_coverline("build/datatable-body/datatable-body.js", 702); values.rowClass += ' ' + formatterData.rowClass; } } _yuitest_coverline("build/datatable-body/datatable-body.js", 706); if (value === undefined || value === null || value === '') { _yuitest_coverline("build/datatable-body/datatable-body.js", 707); value = col.emptyCellValue || ''; } _yuitest_coverline("build/datatable-body/datatable-body.js", 710); values[token] = col.allowHTML ? value : htmlEscape(value); _yuitest_coverline("build/datatable-body/datatable-body.js", 712); values.rowClass = values.rowClass.replace(/\s+/g, ' '); } _yuitest_coverline("build/datatable-body/datatable-body.js", 715); return fromTemplate(this._rowTemplate, values); }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} columns Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (columns) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createRowTemplate", 730); _yuitest_coverline("build/datatable-body/datatable-body.js", 731); var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues; _yuitest_coverline("build/datatable-body/datatable-body.js", 735); for (i = 0, len = columns.length; i < len; ++i) { _yuitest_coverline("build/datatable-body/datatable-body.js", 736); col = columns[i]; _yuitest_coverline("build/datatable-body/datatable-body.js", 737); key = col.key; _yuitest_coverline("build/datatable-body/datatable-body.js", 738); token = col._id || key; // Only include headers if there are more than one _yuitest_coverline("build/datatable-body/datatable-body.js", 740); headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; _yuitest_coverline("build/datatable-body/datatable-body.js", 743); tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; _yuitest_coverline("build/datatable-body/datatable-body.js", 752); if (col.nodeFormatter) { // Defer all node decoration to the formatter _yuitest_coverline("build/datatable-body/datatable-body.js", 754); tokenValues.content = ''; } _yuitest_coverline("build/datatable-body/datatable-body.js", 757); html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } _yuitest_coverline("build/datatable-body/datatable-body.js", 760); this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_createTBodyNode", 773); _yuitest_coverline("build/datatable-body/datatable-body.js", 774); return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "destructor", 786); _yuitest_coverline("build/datatable-body/datatable-body.js", 787); (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "_getRowId", 810); _yuitest_coverline("build/datatable-body/datatable-body.js", 811); return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { _yuitest_coverfunc("build/datatable-body/datatable-body.js", "initializer", 836); _yuitest_coverline("build/datatable-body/datatable-body.js", 837); this.host = config.host; _yuitest_coverline("build/datatable-body/datatable-body.js", 839); this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; _yuitest_coverline("build/datatable-body/datatable-body.js", 843); this._idMap = {}; _yuitest_coverline("build/datatable-body/datatable-body.js", 845); this.CLASS_ODD = this.getClassName('odd'); _yuitest_coverline("build/datatable-body/datatable-body.js", 846); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {HTML} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null }); }, '@VERSION@', {"requires": ["datatable-core", "view", "classnamemanager"]});
src/__tests__/readonly-array.js
brigand/babel-plugin-flow-react-proptypes
const babel = require('babel-core'); const content = ` import React from 'react'; type Props = { foo: $ReadOnlyArray<number>, }; class ReadOnlyArrayTest extends React.Component<Props> {} `; it('generic-array', () => { const res = babel.transform(content, { babelrc: false, presets: ['@babel/env', '@babel/react', '@babel/flow'], plugins: [ '@babel/syntax-flow', require('../'), "@babel/plugin-proposal-class-properties" ], }).code; expect(res).toMatchSnapshot(); });
src/components/Grid/Row.js
aos2006/tesDeploy
import React from 'react'; import { Row } from 'react-flexbox-grid'; export default props => <Row {...props} />;
examples/redux-firestore/src/components/SetupMessaging/SetupMessaging.js
prescottprue/generator-react-firebase
import React from 'react' import firebase from 'firebase/app' import 'firebase/messaging' import useSetupMessaging from './useSetupMessaging' function LoadMessaging() { const { initializeMessaging } = useSetupMessaging() initializeMessaging() return null } function SetupMessaging() { const user = firebase.auth().currentUser const { isSupported } = firebase.messaging // Render nothing if user is not logged in or if messaging is not supported if (!user || !user.uid || !isSupported()) { return null } // Load messaging if user is logged in return <LoadMessaging /> } export default SetupMessaging
client/utils/checkAuth.js
andela-jmacharia/hati-DMS
import React from 'react'; import { connect } from 'react-redux'; export default function(ComposedComponent) { class Authenticate extends React.Component { componentWillMount() { if (!this.props.isAuthenticated) { this.context.router.push('/home'); } } componentWillUpdate(nextProps) { if (!nextProps.isAuthenticated) { this.context.router.push('/dashboard'); } } render() { return ( <ComposedComponent {...this.props} /> ); } } Authenticate.propTypes = { isAuthenticated: React.PropTypes.bool.isRequired } Authenticate.contextTypes = { router: React.PropTypes.object.isRequired } const mapStateToProps = (state) => { return { isAuthenticated: state.auth.isAuthenticated }; }; return connect(mapStateToProps)(Authenticate); }
client/modules/users/components/invitationsList.js
johngonzalez/abcdapp
import React from 'react'; import {ListGroup, ListGroupItem} from 'react-bootstrap'; import NewTeacher from '../containers/newTeacher'; const InvitationsList = ({invitations}) => ( <div> <ListGroup> { invitations && invitations.length > 0 ? invitations.map((i) => ( <ListGroupItem key={i._id}> <span>{i.email}</span> {i.saving ? <span> saving...</span> : null} </ListGroupItem> )) : <p>No hay invitaciones</p> } </ListGroup> <NewTeacher /> </div> ); InvitationsList.propTypes = { invitations: React.PropTypes.array, }; export default InvitationsList;
app/components/Landing.js
hsin421/tacec-2017
import React from 'react'; import Appbar from 'muicss/lib/react/appbar'; import Button from 'muicss/lib/react/button'; import Container from 'muicss/lib/react/container'; import Divider from 'muicss/lib/react/divider'; import Row from 'muicss/lib/react/row'; import Col from 'muicss/lib/react/col'; import { Link } from 'react-router'; import styles from '../styles.css'; import heroImg from '../images/hero_big.png'; import heroImgSmall from '../images/hero_small.png'; import logoMarker from '../images/map-07.png'; import mapInfo from '../images/map_info.png'; import dotImg from '../images/dot.png'; import regForm from '../images/form.pdf'; import GoogleMapReact from 'google-map-react'; import { toAbsPath } from '../utils' import LandingData from '../data/LandingData' export default class Landing extends React.Component { render() { const langPath = this.props.lang; const lang = langPath || "en"; const viewPortWidth = window.innerWidth; const isMobile = viewPortWidth < 600; const mapCenter = isMobile ? [39.9518694, -75.602182] : [39.9662578,-75.1395344]; return ( <div> <div className={styles.landingHero}> { viewPortWidth < 600 ? (<a href="https://tang.regfox.com/tacec-tang-conference-wotd-2017" target="_blank"><img src={heroImgSmall} alt="TACEC 2017 main image" className={styles.landingHeroImg}/></a>) : (<a href="https://tang.regfox.com/tacec-tang-conference-wotd-2017" target="_blank"><img src={heroImg} alt="TACEC 2017 main image" className={styles.landingHeroImg}/></a>) } </div> <Container className={styles.landingBody}> <Row> <Col md="10" md-offset="1"> <h3 className={styles.heading}> GENERATIONS UNITED,<br/> TAIWANESE AMERICANS TOGETHER. </h3> {LandingData.welcomeMessage[lang]} <div className={styles.homepageBoxContainer} style={isMobile ? {marginLeft: -10 + (viewPortWidth - 260) / 2} : {}}> <Link to={toAbsPath(langPath, "schedule")}> <div className={styles.homepageBox} style={isMobile ? {borderBottom: 'none'} : {borderRight: 'none'}}> <h3 className={styles.hpBoxHeading}>TACEC<br/>PROGRAM</h3> <p className={styles.hpViewMore}> {LandingData.viewMore[lang]} </p> <img src={dotImg} style={{marginTop: -33}}/> </div> </Link> <a href='http://tangeneration.org/programs/' target='_blank'> <div className={styles.homepageBox} style={isMobile ? {borderBottom: 'none'} : {borderRight: 'none'}}> <h3 className={styles.hpBoxHeading}>TANG CONFERENCE</h3> <p className={styles.hpViewMore}> {LandingData.viewMore[lang]} </p> <img src={dotImg} style={{marginTop: -33}}/> </div> </a> <Link to={toAbsPath(langPath, "otd")}> <div className={styles.homepageBox}> <h3 className={styles.hpBoxHeading}>OTD<br/>SUMMIT</h3> <p className={styles.hpViewMore}> {LandingData.viewMore[lang]} </p> <img src={dotImg} style={{marginTop: -33}}/> </div> </Link> </div> </Col> </Row> <Row> <Col md="4" md-offset="4"> <div className={styles.bodyTextAbout} style={{textAlign: 'center', marginTop: 90}}> {LandingData.deadlines[lang]} </div> </Col> </Row> <Row> <Link to="/register"> <Button color="primary" className={styles.OTDButton} style={{fontSize: 15}}>{LandingData.registerOnline[lang]}</Button> </Link> </Row> </Container> {viewPortWidth < 700 && ( <img src={mapInfo} width="100%" />)} <div style={{height: 480, width: '100%'}}> <GoogleMapReact bootstrapURLKeys={{key: 'AIzaSyDeZuJsUlNfaMcKn0JBHDfMl2TzALkPwUk'}} defaultCenter={mapCenter} defaultZoom={10} options={{draggable: false, zoomControl: false, scrollwheel: false, scaleControl: false, disableDoubleClickZoom: true}} disableDefaultUI={true} > <div lat={39.9518694} lng={-75.602182} > <img src={logoMarker} width={60} /> </div> {viewPortWidth > 700 && ( <div lat={40.2201578} lng={-74.9695344} > <img src={mapInfo} /> </div> )} </GoogleMapReact> </div> <Container className={styles.landingBody}> <Row> <Col md="4" md-offset="4"> <h3 className={styles.heading}> ORGANIZERS </h3> </Col> </Row> <Row> {LandingData.organizers.map((organizer, index) => <Col md="4" key={index}> <a href={organizer.link} target="_blank"> <img src={organizer.logoImageSource} className={styles.hostLogo} alt={organizer.logoImageAlternativeText[lang]} {...organizer.logoImageExtraProps} /> </a> </Col> )} </Row> </Container> </div> ); } }
docs/app/Examples/elements/Rail/Variations/index.js
Rohanhacker/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const RailVariationsExamples = () => ( <ExampleSection title='Variations'> <ComponentExample title='Attached' description='A rail can appear attached to the main viewport.' examplePath='elements/Rail/Variations/RailExampleAttached' /> <ComponentExample examplePath='elements/Rail/Variations/RailExampleAttachedInternal' /> <ComponentExample title='Close' description='A rail can appear closer to the main viewport.' examplePath='elements/Rail/Variations/RailExampleClose' /> <ComponentExample examplePath='elements/Rail/Variations/RailExampleCloseVery' /> <ComponentExample title='Size' description='A rail can have different sizes.' examplePath='elements/Rail/Variations/RailExampleSize' /> </ExampleSection> ) export default RailVariationsExamples
client/util/react-intl-test-helper.js
buermo/bembox
/** * Components using the react-intl module require access to the intl context. * This is not available when mounting single components in Enzyme. * These helper functions aim to address that and wrap a valid, * English-locale intl context around them. */ import React from 'react'; import { IntlProvider, intlShape } from 'react-intl'; import { mount, shallow } from 'enzyme'; // You can pass your messages to the IntlProvider. Optional: remove if unneeded. const messages = require('../../Intl/localizationData/en'); // Create the IntlProvider to retrieve context for wrapping around. const intlProvider = new IntlProvider({ locale: 'en', messages }, {}); export const { intl } = intlProvider.getChildContext(); /** * When using React-Intl `injectIntl` on components, props.intl is required. */ const nodeWithIntlProp = node => { return React.cloneElement(node, { intl }); }; export const shallowWithIntl = node => { return shallow(nodeWithIntlProp(node), { context: { intl } }); }; export const mountWithIntl = node => { return mount(nodeWithIntlProp(node), { context: { intl }, childContextTypes: { intl: intlShape }, }); };
ajax/libs/react/0.10.0/react-with-addons.min.js
melvinsembrano/cdnjs
/** * React (with addons) v0.10.0 * * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !function(t){if("object"==typeof exports)module.exports=t();else if("function"==typeof define&&define.amd)define(t);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.React=t()}}(function(){return function t(e,n,o){function r(a,s){if(!n[a]){if(!e[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=n[a]={exports:{}};e[a][0].call(c.exports,function(t){var n=e[a][1][t];return r(n?n:t)},c,c.exports,t,e,n,o)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<o.length;a++)r(o[a]);return r}({1:[function(t,e){"use strict";var n=t("./focusNode"),o={componentDidMount:function(){this.props.autoFocus&&n(this.getDOMNode())}};e.exports=o},{"./focusNode":110}],2:[function(t,e){var n=t("./invariant"),o={addClass:function(t,e){return n(!/\s/.test(e)),e&&(t.classList?t.classList.add(e):o.hasClass(t,e)||(t.className=t.className+" "+e)),t},removeClass:function(t,e){return n(!/\s/.test(e)),e&&(t.classList?t.classList.remove(e):o.hasClass(t,e)&&(t.className=t.className.replace(new RegExp("(^|\\s)"+e+"(?:\\s|$)","g"),"$1").replace(/\s+/g," ").replace(/^\s*|\s*$/g,""))),t},conditionClass:function(t,e,n){return(n?o.addClass:o.removeClass)(t,e)},hasClass:function(t,e){return n(!/\s/.test(e)),t.classList?!!e&&t.classList.contains(e):(" "+t.className+" ").indexOf(" "+e+" ")>-1}};e.exports=o},{"./invariant":122}],3:[function(t,e){"use strict";function n(t,e){return t+e.charAt(0).toUpperCase()+e.substring(1)}var o={columnCount:!0,fillOpacity:!0,flex:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},r=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(t){r.forEach(function(e){o[n(e,t)]=o[t]})});var i={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},a={isUnitlessNumber:o,shorthandPropertyExpansions:i};e.exports=a},{}],4:[function(t,e){"use strict";var n=t("./CSSProperty"),o=t("./dangerousStyleValue"),r=t("./escapeTextForBrowser"),i=t("./hyphenate"),a=t("./memoizeStringOnly"),s=a(function(t){return r(i(t))}),u={createMarkupForStyles:function(t){var e="";for(var n in t)if(t.hasOwnProperty(n)){var r=t[n];null!=r&&(e+=s(n)+":",e+=o(n,r)+";")}return e||null},setValueForStyles:function(t,e){var r=t.style;for(var i in e)if(e.hasOwnProperty(i)){var a=o(i,e[i]);if(a)r[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var u in s)r[u]="";else r[i]=""}}}};e.exports=u},{"./CSSProperty":3,"./dangerousStyleValue":105,"./escapeTextForBrowser":108,"./hyphenate":120,"./memoizeStringOnly":130}],5:[function(t,e){"use strict";function n(t){return"SELECT"===t.nodeName||"INPUT"===t.nodeName&&"file"===t.type}function o(t){var e=M.getPooled(b.change,S,t);C.accumulateTwoPhaseDispatches(e),R.batchedUpdates(r,e)}function r(t){y.enqueueEvents(t),y.processEventQueue()}function i(t,e){O=t,S=e,O.attachEvent("onchange",o)}function a(){O&&(O.detachEvent("onchange",o),O=null,S=null)}function s(t,e,n){return t===T.topChange?n:void 0}function u(t,e,n){t===T.topFocus?(a(),i(e,n)):t===T.topBlur&&a()}function c(t,e){O=t,S=e,N=t.value,I=Object.getOwnPropertyDescriptor(t.constructor.prototype,"value"),Object.defineProperty(O,"value",A),O.attachEvent("onpropertychange",p)}function l(){O&&(delete O.value,O.detachEvent("onpropertychange",p),O=null,S=null,N=null,I=null)}function p(t){if("value"===t.propertyName){var e=t.srcElement.value;e!==N&&(N=e,o(t))}}function d(t,e,n){return t===T.topInput?n:void 0}function h(t,e,n){t===T.topFocus?(l(),c(e,n)):t===T.topBlur&&l()}function f(t){return t!==T.topSelectionChange&&t!==T.topKeyUp&&t!==T.topKeyDown||!O||O.value===N?void 0:(N=O.value,S)}function m(t){return"INPUT"===t.nodeName&&("checkbox"===t.type||"radio"===t.type)}function v(t,e,n){return t===T.topClick?n:void 0}var g=t("./EventConstants"),y=t("./EventPluginHub"),C=t("./EventPropagators"),E=t("./ExecutionEnvironment"),R=t("./ReactUpdates"),M=t("./SyntheticEvent"),D=t("./isEventSupported"),x=t("./isTextInputElement"),P=t("./keyOf"),T=g.topLevelTypes,b={change:{phasedRegistrationNames:{bubbled:P({onChange:null}),captured:P({onChangeCapture:null})},dependencies:[T.topBlur,T.topChange,T.topClick,T.topFocus,T.topInput,T.topKeyDown,T.topKeyUp,T.topSelectionChange]}},O=null,S=null,N=null,I=null,_=!1;E.canUseDOM&&(_=D("change")&&(!("documentMode"in document)||document.documentMode>8));var w=!1;E.canUseDOM&&(w=D("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return I.get.call(this)},set:function(t){N=""+t,I.set.call(this,t)}},k={eventTypes:b,extractEvents:function(t,e,o,r){var i,a;if(n(e)?_?i=s:a=u:x(e)?w?i=d:(i=f,a=h):m(e)&&(i=v),i){var c=i(t,e,o);if(c){var l=M.getPooled(b.change,c,r);return C.accumulateTwoPhaseDispatches(l),l}}a&&a(t,e,o)}};e.exports=k},{"./EventConstants":15,"./EventPluginHub":17,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactUpdates":78,"./SyntheticEvent":86,"./isEventSupported":123,"./isTextInputElement":125,"./keyOf":129}],6:[function(t,e){"use strict";var n=0,o={createReactRootIndex:function(){return n++}};e.exports=o},{}],7:[function(t,e){"use strict";function n(t){switch(t){case g.topCompositionStart:return C.compositionStart;case g.topCompositionEnd:return C.compositionEnd;case g.topCompositionUpdate:return C.compositionUpdate}}function o(t,e){return t===g.topKeyDown&&e.keyCode===f}function r(t,e){switch(t){case g.topKeyUp:return-1!==h.indexOf(e.keyCode);case g.topKeyDown:return e.keyCode!==f;case g.topKeyPress:case g.topMouseDown:case g.topBlur:return!0;default:return!1}}function i(t){this.root=t,this.startSelection=c.getSelection(t),this.startValue=this.getText()}var a=t("./EventConstants"),s=t("./EventPropagators"),u=t("./ExecutionEnvironment"),c=t("./ReactInputSelection"),l=t("./SyntheticCompositionEvent"),p=t("./getTextContentAccessor"),d=t("./keyOf"),h=[9,13,27,32],f=229,m=u.canUseDOM&&"CompositionEvent"in window,v=!m||"documentMode"in document&&document.documentMode>8,g=a.topLevelTypes,y=null,C={compositionEnd:{phasedRegistrationNames:{bubbled:d({onCompositionEnd:null}),captured:d({onCompositionEndCapture:null})},dependencies:[g.topBlur,g.topCompositionEnd,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:d({onCompositionStart:null}),captured:d({onCompositionStartCapture:null})},dependencies:[g.topBlur,g.topCompositionStart,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:d({onCompositionUpdate:null}),captured:d({onCompositionUpdateCapture:null})},dependencies:[g.topBlur,g.topCompositionUpdate,g.topKeyDown,g.topKeyPress,g.topKeyUp,g.topMouseDown]}};i.prototype.getText=function(){return this.root.value||this.root[p()]},i.prototype.getData=function(){var t=this.getText(),e=this.startSelection.start,n=this.startValue.length-this.startSelection.end;return t.substr(e,t.length-n-e)};var E={eventTypes:C,extractEvents:function(t,e,a,u){var c,p;if(m?c=n(t):y?r(t,u)&&(c=C.compositionEnd):o(t,u)&&(c=C.compositionStart),v&&(y||c!==C.compositionStart?c===C.compositionEnd&&y&&(p=y.getData(),y=null):y=new i(e)),c){var d=l.getPooled(c,a,u);return p&&(d.data=p),s.accumulateTwoPhaseDispatches(d),d}}};e.exports=E},{"./EventConstants":15,"./EventPropagators":20,"./ExecutionEnvironment":21,"./ReactInputSelection":54,"./SyntheticCompositionEvent":84,"./getTextContentAccessor":118,"./keyOf":129}],8:[function(t,e){"use strict";function n(t,e,n){var o=t.childNodes;o[n]!==e&&(e.parentNode===t&&t.removeChild(e),n>=o.length?t.appendChild(e):t.insertBefore(e,o[n]))}var o,r=t("./Danger"),i=t("./ReactMultiChildUpdateTypes"),a=t("./getTextContentAccessor"),s=a();o="textContent"===s?function(t,e){t.textContent=e}:function(t,e){for(;t.firstChild;)t.removeChild(t.firstChild);if(e){var n=t.ownerDocument||document;t.appendChild(n.createTextNode(e))}};var u={dangerouslyReplaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,updateTextContent:o,processUpdates:function(t,e){for(var a,s=null,u=null,c=0;a=t[c];c++)if(a.type===i.MOVE_EXISTING||a.type===i.REMOVE_NODE){var l=a.fromIndex,p=a.parentNode.childNodes[l],d=a.parentID;s=s||{},s[d]=s[d]||[],s[d][l]=p,u=u||[],u.push(p)}var h=r.dangerouslyRenderMarkup(e);if(u)for(var f=0;f<u.length;f++)u[f].parentNode.removeChild(u[f]);for(var m=0;a=t[m];m++)switch(a.type){case i.INSERT_MARKUP:n(a.parentNode,h[a.markupIndex],a.toIndex);break;case i.MOVE_EXISTING:n(a.parentNode,s[a.parentID][a.fromIndex],a.toIndex);break;case i.TEXT_CONTENT:o(a.parentNode,a.textContent);break;case i.REMOVE_NODE:}}};e.exports=u},{"./Danger":11,"./ReactMultiChildUpdateTypes":61,"./getTextContentAccessor":118}],9:[function(t,e){"use strict";var n=t("./invariant"),o={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_POSITIVE_NUMERIC_VALUE:16,injectDOMPropertyConfig:function(t){var e=t.Properties||{},r=t.DOMAttributeNames||{},a=t.DOMPropertyNames||{},s=t.DOMMutationMethods||{};t.isCustomAttribute&&i._isCustomAttributeFunctions.push(t.isCustomAttribute);for(var u in e){n(!i.isStandardName[u]),i.isStandardName[u]=!0;var c=u.toLowerCase();i.getPossibleStandardName[c]=u;var l=r[u];l&&(i.getPossibleStandardName[l]=u),i.getAttributeName[u]=l||c,i.getPropertyName[u]=a[u]||u;var p=s[u];p&&(i.getMutationMethod[u]=p);var d=e[u];i.mustUseAttribute[u]=d&o.MUST_USE_ATTRIBUTE,i.mustUseProperty[u]=d&o.MUST_USE_PROPERTY,i.hasSideEffects[u]=d&o.HAS_SIDE_EFFECTS,i.hasBooleanValue[u]=d&o.HAS_BOOLEAN_VALUE,i.hasPositiveNumericValue[u]=d&o.HAS_POSITIVE_NUMERIC_VALUE,n(!i.mustUseAttribute[u]||!i.mustUseProperty[u]),n(i.mustUseProperty[u]||!i.hasSideEffects[u]),n(!i.hasBooleanValue[u]||!i.hasPositiveNumericValue[u])}}},r={},i={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasPositiveNumericValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(t){for(var e=0;e<i._isCustomAttributeFunctions.length;e++){var n=i._isCustomAttributeFunctions[e];if(n(t))return!0}return!1},getDefaultValueForProperty:function(t,e){var n,o=r[t];return o||(r[t]=o={}),e in o||(n=document.createElement(t),o[e]=n[e]),o[e]},injection:o};e.exports=i},{"./invariant":122}],10:[function(t,e){"use strict";function n(t,e){return null==e||o.hasBooleanValue[t]&&!e||o.hasPositiveNumericValue[t]&&(isNaN(e)||1>e)}var o=t("./DOMProperty"),r=t("./escapeTextForBrowser"),i=t("./memoizeStringOnly"),a=(t("./warning"),i(function(t){return r(t)+'="'})),s={createMarkupForID:function(t){return a(o.ID_ATTRIBUTE_NAME)+r(t)+'"'},createMarkupForProperty:function(t,e){if(o.isStandardName[t]){if(n(t,e))return"";var i=o.getAttributeName[t];return o.hasBooleanValue[t]?r(i):a(i)+r(e)+'"'}return o.isCustomAttribute(t)?null==e?"":a(t)+r(e)+'"':null},setValueForProperty:function(t,e,r){if(o.isStandardName[e]){var i=o.getMutationMethod[e];if(i)i(t,r);else if(n(e,r))this.deleteValueForProperty(t,e);else if(o.mustUseAttribute[e])t.setAttribute(o.getAttributeName[e],""+r);else{var a=o.getPropertyName[e];o.hasSideEffects[e]&&t[a]===r||(t[a]=r)}}else o.isCustomAttribute(e)&&(null==r?t.removeAttribute(o.getAttributeName[e]):t.setAttribute(e,""+r))},deleteValueForProperty:function(t,e){if(o.isStandardName[e]){var n=o.getMutationMethod[e];if(n)n(t,void 0);else if(o.mustUseAttribute[e])t.removeAttribute(o.getAttributeName[e]);else{var r=o.getPropertyName[e],i=o.getDefaultValueForProperty(t.nodeName,r);o.hasSideEffects[e]&&t[r]===i||(t[r]=i)}}else o.isCustomAttribute(e)&&t.removeAttribute(e)}};e.exports=s},{"./DOMProperty":9,"./escapeTextForBrowser":108,"./memoizeStringOnly":130,"./warning":144}],11:[function(t,e){"use strict";function n(t){return t.substring(1,t.indexOf(" "))}var o=t("./ExecutionEnvironment"),r=t("./createNodesFromMarkup"),i=t("./emptyFunction"),a=t("./getMarkupWrap"),s=t("./invariant"),u=/^(<[^ \/>]+)/,c="data-danger-index",l={dangerouslyRenderMarkup:function(t){s(o.canUseDOM);for(var e,l={},p=0;p<t.length;p++)s(t[p]),e=n(t[p]),e=a(e)?e:"*",l[e]=l[e]||[],l[e][p]=t[p];var d=[],h=0;for(e in l)if(l.hasOwnProperty(e)){var f=l[e];for(var m in f)if(f.hasOwnProperty(m)){var v=f[m];f[m]=v.replace(u,"$1 "+c+'="'+m+'" ')}var g=r(f.join(""),i);for(p=0;p<g.length;++p){var y=g[p];y.hasAttribute&&y.hasAttribute(c)&&(m=+y.getAttribute(c),y.removeAttribute(c),s(!d.hasOwnProperty(m)),d[m]=y,h+=1)}}return s(h===d.length),s(d.length===t.length),d},dangerouslyReplaceNodeWithMarkup:function(t,e){s(o.canUseDOM),s(e),s("html"!==t.tagName.toLowerCase());var n=r(e,i)[0];t.parentNode.replaceChild(n,t)}};e.exports=l},{"./ExecutionEnvironment":21,"./createNodesFromMarkup":102,"./emptyFunction":106,"./getMarkupWrap":115,"./invariant":122}],12:[function(t,e){"use strict";var n=t("./DOMProperty"),o=n.injection.MUST_USE_ATTRIBUTE,r=n.injection.MUST_USE_PROPERTY,i=n.injection.HAS_BOOLEAN_VALUE,a=n.injection.HAS_SIDE_EFFECTS,s=n.injection.HAS_POSITIVE_NUMERIC_VALUE,u={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,accessKey:null,action:null,allowFullScreen:o|i,allowTransparency:o,alt:null,async:i,autoComplete:null,autoPlay:i,cellPadding:null,cellSpacing:null,charSet:o,checked:r|i,className:r,cols:o|s,colSpan:null,content:null,contentEditable:null,contextMenu:o,controls:r|i,crossOrigin:null,data:null,dateTime:o,defer:i,dir:null,disabled:o|i,download:null,draggable:null,encType:null,form:o,formNoValidate:i,frameBorder:o,height:o,hidden:o|i,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:r,label:null,lang:null,list:null,loop:r|i,max:null,maxLength:o,mediaGroup:null,method:null,min:null,multiple:r|i,muted:r|i,name:null,noValidate:i,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:r|i,rel:null,required:i,role:o,rows:o|s,rowSpan:null,sandbox:null,scope:null,scrollLeft:r,scrollTop:r,seamless:o|i,selected:r|i,size:o|s,span:s,spellCheck:null,src:null,srcDoc:r,srcSet:null,step:null,style:null,tabIndex:null,target:null,title:null,type:null,value:r|a,width:o,wmode:o,autoCapitalize:null,autoCorrect:null,property:null,cx:o,cy:o,d:o,fill:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,offset:o,points:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeLinecap:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,y1:o,y2:o,y:o},DOMAttributeNames:{className:"class",gradientTransform:"gradientTransform",gradientUnits:"gradientUnits",htmlFor:"for",spreadMethod:"spreadMethod",stopColor:"stop-color",stopOpacity:"stop-opacity",strokeLinecap:"stroke-linecap",strokeWidth:"stroke-width",textAnchor:"text-anchor",viewBox:"viewBox"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"enctype",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};e.exports=u},{"./DOMProperty":9}],13:[function(t,e){"use strict";var n=t("./keyOf"),o=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({SelectEventPlugin:null}),n({CompositionEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];e.exports=o},{"./keyOf":129}],14:[function(t,e){"use strict";var n=t("./EventConstants"),o=t("./EventPropagators"),r=t("./SyntheticMouseEvent"),i=t("./ReactMount"),a=t("./keyOf"),s=n.topLevelTypes,u=i.getFirstReactDOM,c={mouseEnter:{registrationName:a({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:a({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},l=[null,null],p={eventTypes:c,extractEvents:function(t,e,n,a){if(t===s.topMouseOver&&(a.relatedTarget||a.fromElement))return null;if(t!==s.topMouseOut&&t!==s.topMouseOver)return null;var p;if(e.window===e)p=e;else{var d=e.ownerDocument;p=d?d.defaultView||d.parentWindow:window}var h,f;if(t===s.topMouseOut?(h=e,f=u(a.relatedTarget||a.toElement)||p):(h=p,f=e),h===f)return null;var m=h?i.getID(h):"",v=f?i.getID(f):"",g=r.getPooled(c.mouseLeave,m,a);g.type="mouseleave",g.target=h,g.relatedTarget=f;var y=r.getPooled(c.mouseEnter,v,a);return y.type="mouseenter",y.target=f,y.relatedTarget=h,o.accumulateEnterLeaveDispatches(g,y,m,v),l[0]=g,l[1]=y,l}};e.exports=p},{"./EventConstants":15,"./EventPropagators":20,"./ReactMount":58,"./SyntheticMouseEvent":89,"./keyOf":129}],15:[function(t,e){"use strict";var n=t("./keyMirror"),o=n({bubbled:null,captured:null}),r=n({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),i={topLevelTypes:r,PropagationPhases:o};e.exports=i},{"./keyMirror":128}],16:[function(t,e){var n=t("./emptyFunction"),o={listen:function(t,e,n){return t.addEventListener?(t.addEventListener(e,n,!1),{remove:function(){t.removeEventListener(e,n,!1)}}):t.attachEvent?(t.attachEvent("on"+e,n),{remove:function(){t.detachEvent(e,n)}}):void 0},capture:function(t,e,o){return t.addEventListener?(t.addEventListener(e,o,!0),{remove:function(){t.removeEventListener(e,o,!0)}}):{remove:n}}};e.exports=o},{"./emptyFunction":106}],17:[function(t,e){"use strict";var n=t("./EventPluginRegistry"),o=t("./EventPluginUtils"),r=t("./ExecutionEnvironment"),i=t("./accumulate"),a=t("./forEachAccumulated"),s=t("./invariant"),u=(t("./isEventSupported"),t("./monitorCodeUse"),{}),c=null,l=function(t){if(t){var e=o.executeDispatch,r=n.getPluginModuleForEvent(t);r&&r.executeDispatch&&(e=r.executeDispatch),o.executeDispatchesInOrder(t,e),t.isPersistent()||t.constructor.release(t)}},p=null,d={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(t){p=t},getInstanceHandle:function(){return p},injectEventPluginOrder:n.injectEventPluginOrder,injectEventPluginsByName:n.injectEventPluginsByName},eventNameDispatchConfigs:n.eventNameDispatchConfigs,registrationNameModules:n.registrationNameModules,putListener:function(t,e,n){s(r.canUseDOM),s(!n||"function"==typeof n);var o=u[e]||(u[e]={});o[t]=n},getListener:function(t,e){var n=u[e];return n&&n[t]},deleteListener:function(t,e){var n=u[e];n&&delete n[t]},deleteAllListeners:function(t){for(var e in u)delete u[e][t]},extractEvents:function(t,e,o,r){for(var a,s=n.plugins,u=0,c=s.length;c>u;u++){var l=s[u];if(l){var p=l.extractEvents(t,e,o,r);p&&(a=i(a,p))}}return a},enqueueEvents:function(t){t&&(c=i(c,t))},processEventQueue:function(){var t=c;c=null,a(t,l),s(!c)},__purge:function(){u={}},__getListenerBank:function(){return u}};e.exports=d},{"./EventPluginRegistry":18,"./EventPluginUtils":19,"./ExecutionEnvironment":21,"./accumulate":95,"./forEachAccumulated":111,"./invariant":122,"./isEventSupported":123,"./monitorCodeUse":135}],18:[function(t,e){"use strict";function n(){if(a)for(var t in s){var e=s[t],n=a.indexOf(t);if(i(n>-1),!u.plugins[n]){i(e.extractEvents),u.plugins[n]=e;var r=e.eventTypes;for(var c in r)i(o(r[c],e,c))}}}function o(t,e,n){i(!u.eventNameDispatchConfigs[n]),u.eventNameDispatchConfigs[n]=t;var o=t.phasedRegistrationNames;if(o){for(var a in o)if(o.hasOwnProperty(a)){var s=o[a];r(s,e,n)}return!0}return t.registrationName?(r(t.registrationName,e,n),!0):!1}function r(t,e,n){i(!u.registrationNameModules[t]),u.registrationNameModules[t]=e,u.registrationNameDependencies[t]=e.eventTypes[n].dependencies}var i=t("./invariant"),a=null,s={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(t){i(!a),a=Array.prototype.slice.call(t),n()},injectEventPluginsByName:function(t){var e=!1;for(var o in t)if(t.hasOwnProperty(o)){var r=t[o];s[o]!==r&&(i(!s[o]),s[o]=r,e=!0)}e&&n()},getPluginModuleForEvent:function(t){var e=t.dispatchConfig;if(e.registrationName)return u.registrationNameModules[e.registrationName]||null;for(var n in e.phasedRegistrationNames)if(e.phasedRegistrationNames.hasOwnProperty(n)){var o=u.registrationNameModules[e.phasedRegistrationNames[n]];if(o)return o}return null},_resetEventPlugins:function(){a=null;for(var t in s)s.hasOwnProperty(t)&&delete s[t];u.plugins.length=0;var e=u.eventNameDispatchConfigs;for(var n in e)e.hasOwnProperty(n)&&delete e[n];var o=u.registrationNameModules;for(var r in o)o.hasOwnProperty(r)&&delete o[r]}};e.exports=u},{"./invariant":122}],19:[function(t,e){"use strict";function n(t){return t===f.topMouseUp||t===f.topTouchEnd||t===f.topTouchCancel}function o(t){return t===f.topMouseMove||t===f.topTouchMove}function r(t){return t===f.topMouseDown||t===f.topTouchStart}function i(t,e){var n=t._dispatchListeners,o=t._dispatchIDs;if(Array.isArray(n))for(var r=0;r<n.length&&!t.isPropagationStopped();r++)e(t,n[r],o[r]);else n&&e(t,n,o)}function a(t,e,n){t.currentTarget=h.Mount.getNode(n);var o=e(t,n);return t.currentTarget=null,o}function s(t,e){i(t,e),t._dispatchListeners=null,t._dispatchIDs=null}function u(t){var e=t._dispatchListeners,n=t._dispatchIDs;if(Array.isArray(e)){for(var o=0;o<e.length&&!t.isPropagationStopped();o++)if(e[o](t,n[o]))return n[o]}else if(e&&e(t,n))return n;return null}function c(t){var e=t._dispatchListeners,n=t._dispatchIDs;d(!Array.isArray(e));var o=e?e(t,n):null;return t._dispatchListeners=null,t._dispatchIDs=null,o}function l(t){return!!t._dispatchListeners}var p=t("./EventConstants"),d=t("./invariant"),h={Mount:null,injectMount:function(t){h.Mount=t}},f=p.topLevelTypes,m={isEndish:n,isMoveish:o,isStartish:r,executeDirectDispatch:c,executeDispatch:a,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:u,hasDispatches:l,injection:h,useTouchEvents:!1};e.exports=m},{"./EventConstants":15,"./invariant":122}],20:[function(t,e){"use strict";function n(t,e,n){var o=e.dispatchConfig.phasedRegistrationNames[n];return m(t,o)}function o(t,e,o){var r=e?f.bubbled:f.captured,i=n(t,o,r);i&&(o._dispatchListeners=d(o._dispatchListeners,i),o._dispatchIDs=d(o._dispatchIDs,t))}function r(t){t&&t.dispatchConfig.phasedRegistrationNames&&p.injection.getInstanceHandle().traverseTwoPhase(t.dispatchMarker,o,t)}function i(t,e,n){if(n&&n.dispatchConfig.registrationName){var o=n.dispatchConfig.registrationName,r=m(t,o);r&&(n._dispatchListeners=d(n._dispatchListeners,r),n._dispatchIDs=d(n._dispatchIDs,t))}}function a(t){t&&t.dispatchConfig.registrationName&&i(t.dispatchMarker,null,t)}function s(t){h(t,r)}function u(t,e,n,o){p.injection.getInstanceHandle().traverseEnterLeave(n,o,i,t,e)}function c(t){h(t,a)}var l=t("./EventConstants"),p=t("./EventPluginHub"),d=t("./accumulate"),h=t("./forEachAccumulated"),f=l.PropagationPhases,m=p.getListener,v={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:c,accumulateEnterLeaveDispatches:u};e.exports=v},{"./EventConstants":15,"./EventPluginHub":17,"./accumulate":95,"./forEachAccumulated":111}],21:[function(t,e){"use strict";var n="undefined"!=typeof window,o={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&(window.addEventListener||window.attachEvent),isInWorker:!n};e.exports=o},{}],22:[function(t,e){"use strict";var n=t("./ReactLink"),o=t("./ReactStateSetters"),r={linkState:function(t){return new n(this.state[t],o.createStateKeySetter(this,t))}};e.exports=r},{"./ReactLink":56,"./ReactStateSetters":73}],23:[function(t,e){"use strict";function n(t){u(null==t.props.checkedLink||null==t.props.valueLink)}function o(t){n(t),u(null==t.props.value&&null==t.props.onChange)}function r(t){n(t),u(null==t.props.checked&&null==t.props.onChange)}function i(t){this.props.valueLink.requestChange(t.target.value)}function a(t){this.props.checkedLink.requestChange(t.target.checked)}var s=t("./ReactPropTypes"),u=t("./invariant"),c=(t("./warning"),{Mixin:{propTypes:{value:function(){},checked:function(){},onChange:s.func}},getValue:function(t){return t.props.valueLink?(o(t),t.props.valueLink.value):t.props.value},getChecked:function(t){return t.props.checkedLink?(r(t),t.props.checkedLink.value):t.props.checked},getOnChange:function(t){return t.props.valueLink?(o(t),i):t.props.checkedLink?(r(t),a):t.props.onChange}});e.exports=c},{"./ReactPropTypes":67,"./invariant":122,"./warning":144}],24:[function(t,e){"use strict";var n=t("./EventConstants"),o=t("./emptyFunction"),r=n.topLevelTypes,i={eventTypes:null,extractEvents:function(t,e,n,i){if(t===r.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=o)}}};e.exports=i},{"./EventConstants":15,"./emptyFunction":106}],25:[function(t,e){"use strict";var n=t("./invariant"),o=function(t){var e=this;if(e.instancePool.length){var n=e.instancePool.pop();return e.call(n,t),n}return new e(t)},r=function(t,e){var n=this;if(n.instancePool.length){var o=n.instancePool.pop();return n.call(o,t,e),o}return new n(t,e)},i=function(t,e,n){var o=this;if(o.instancePool.length){var r=o.instancePool.pop();return o.call(r,t,e,n),r}return new o(t,e,n)},a=function(t,e,n,o,r){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,t,e,n,o,r),a}return new i(t,e,n,o,r)},s=function(t){var e=this;n(t instanceof e),t.destructor&&t.destructor(),e.instancePool.length<e.poolSize&&e.instancePool.push(t)},u=10,c=o,l=function(t,e){var n=t;return n.instancePool=[],n.getPooled=e||c,n.poolSize||(n.poolSize=u),n.release=s,n},p={addPoolingTo:l,oneArgumentPooler:o,twoArgumentPooler:r,threeArgumentPooler:i,fiveArgumentPooler:a};e.exports=p},{"./invariant":122}],26:[function(t,e){"use strict";var n=t("./DOMPropertyOperations"),o=t("./EventPluginUtils"),r=t("./ReactChildren"),i=t("./ReactComponent"),a=t("./ReactCompositeComponent"),s=t("./ReactContext"),u=t("./ReactCurrentOwner"),c=t("./ReactDOM"),l=t("./ReactDOMComponent"),p=t("./ReactDefaultInjection"),d=t("./ReactInstanceHandles"),h=t("./ReactMount"),f=t("./ReactMultiChild"),m=t("./ReactPerf"),v=t("./ReactPropTypes"),g=t("./ReactServerRendering"),y=t("./ReactTextComponent"),C=t("./onlyChild");p.inject();var E={Children:{map:r.map,forEach:r.forEach,only:C},DOM:c,PropTypes:v,initializeTouchEvents:function(t){o.useTouchEvents=t},createClass:a.createClass,constructAndRenderComponent:h.constructAndRenderComponent,constructAndRenderComponentByID:h.constructAndRenderComponentByID,renderComponent:m.measure("React","renderComponent",h.renderComponent),renderComponentToString:g.renderComponentToString,renderComponentToStaticMarkup:g.renderComponentToStaticMarkup,unmountComponentAtNode:h.unmountComponentAtNode,isValidClass:a.isValidClass,isValidComponent:i.isValidComponent,withContext:s.withContext,__internals:{Component:i,CurrentOwner:u,DOMComponent:l,DOMPropertyOperations:n,InstanceHandles:d,Mount:h,MultiChild:f,TextComponent:y}};E.version="0.10.0",e.exports=E},{"./DOMPropertyOperations":10,"./EventPluginUtils":19,"./ReactChildren":30,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactDOM":36,"./ReactDOMComponent":38,"./ReactDefaultInjection":48,"./ReactInstanceHandles":55,"./ReactMount":58,"./ReactMultiChild":60,"./ReactPerf":63,"./ReactPropTypes":67,"./ReactServerRendering":71,"./ReactTextComponent":74,"./onlyChild":138}],27:[function(t,e){"use strict";var n=t("./ReactMount"),o=t("./invariant"),r={getDOMNode:function(){return o(this.isMounted()),n.getNode(this._rootNodeID)}};e.exports=r},{"./ReactMount":58,"./invariant":122}],28:[function(t,e){"use strict";var n=t("./React"),o=t("./ReactTransitionGroup"),r=t("./ReactCSSTransitionGroupChild"),i=n.createClass({propTypes:{transitionName:n.PropTypes.string.isRequired,transitionEnter:n.PropTypes.bool,transitionLeave:n.PropTypes.bool},getDefaultProps:function(){return{transitionEnter:!0,transitionLeave:!0}},_wrapChild:function(t){return r({name:this.props.transitionName,enter:this.props.transitionEnter,leave:this.props.transitionLeave},t)},render:function(){return this.transferPropsTo(o({childFactory:this._wrapChild},this.props.children))}});e.exports=i},{"./React":26,"./ReactCSSTransitionGroupChild":29,"./ReactTransitionGroup":77}],29:[function(t,e){"use strict";var n=t("./React"),o=t("./CSSCore"),r=t("./ReactTransitionEvents"),i=t("./onlyChild"),a=17,s=n.createClass({transition:function(t,e){var n=this.getDOMNode(),i=this.props.name+"-"+t,a=i+"-active",s=function(){o.removeClass(n,i),o.removeClass(n,a),r.removeEndEventListener(n,s),e&&e()};r.addEndEventListener(n,s),o.addClass(n,i),this.queueClass(a)},queueClass:function(t){return this.classNameQueue.push(t),this.props.runNextTick?void this.props.runNextTick(this.flushClassNameQueue):void(this.timeout||(this.timeout=setTimeout(this.flushClassNameQueue,a)))},flushClassNameQueue:function(){this.isMounted()&&this.classNameQueue.forEach(o.addClass.bind(o,this.getDOMNode())),this.classNameQueue.length=0,this.timeout=null},componentWillMount:function(){this.classNameQueue=[]},componentWillUnmount:function(){this.timeout&&clearTimeout(this.timeout)},componentWillEnter:function(t){this.props.enter?this.transition("enter",t):t()},componentWillLeave:function(t){this.props.leave?this.transition("leave",t):t()},render:function(){return i(this.props.children)}});e.exports=s},{"./CSSCore":2,"./React":26,"./ReactTransitionEvents":76,"./onlyChild":138}],30:[function(t,e){"use strict";function n(t,e){this.forEachFunction=t,this.forEachContext=e}function o(t,e,n,o){var r=t;r.forEachFunction.call(r.forEachContext,e,o)}function r(t,e,r){if(null==t)return t;var i=n.getPooled(e,r);l(t,o,i),n.release(i)}function i(t,e,n){this.mapResult=t,this.mapFunction=e,this.mapContext=n}function a(t,e,n,o){var r=t,i=r.mapResult,a=r.mapFunction.call(r.mapContext,e,o);c(!i.hasOwnProperty(n)),i[n]=a}function s(t,e,n){if(null==t)return t;var o={},r=i.getPooled(o,e,n);return l(t,a,r),i.release(r),o}var u=t("./PooledClass"),c=t("./invariant"),l=t("./traverseAllChildren"),p=u.twoArgumentPooler,d=u.threeArgumentPooler;u.addPoolingTo(n,p),u.addPoolingTo(i,d);var h={forEach:r,map:s};e.exports=h},{"./PooledClass":25,"./invariant":122,"./traverseAllChildren":142}],31:[function(t,e){"use strict";var n=t("./ReactCurrentOwner"),o=t("./ReactOwner"),r=t("./ReactUpdates"),i=t("./invariant"),a=t("./keyMirror"),s=t("./merge"),u=(t("./monitorCodeUse"),a({MOUNTED:null,UNMOUNTED:null})),c=!1,l=null,p=null,d={injection:{injectEnvironment:function(t){i(!c),p=t.mountImageIntoNode,l=t.unmountIDFromEnvironment,d.BackendIDOperations=t.BackendIDOperations,d.ReactReconcileTransaction=t.ReactReconcileTransaction,c=!0}},isValidComponent:function(t){if(!t||!t.type||!t.type.prototype)return!1;var e=t.type.prototype;return"function"==typeof e.mountComponentIntoNode&&"function"==typeof e.receiveComponent},LifeCycle:u,BackendIDOperations:null,ReactReconcileTransaction:null,Mixin:{isMounted:function(){return this._lifeCycleState===u.MOUNTED},setProps:function(t,e){this.replaceProps(s(this._pendingProps||this.props,t),e)},replaceProps:function(t,e){i(this.isMounted()),i(0===this._mountDepth),this._pendingProps=t,r.enqueueUpdate(this,e) },construct:function(t,e){this.props=t||{},this._owner=n.current,this._lifeCycleState=u.UNMOUNTED,this._pendingProps=null,this._pendingCallbacks=null,this._pendingOwner=this._owner;var o=arguments.length-1;if(1===o)this.props.children=e;else if(o>1){for(var r=Array(o),i=0;o>i;i++)r[i]=arguments[i+1];this.props.children=r}},mountComponent:function(t,e,n){i(!this.isMounted());var r=this.props;null!=r.ref&&o.addComponentAsRefTo(this,r.ref,this._owner),this._rootNodeID=t,this._lifeCycleState=u.MOUNTED,this._mountDepth=n},unmountComponent:function(){i(this.isMounted());var t=this.props;null!=t.ref&&o.removeComponentAsRefFrom(this,t.ref,this._owner),l(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=u.UNMOUNTED},receiveComponent:function(t,e){i(this.isMounted()),this._pendingOwner=t._owner,this._pendingProps=t.props,this._performUpdateIfNecessary(e)},performUpdateIfNecessary:function(){var t=d.ReactReconcileTransaction.getPooled();t.perform(this._performUpdateIfNecessary,this,t),d.ReactReconcileTransaction.release(t)},_performUpdateIfNecessary:function(t){if(null!=this._pendingProps){var e=this.props,n=this._owner;this.props=this._pendingProps,this._owner=this._pendingOwner,this._pendingProps=null,this.updateComponent(t,e,n)}},updateComponent:function(t,e,n){var r=this.props;(this._owner!==n||r.ref!==e.ref)&&(null!=e.ref&&o.removeComponentAsRefFrom(this,e.ref,n),null!=r.ref&&o.addComponentAsRefTo(this,r.ref,this._owner))},mountComponentIntoNode:function(t,e,n){var o=d.ReactReconcileTransaction.getPooled();o.perform(this._mountComponentIntoNode,this,t,e,o,n),d.ReactReconcileTransaction.release(o)},_mountComponentIntoNode:function(t,e,n,o){var r=this.mountComponent(t,n,0);p(r,e,o)},isOwnedBy:function(t){return this._owner===t},getSiblingByRef:function(t){var e=this._owner;return e&&e.refs?e.refs[t]:null}}};e.exports=d},{"./ReactCurrentOwner":35,"./ReactOwner":62,"./ReactUpdates":78,"./invariant":122,"./keyMirror":128,"./merge":131,"./monitorCodeUse":135}],32:[function(t,e){"use strict";var n=t("./ReactDOMIDOperations"),o=t("./ReactMarkupChecksum"),r=t("./ReactMount"),i=t("./ReactPerf"),a=t("./ReactReconcileTransaction"),s=t("./getReactRootElementInContainer"),u=t("./invariant"),c=1,l=9,p={ReactReconcileTransaction:a,BackendIDOperations:n,unmountIDFromEnvironment:function(t){r.purgeID(t)},mountImageIntoNode:i.measure("ReactComponentBrowserEnvironment","mountImageIntoNode",function(t,e,n){if(u(e&&(e.nodeType===c||e.nodeType===l)),n){if(o.canReuseMarkup(t,s(e)))return;u(e.nodeType!==l)}u(e.nodeType!==l),e.innerHTML=t})};e.exports=p},{"./ReactDOMIDOperations":40,"./ReactMarkupChecksum":57,"./ReactMount":58,"./ReactPerf":63,"./ReactReconcileTransaction":69,"./getReactRootElementInContainer":117,"./invariant":122}],33:[function(t,e){"use strict";function n(t,e){for(var n in e)e.hasOwnProperty(n)&&R("function"==typeof e[n])}function o(t,e){var n=S[e];_.hasOwnProperty(e)&&R(n===b.OVERRIDE_BASE),t.hasOwnProperty(e)&&R(n===b.DEFINE_MANY||n===b.DEFINE_MANY_MERGED)}function r(t){var e=t._compositeLifeCycleState;R(t.isMounted()||e===I.MOUNTING),R(e!==I.RECEIVING_STATE),R(e!==I.UNMOUNTING)}function i(t,e){R(!l(e)),R(!p.isValidComponent(e));var n=t.componentConstructor,r=n.prototype;for(var i in e){var a=e[i];if(e.hasOwnProperty(i))if(o(r,i),N.hasOwnProperty(i))N[i](t,a);else{var s=i in S,d=i in r,h=a&&a.__reactDontBind,f="function"==typeof a,m=f&&!s&&!d&&!h;m?(r.__reactAutoBindMap||(r.__reactAutoBindMap={}),r.__reactAutoBindMap[i]=a,r[i]=a):r[i]=d?S[i]===b.DEFINE_MANY_MERGED?u(r[i],a):c(r[i],a):a}}}function a(t,e){if(e)for(var n in e){var o=e[n];if(!e.hasOwnProperty(n))return;var r=n in t,i=o;if(r){var a=t[n],s=typeof a,u=typeof o;R("function"===s&&"function"===u),i=c(a,o)}t[n]=i,t.componentConstructor[n]=i}}function s(t,e){return R(t&&e&&"object"==typeof t&&"object"==typeof e),P(e,function(e,n){R(void 0===t[n]),t[n]=e}),t}function u(t,e){return function(){var n=t.apply(this,arguments),o=e.apply(this,arguments);return null==n?o:null==o?n:s(n,o)}}function c(t,e){return function(){t.apply(this,arguments),e.apply(this,arguments)}}function l(t){return t instanceof Function&&"componentConstructor"in t&&t.componentConstructor instanceof Function}var p=t("./ReactComponent"),d=t("./ReactContext"),h=t("./ReactCurrentOwner"),f=t("./ReactErrorUtils"),m=t("./ReactOwner"),v=t("./ReactPerf"),g=t("./ReactPropTransferer"),y=t("./ReactPropTypeLocations"),C=(t("./ReactPropTypeLocationNames"),t("./ReactUpdates")),E=t("./instantiateReactComponent"),R=t("./invariant"),M=t("./keyMirror"),D=t("./merge"),x=t("./mixInto"),P=(t("./monitorCodeUse"),t("./objMap")),T=t("./shouldUpdateReactComponent"),b=(t("./warning"),M({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null})),O=[],S={mixins:b.DEFINE_MANY,statics:b.DEFINE_MANY,propTypes:b.DEFINE_MANY,contextTypes:b.DEFINE_MANY,childContextTypes:b.DEFINE_MANY,getDefaultProps:b.DEFINE_MANY_MERGED,getInitialState:b.DEFINE_MANY_MERGED,getChildContext:b.DEFINE_MANY_MERGED,render:b.DEFINE_ONCE,componentWillMount:b.DEFINE_MANY,componentDidMount:b.DEFINE_MANY,componentWillReceiveProps:b.DEFINE_MANY,shouldComponentUpdate:b.DEFINE_ONCE,componentWillUpdate:b.DEFINE_MANY,componentDidUpdate:b.DEFINE_MANY,componentWillUnmount:b.DEFINE_MANY,updateComponent:b.OVERRIDE_BASE},N={displayName:function(t,e){t.componentConstructor.displayName=e},mixins:function(t,e){if(e)for(var n=0;n<e.length;n++)i(t,e[n])},childContextTypes:function(t,e){var o=t.componentConstructor;n(o,e,y.childContext),o.childContextTypes=D(o.childContextTypes,e)},contextTypes:function(t,e){var o=t.componentConstructor;n(o,e,y.context),o.contextTypes=D(o.contextTypes,e)},propTypes:function(t,e){var o=t.componentConstructor;n(o,e,y.prop),o.propTypes=D(o.propTypes,e)},statics:function(t,e){a(t,e)}},I=M({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null,RECEIVING_STATE:null}),_={construct:function(){p.Mixin.construct.apply(this,arguments),m.Mixin.construct.apply(this,arguments),this.state=null,this._pendingState=null,this.context=null,this._currentContext=d.current,this._pendingContext=null,this._descriptor=null,this._compositeLifeCycleState=null},toJSON:function(){return{type:this.type,props:this.props}},isMounted:function(){return p.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==I.MOUNTING},mountComponent:v.measure("ReactCompositeComponent","mountComponent",function(t,e,n){p.Mixin.mountComponent.call(this,t,e,n),this._compositeLifeCycleState=I.MOUNTING,this.context=this._processContext(this._currentContext),this._defaultProps=this.getDefaultProps?this.getDefaultProps():null,this.props=this._processProps(this.props),this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.state=this.getInitialState?this.getInitialState():null,R("object"==typeof this.state&&!Array.isArray(this.state)),this._pendingState=null,this._pendingForceUpdate=!1,this.componentWillMount&&(this.componentWillMount(),this._pendingState&&(this.state=this._pendingState,this._pendingState=null)),this._renderedComponent=E(this._renderValidatedComponent()),this._compositeLifeCycleState=null;var o=this._renderedComponent.mountComponent(t,e,n+1);return this.componentDidMount&&e.getReactMountReady().enqueue(this,this.componentDidMount),o}),unmountComponent:function(){this._compositeLifeCycleState=I.UNMOUNTING,this.componentWillUnmount&&this.componentWillUnmount(),this._compositeLifeCycleState=null,this._defaultProps=null,this._renderedComponent.unmountComponent(),this._renderedComponent=null,p.Mixin.unmountComponent.call(this)},setState:function(t,e){R("object"==typeof t||null==t),this.replaceState(D(this._pendingState||this.state,t),e)},replaceState:function(t,e){r(this),this._pendingState=t,C.enqueueUpdate(this,e)},_processContext:function(t){var e=null,n=this.constructor.contextTypes;if(n){e={};for(var o in n)e[o]=t[o]}return e},_processChildContext:function(t){var e=this.getChildContext&&this.getChildContext();if(this.constructor.displayName||"ReactCompositeComponent",e){R("object"==typeof this.constructor.childContextTypes);for(var n in e)R(n in this.constructor.childContextTypes);return D(t,e)}return t},_processProps:function(t){var e=D(t),n=this._defaultProps;for(var o in n)"undefined"==typeof e[o]&&(e[o]=n[o]);return e},_checkPropTypes:function(t,e,n){var o=this.constructor.displayName;for(var r in t)t.hasOwnProperty(r)&&t[r](e,r,o,n)},performUpdateIfNecessary:function(){var t=this._compositeLifeCycleState;t!==I.MOUNTING&&t!==I.RECEIVING_PROPS&&p.Mixin.performUpdateIfNecessary.call(this)},_performUpdateIfNecessary:function(t){if(null!=this._pendingProps||null!=this._pendingState||null!=this._pendingContext||this._pendingForceUpdate){var e=this._pendingContext||this._currentContext,n=this._processContext(e);this._pendingContext=null;var o=this.props;null!=this._pendingProps&&(o=this._processProps(this._pendingProps),this._pendingProps=null,this._compositeLifeCycleState=I.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(o,n)),this._compositeLifeCycleState=I.RECEIVING_STATE;var r=this._pendingOwner,i=this._pendingState||this.state;this._pendingState=null;try{this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(o,i,n)?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,r,i,e,n,t)):(this.props=o,this._owner=r,this.state=i,this._currentContext=e,this.context=n)}finally{this._compositeLifeCycleState=null}}},_performComponentUpdate:function(t,e,n,o,r,i){var a=this.props,s=this._owner,u=this.state,c=this.context;this.componentWillUpdate&&this.componentWillUpdate(t,n,r),this.props=t,this._owner=e,this.state=n,this._currentContext=o,this.context=r,this.updateComponent(i,a,s,u,c),this.componentDidUpdate&&i.getReactMountReady().enqueue(this,this.componentDidUpdate.bind(this,a,u,c))},receiveComponent:function(t,e){t!==this._descriptor&&(this._descriptor=t,this._pendingContext=t._currentContext,p.Mixin.receiveComponent.call(this,t,e))},updateComponent:v.measure("ReactCompositeComponent","updateComponent",function(t,e,n){p.Mixin.updateComponent.call(this,t,e,n);var o=this._renderedComponent,r=this._renderValidatedComponent();if(T(o,r))o.receiveComponent(r,t);else{var i=this._rootNodeID,a=o._rootNodeID;o.unmountComponent(),this._renderedComponent=E(r);var s=this._renderedComponent.mountComponent(i,t,this._mountDepth+1);p.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(a,s)}}),forceUpdate:function(t){var e=this._compositeLifeCycleState;R(this.isMounted()||e===I.MOUNTING),R(e!==I.RECEIVING_STATE&&e!==I.UNMOUNTING),this._pendingForceUpdate=!0,C.enqueueUpdate(this,t)},_renderValidatedComponent:v.measure("ReactCompositeComponent","_renderValidatedComponent",function(){var t,e=d.current;d.current=this._processChildContext(this._currentContext),h.current=this;try{t=this.render()}finally{d.current=e,h.current=null}return R(p.isValidComponent(t)),t}),_bindAutoBindMethods:function(){for(var t in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(t)){var e=this.__reactAutoBindMap[t];this[t]=this._bindAutoBindMethod(f.guard(e,this.constructor.displayName+"."+t))}},_bindAutoBindMethod:function(t){var e=this,n=function(){return t.apply(e,arguments)};return n}},w=function(){};x(w,p.Mixin),x(w,m.Mixin),x(w,g.Mixin),x(w,_);var A={LifeCycle:I,Base:w,createClass:function(t){var e=function(){};e.prototype=new w,e.prototype.constructor=e;var n=e,o=function(){var t=new n;return t.construct.apply(t,arguments),t};o.componentConstructor=e,e.ConvenienceConstructor=o,o.originalSpec=t,O.forEach(i.bind(null,o)),i(o,t),R(e.prototype.render),o.type=e,e.prototype.type=e;for(var r in S)e.prototype[r]||(e.prototype[r]=null);return o},isValidClass:l,injection:{injectMixin:function(t){O.push(t)}}};e.exports=A},{"./ReactComponent":31,"./ReactContext":34,"./ReactCurrentOwner":35,"./ReactErrorUtils":49,"./ReactOwner":62,"./ReactPerf":63,"./ReactPropTransferer":64,"./ReactPropTypeLocationNames":65,"./ReactPropTypeLocations":66,"./ReactUpdates":78,"./instantiateReactComponent":121,"./invariant":122,"./keyMirror":128,"./merge":131,"./mixInto":134,"./monitorCodeUse":135,"./objMap":136,"./shouldUpdateReactComponent":140,"./warning":144}],34:[function(t,e){"use strict";var n=t("./merge"),o={current:{},withContext:function(t,e){var r,i=o.current;o.current=n(i,t);try{r=e()}finally{o.current=i}return r}};e.exports=o},{"./merge":131}],35:[function(t,e){"use strict";var n={current:null};e.exports=n},{}],36:[function(t,e){"use strict";function n(t,e){var n=function(){};n.prototype=new o(t,e),n.prototype.constructor=n,n.displayName=t;var r=function(){var t=new n;return t.construct.apply(t,arguments),t};return r.type=n,n.prototype.type=n,n.ConvenienceConstructor=r,r.componentConstructor=n,r}var o=t("./ReactDOMComponent"),r=t("./mergeInto"),i=t("./objMapKeyVal"),a=i({a:!1,abbr:!1,address:!1,area:!0,article:!1,aside:!1,audio:!1,b:!1,base:!0,bdi:!1,bdo:!1,big:!1,blockquote:!1,body:!1,br:!0,button:!1,canvas:!1,caption:!1,cite:!1,code:!1,col:!0,colgroup:!1,data:!1,datalist:!1,dd:!1,del:!1,details:!1,dfn:!1,div:!1,dl:!1,dt:!1,em:!1,embed:!0,fieldset:!1,figcaption:!1,figure:!1,footer:!1,form:!1,h1:!1,h2:!1,h3:!1,h4:!1,h5:!1,h6:!1,head:!1,header:!1,hr:!0,html:!1,i:!1,iframe:!1,img:!0,input:!0,ins:!1,kbd:!1,keygen:!0,label:!1,legend:!1,li:!1,link:!0,main:!1,map:!1,mark:!1,menu:!1,menuitem:!1,meta:!0,meter:!1,nav:!1,noscript:!1,object:!1,ol:!1,optgroup:!1,option:!1,output:!1,p:!1,param:!0,pre:!1,progress:!1,q:!1,rp:!1,rt:!1,ruby:!1,s:!1,samp:!1,script:!1,section:!1,select:!1,small:!1,source:!0,span:!1,strong:!1,style:!1,sub:!1,summary:!1,sup:!1,table:!1,tbody:!1,td:!1,textarea:!1,tfoot:!1,th:!1,thead:!1,time:!1,title:!1,tr:!1,track:!0,u:!1,ul:!1,"var":!1,video:!1,wbr:!0,circle:!1,defs:!1,g:!1,line:!1,linearGradient:!1,path:!1,polygon:!1,polyline:!1,radialGradient:!1,rect:!1,stop:!1,svg:!1,text:!1},n),s={injectComponentClasses:function(t){r(a,t)}};a.injection=s,e.exports=a},{"./ReactDOMComponent":38,"./mergeInto":133,"./objMapKeyVal":137}],37:[function(t,e){"use strict";var n=t("./AutoFocusMixin"),o=t("./ReactBrowserComponentMixin"),r=t("./ReactCompositeComponent"),i=t("./ReactDOM"),a=t("./keyMirror"),s=i.button,u=a({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=r.createClass({displayName:"ReactDOMButton",mixins:[n,o],render:function(){var t={};for(var e in this.props)!this.props.hasOwnProperty(e)||this.props.disabled&&u[e]||(t[e]=this.props[e]);return s(t,this.props.children)}});e.exports=c},{"./AutoFocusMixin":1,"./ReactBrowserComponentMixin":27,"./ReactCompositeComponent":33,"./ReactDOM":36,"./keyMirror":128}],38:[function(t,e){"use strict";function n(t){t&&(m(null==t.children||null==t.dangerouslySetInnerHTML),m(null==t.style||"object"==typeof t.style))}function o(t,e,n,o){var r=p.findReactContainerForID(t);if(r){var i=r.nodeType===x?r.ownerDocument:r;E(e,i)}o.getPutListenerQueue().enqueuePutListener(t,e,n)}function r(t,e){this._tagOpen="<"+t,this._tagClose=e?"":"</"+t+">",this.tagName=t.toUpperCase()}var i=t("./CSSPropertyOperations"),a=t("./DOMProperty"),s=t("./DOMPropertyOperations"),u=t("./ReactBrowserComponentMixin"),c=t("./ReactComponent"),l=t("./ReactEventEmitter"),p=t("./ReactMount"),d=t("./ReactMultiChild"),h=t("./ReactPerf"),f=t("./escapeTextForBrowser"),m=t("./invariant"),v=t("./keyOf"),g=t("./merge"),y=t("./mixInto"),C=l.deleteListener,E=l.listenTo,R=l.registrationNameModules,M={string:!0,number:!0},D=v({style:null}),x=1;r.Mixin={mountComponent:h.measure("ReactDOMComponent","mountComponent",function(t,e,o){return c.Mixin.mountComponent.call(this,t,e,o),n(this.props),this._createOpenTagMarkupAndPutListeners(e)+this._createContentMarkup(e)+this._tagClose}),_createOpenTagMarkupAndPutListeners:function(t){var e=this.props,n=this._tagOpen;for(var r in e)if(e.hasOwnProperty(r)){var a=e[r];if(null!=a)if(R[r])o(this._rootNodeID,r,a,t);else{r===D&&(a&&(a=e.style=g(e.style)),a=i.createMarkupForStyles(a));var u=s.createMarkupForProperty(r,a);u&&(n+=" "+u)}}if(t.renderToStaticMarkup)return n+">";var c=s.createMarkupForID(this._rootNodeID);return n+" "+c+">"},_createContentMarkup:function(t){var e=this.props.dangerouslySetInnerHTML;if(null!=e){if(null!=e.__html)return e.__html}else{var n=M[typeof this.props.children]?this.props.children:null,o=null!=n?null:this.props.children;if(null!=n)return f(n);if(null!=o){var r=this.mountChildren(o,t);return r.join("")}}return""},receiveComponent:function(t,e){t!==this&&(n(t.props),c.Mixin.receiveComponent.call(this,t,e))},updateComponent:h.measure("ReactDOMComponent","updateComponent",function(t,e,n){c.Mixin.updateComponent.call(this,t,e,n),this._updateDOMProperties(e,t),this._updateDOMChildren(e,t)}),_updateDOMProperties:function(t,e){var n,r,i,s=this.props;for(n in t)if(!s.hasOwnProperty(n)&&t.hasOwnProperty(n))if(n===D){var u=t[n];for(r in u)u.hasOwnProperty(r)&&(i=i||{},i[r]="")}else R[n]?C(this._rootNodeID,n):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in s){var l=s[n],p=t[n];if(s.hasOwnProperty(n)&&l!==p)if(n===D)if(l&&(l=s.style=g(l)),p){for(r in p)p.hasOwnProperty(r)&&!l.hasOwnProperty(r)&&(i=i||{},i[r]="");for(r in l)l.hasOwnProperty(r)&&p[r]!==l[r]&&(i=i||{},i[r]=l[r])}else i=l;else R[n]?o(this._rootNodeID,n,l,e):(a.isStandardName[n]||a.isCustomAttribute(n))&&c.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,l)}i&&c.BackendIDOperations.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(t,e){var n=this.props,o=M[typeof t.children]?t.children:null,r=M[typeof n.children]?n.children:null,i=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,a=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,s=null!=o?null:t.children,u=null!=r?null:n.children,l=null!=o||null!=i,p=null!=r||null!=a;null!=s&&null==u?this.updateChildren(null,e):l&&!p&&this.updateTextContent(""),null!=r?o!==r&&this.updateTextContent(""+r):null!=a?i!==a&&c.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=u&&this.updateChildren(u,e)},unmountComponent:function(){this.unmountChildren(),l.deleteAllListeners(this._rootNodeID),c.Mixin.unmountComponent.call(this)}},y(r,c.Mixin),y(r,r.Mixin),y(r,d.Mixin),y(r,u),e.exports=r},{"./CSSPropertyOperations":4,"./DOMProperty":9,"./DOMPropertyOperations":10,"./ReactBrowserComponentMixin":27,"./ReactComponent":31,"./ReactEventEmitter":50,"./ReactMount":58,"./ReactMultiChild":60,"./ReactPerf":63,"./escapeTextForBrowser":108,"./invariant":122,"./keyOf":129,"./merge":131,"./mixInto":134}],39:[function(t,e){"use strict";var n=t("./ReactBrowserComponentMixin"),o=t("./ReactCompositeComponent"),r=t("./ReactDOM"),i=t("./ReactEventEmitter"),a=t("./EventConstants"),s=r.form,u=o.createClass({displayName:"ReactDOMForm",mixins:[n],render:function(){return this.transferPropsTo(s(null,this.props.children))},componentDidMount:function(){i.trapBubbledEvent(a.topLevelTypes.topReset,"reset",this.getDOMNode()),i.trapBubbledEvent(a.topLevelTypes.topSubmit,"submit",this.getDOMNode())}});e.exports=u},{"./EventConstants":15,"./ReactBrowserComponentMixin":27,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEventEmitter":50}],40:[function(t,e){"use strict";var n,o=t("./CSSPropertyOperations"),r=t("./DOMChildrenOperations"),i=t("./DOMPropertyOperations"),a=t("./ReactMount"),s=t("./ReactPerf"),u=t("./invariant"),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l={updatePropertyByID:s.measure("ReactDOMIDOperations","updatePropertyByID",function(t,e,n){var o=a.getNode(t);u(!c.hasOwnProperty(e)),null!=n?i.setValueForProperty(o,e,n):i.deleteValueForProperty(o,e)}),deletePropertyByID:s.measure("ReactDOMIDOperations","deletePropertyByID",function(t,e,n){var o=a.getNode(t);u(!c.hasOwnProperty(e)),i.deleteValueForProperty(o,e,n)}),updateStylesByID:s.measure("ReactDOMIDOperations","updateStylesByID",function(t,e){var n=a.getNode(t);o.setValueForStyles(n,e)}),updateInnerHTMLByID:s.measure("ReactDOMIDOperations","updateInnerHTMLByID",function(t,e){var o=a.getNode(t);if(void 0===n){var r=document.createElement("div");r.innerHTML=" ",n=""===r.innerHTML}n&&o.parentNode.replaceChild(o,o),n&&e.match(/^[ \r\n\t\f]/)?(o.innerHTML=""+e,o.firstChild.deleteData(0,1)):o.innerHTML=e}),updateTextContentByID:s.measure("ReactDOMIDOperations","updateTextContentByID",function(t,e){var n=a.getNode(t);r.updateTextContent(n,e)}),dangerouslyReplaceNodeWithMarkupByID:s.measure("ReactDOMIDOperations","dangerouslyReplaceNodeWithMarkupByID",function(t,e){var n=a.getNode(t);r.dangerouslyReplaceNodeWithMarkup(n,e)}),dangerouslyProcessChildrenUpdates:s.measure("ReactDOMIDOperations","dangerouslyProcessChildrenUpdates",function(t,e){for(var n=0;n<t.length;n++)t[n].parentNode=a.getNode(t[n].parentID);r.processUpdates(t,e)})};e.exports=l},{"./CSSPropertyOperations":4,"./DOMChildrenOperations":8,"./DOMPropertyOperations":10,"./ReactMount":58,"./ReactPerf":63,"./invariant":122}],41:[function(t,e){"use strict";var n=t("./ReactBrowserComponentMixin"),o=t("./ReactCompositeComponent"),r=t("./ReactDOM"),i=t("./ReactEventEmitter"),a=t("./EventConstants"),s=r.img,u=o.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[n],render:function(){return s(this.props)},componentDidMount:function(){var t=this.getDOMNode();i.trapBubbledEvent(a.topLevelTypes.topLoad,"load",t),i.trapBubbledEvent(a.topLevelTypes.topError,"error",t)}});e.exports=u},{"./EventConstants":15,"./ReactBrowserComponentMixin":27,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEventEmitter":50}],42:[function(t,e){"use strict";var n=t("./AutoFocusMixin"),o=t("./DOMPropertyOperations"),r=t("./LinkedValueUtils"),i=t("./ReactBrowserComponentMixin"),a=t("./ReactCompositeComponent"),s=t("./ReactDOM"),u=t("./ReactMount"),c=t("./invariant"),l=t("./merge"),p=s.input,d={},h=a.createClass({displayName:"ReactDOMInput",mixins:[n,r.Mixin,i],getInitialState:function(){var t=this.props.defaultValue;return{checked:this.props.defaultChecked||!1,value:null!=t?t:null}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var t=l(this.props);t.defaultChecked=null,t.defaultValue=null;var e=r.getValue(this);t.value=null!=e?e:this.state.value;var n=r.getChecked(this);return t.checked=null!=n?n:this.state.checked,t.onChange=this._handleChange,p(t,this.props.children)},componentDidMount:function(){var t=u.getID(this.getDOMNode());d[t]=this},componentWillUnmount:function(){var t=this.getDOMNode(),e=u.getID(t);delete d[e]},componentDidUpdate:function(){var t=this.getDOMNode();null!=this.props.checked&&o.setValueForProperty(t,"checked",this.props.checked||!1);var e=r.getValue(this);null!=e&&o.setValueForProperty(t,"value",""+e)},_handleChange:function(t){var e,n=r.getOnChange(this);n&&(this._isChanging=!0,e=n.call(this,t),this._isChanging=!1),this.setState({checked:t.target.checked,value:t.target.value});var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var i=this.getDOMNode(),a=i;a.parentNode;)a=a.parentNode;for(var s=a.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),l=0,p=s.length;p>l;l++){var h=s[l];if(h!==i&&h.form===i.form){var f=u.getID(h);c(f);var m=d[f];c(m),m.setState({checked:!1})}}}return e}});e.exports=h},{"./AutoFocusMixin":1,"./DOMPropertyOperations":10,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":27,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactMount":58,"./invariant":122,"./merge":131}],43:[function(t,e){"use strict";var n=t("./ReactBrowserComponentMixin"),o=t("./ReactCompositeComponent"),r=t("./ReactDOM"),i=(t("./warning"),r.option),a=o.createClass({displayName:"ReactDOMOption",mixins:[n],componentWillMount:function(){},render:function(){return i(this.props,this.props.children)}});e.exports=a},{"./ReactBrowserComponentMixin":27,"./ReactCompositeComponent":33,"./ReactDOM":36,"./warning":144}],44:[function(t,e){"use strict";function n(t,e){null!=t[e]&&c(t.multiple?Array.isArray(t[e]):!Array.isArray(t[e]))}function o(t,e){var n,o,r,i=t.props.multiple,a=null!=e?e:t.state.value,s=t.getDOMNode().options;if(i)for(n={},o=0,r=a.length;r>o;++o)n[""+a[o]]=!0;else n=""+a;for(o=0,r=s.length;r>o;o++){var u=i?n.hasOwnProperty(s[o].value):s[o].value===n;u!==s[o].selected&&(s[o].selected=u)}}var r=t("./AutoFocusMixin"),i=t("./LinkedValueUtils"),a=t("./ReactBrowserComponentMixin"),s=t("./ReactCompositeComponent"),u=t("./ReactDOM"),c=t("./invariant"),l=t("./merge"),p=u.select,d=s.createClass({displayName:"ReactDOMSelect",mixins:[r,i.Mixin,a],propTypes:{defaultValue:n,value:n},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},componentWillReceiveProps:function(t){!this.props.multiple&&t.multiple?this.setState({value:[this.state.value]}):this.props.multiple&&!t.multiple&&this.setState({value:this.state.value[0]})},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var t=l(this.props);return t.onChange=this._handleChange,t.value=null,p(t,this.props.children)},componentDidMount:function(){o(this,i.getValue(this))},componentDidUpdate:function(){var t=i.getValue(this);null!=t&&o(this,t)},_handleChange:function(t){var e,n=i.getOnChange(this);n&&(this._isChanging=!0,e=n.call(this,t),this._isChanging=!1);var o;if(this.props.multiple){o=[];for(var r=t.target.options,a=0,s=r.length;s>a;a++)r[a].selected&&o.push(r[a].value)}else o=t.target.value;return this.setState({value:o}),e}});e.exports=d},{"./AutoFocusMixin":1,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":27,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":122,"./merge":131}],45:[function(t,e){"use strict";function n(t){var e=document.selection,n=e.createRange(),o=n.text.length,r=n.duplicate();r.moveToElementText(t),r.setEndPoint("EndToStart",n);var i=r.text.length,a=i+o;return{start:i,end:a}}function o(t){var e=window.getSelection();if(0===e.rangeCount)return null;var n=e.anchorNode,o=e.anchorOffset,r=e.focusNode,i=e.focusOffset,a=e.getRangeAt(0),s=a.toString().length,u=a.cloneRange();u.selectNodeContents(t),u.setEnd(a.startContainer,a.startOffset);var c=u.toString().length,l=c+s,p=document.createRange();p.setStart(n,o),p.setEnd(r,i);var d=p.collapsed;return p.detach(),{start:d?l:c,end:d?c:l}}function r(t,e){var n,o,r=document.selection.createRange().duplicate();"undefined"==typeof e.end?(n=e.start,o=n):e.start>e.end?(n=e.end,o=e.start):(n=e.start,o=e.end),r.moveToElementText(t),r.moveStart("character",n),r.setEndPoint("EndToStart",r),r.moveEnd("character",o-n),r.select()}function i(t,e){var n=window.getSelection(),o=t[s()].length,r=Math.min(e.start,o),i="undefined"==typeof e.end?r:Math.min(e.end,o);if(!n.extend&&r>i){var u=i;i=r,r=u}var c=a(t,r),l=a(t,i);if(c&&l){var p=document.createRange();p.setStart(c.node,c.offset),n.removeAllRanges(),r>i?(n.addRange(p),n.extend(l.node,l.offset)):(p.setEnd(l.node,l.offset),n.addRange(p)),p.detach()}}var a=t("./getNodeForCharacterOffset"),s=t("./getTextContentAccessor"),u={getOffsets:function(t){var e=document.selection?n:o;return e(t)},setOffsets:function(t,e){var n=document.selection?r:i;n(t,e)}};e.exports=u},{"./getNodeForCharacterOffset":116,"./getTextContentAccessor":118}],46:[function(t,e){"use strict";var n=t("./AutoFocusMixin"),o=t("./DOMPropertyOperations"),r=t("./LinkedValueUtils"),i=t("./ReactBrowserComponentMixin"),a=t("./ReactCompositeComponent"),s=t("./ReactDOM"),u=t("./invariant"),c=t("./merge"),l=(t("./warning"),s.textarea),p=a.createClass({displayName:"ReactDOMTextarea",mixins:[n,r.Mixin,i],getInitialState:function(){var t=this.props.defaultValue,e=this.props.children;null!=e&&(u(null==t),Array.isArray(e)&&(u(e.length<=1),e=e[0]),t=""+e),null==t&&(t="");var n=r.getValue(this);return{initialValue:""+(null!=n?n:t),value:t}},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var t=c(this.props),e=r.getValue(this);return u(null==t.dangerouslySetInnerHTML),t.defaultValue=null,t.value=null!=e?e:this.state.value,t.onChange=this._handleChange,l(t,this.state.initialValue)},componentDidUpdate:function(){var t=r.getValue(this);if(null!=t){var e=this.getDOMNode();o.setValueForProperty(e,"value",""+t)}},_handleChange:function(t){var e,n=r.getOnChange(this);return n&&(this._isChanging=!0,e=n.call(this,t),this._isChanging=!1),this.setState({value:t.target.value}),e}});e.exports=p},{"./AutoFocusMixin":1,"./DOMPropertyOperations":10,"./LinkedValueUtils":23,"./ReactBrowserComponentMixin":27,"./ReactCompositeComponent":33,"./ReactDOM":36,"./invariant":122,"./merge":131,"./warning":144}],47:[function(t,e){"use strict";function n(){this.reinitializeTransaction()}var o=t("./ReactUpdates"),r=t("./Transaction"),i=t("./emptyFunction"),a=t("./mixInto"),s={initialize:i,close:function(){p.isBatchingUpdates=!1}},u={initialize:i,close:o.flushBatchedUpdates.bind(o)},c=[u,s];a(n,r.Mixin),a(n,{getTransactionWrappers:function(){return c}});var l=new n,p={isBatchingUpdates:!1,batchedUpdates:function(t,e){var n=p.isBatchingUpdates;p.isBatchingUpdates=!0,n?t(e):l.perform(t,null,e)}};e.exports=p},{"./ReactUpdates":78,"./Transaction":93,"./emptyFunction":106,"./mixInto":134}],48:[function(t,e){"use strict";function n(){o.EventEmitter.injectTopLevelCallbackCreator(f),o.EventPluginHub.injectEventPluginOrder(c),o.EventPluginHub.injectInstanceHandle(D),o.EventPluginHub.injectMount(x),o.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:b,EnterLeaveEventPlugin:l,ChangeEventPlugin:a,CompositionEventPlugin:u,MobileSafariClickEventPlugin:p,SelectEventPlugin:P}),o.DOM.injectComponentClasses({button:v,form:g,img:y,input:C,option:E,select:R,textarea:M,html:S(m.html),head:S(m.head),title:S(m.title),body:S(m.body)}),o.CompositeComponent.injectMixin(d),o.DOMProperty.injectDOMPropertyConfig(i),o.Updates.injectBatchingStrategy(O),o.RootIndex.injectCreateReactRootIndex(r.canUseDOM?s.createReactRootIndex:T.createReactRootIndex),o.Component.injectEnvironment(h)}var o=t("./ReactInjection"),r=t("./ExecutionEnvironment"),i=t("./DefaultDOMPropertyConfig"),a=t("./ChangeEventPlugin"),s=t("./ClientReactRootIndex"),u=t("./CompositionEventPlugin"),c=t("./DefaultEventPluginOrder"),l=t("./EnterLeaveEventPlugin"),p=t("./MobileSafariClickEventPlugin"),d=t("./ReactBrowserComponentMixin"),h=t("./ReactComponentBrowserEnvironment"),f=t("./ReactEventTopLevelCallback"),m=t("./ReactDOM"),v=t("./ReactDOMButton"),g=t("./ReactDOMForm"),y=t("./ReactDOMImg"),C=t("./ReactDOMInput"),E=t("./ReactDOMOption"),R=t("./ReactDOMSelect"),M=t("./ReactDOMTextarea"),D=t("./ReactInstanceHandles"),x=t("./ReactMount"),P=t("./SelectEventPlugin"),T=t("./ServerReactRootIndex"),b=t("./SimpleEventPlugin"),O=t("./ReactDefaultBatchingStrategy"),S=t("./createFullPageComponent");e.exports={inject:n}},{"./ChangeEventPlugin":5,"./ClientReactRootIndex":6,"./CompositionEventPlugin":7,"./DefaultDOMPropertyConfig":12,"./DefaultEventPluginOrder":13,"./EnterLeaveEventPlugin":14,"./ExecutionEnvironment":21,"./MobileSafariClickEventPlugin":24,"./ReactBrowserComponentMixin":27,"./ReactComponentBrowserEnvironment":32,"./ReactDOM":36,"./ReactDOMButton":37,"./ReactDOMForm":39,"./ReactDOMImg":41,"./ReactDOMInput":42,"./ReactDOMOption":43,"./ReactDOMSelect":44,"./ReactDOMTextarea":46,"./ReactDefaultBatchingStrategy":47,"./ReactEventTopLevelCallback":52,"./ReactInjection":53,"./ReactInstanceHandles":55,"./ReactMount":58,"./SelectEventPlugin":80,"./ServerReactRootIndex":81,"./SimpleEventPlugin":82,"./createFullPageComponent":101}],49:[function(t,e){"use strict";var n={guard:function(t){return t}};e.exports=n},{}],50:[function(t,e){"use strict";function n(t){return null==t[C]&&(t[C]=g++,m[t[C]]={}),m[t[C]]}function o(t,e,n){a.listen(n,e,E.TopLevelCallbackCreator.createTopLevelCallback(t))}function r(t,e,n){a.capture(n,e,E.TopLevelCallbackCreator.createTopLevelCallback(t))}var i=t("./EventConstants"),a=t("./EventListener"),s=t("./EventPluginHub"),u=t("./EventPluginRegistry"),c=t("./ExecutionEnvironment"),l=t("./ReactEventEmitterMixin"),p=t("./ViewportMetrics"),d=t("./invariant"),h=t("./isEventSupported"),f=t("./merge"),m={},v=!1,g=0,y={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},C="_reactListenersID"+String(Math.random()).slice(2),E=f(l,{TopLevelCallbackCreator:null,injection:{injectTopLevelCallbackCreator:function(t){E.TopLevelCallbackCreator=t }},setEnabled:function(t){d(c.canUseDOM),E.TopLevelCallbackCreator&&E.TopLevelCallbackCreator.setEnabled(t)},isEnabled:function(){return!(!E.TopLevelCallbackCreator||!E.TopLevelCallbackCreator.isEnabled())},listenTo:function(t,e){for(var a=e,s=n(a),c=u.registrationNameDependencies[t],l=i.topLevelTypes,p=0,d=c.length;d>p;p++){var f=c[p];if(!s[f]){var m=l[f];m===l.topWheel?h("wheel")?o(l.topWheel,"wheel",a):h("mousewheel")?o(l.topWheel,"mousewheel",a):o(l.topWheel,"DOMMouseScroll",a):m===l.topScroll?h("scroll",!0)?r(l.topScroll,"scroll",a):o(l.topScroll,"scroll",window):m===l.topFocus||m===l.topBlur?(h("focus",!0)?(r(l.topFocus,"focus",a),r(l.topBlur,"blur",a)):h("focusin")&&(o(l.topFocus,"focusin",a),o(l.topBlur,"focusout",a)),s[l.topBlur]=!0,s[l.topFocus]=!0):y[f]&&o(m,y[f],a),s[f]=!0}}},ensureScrollValueMonitoring:function(){if(!v){var t=p.refreshScrollValues;a.listen(window,"scroll",t),a.listen(window,"resize",t),v=!0}},eventNameDispatchConfigs:s.eventNameDispatchConfigs,registrationNameModules:s.registrationNameModules,putListener:s.putListener,getListener:s.getListener,deleteListener:s.deleteListener,deleteAllListeners:s.deleteAllListeners,trapBubbledEvent:o,trapCapturedEvent:r});e.exports=E},{"./EventConstants":15,"./EventListener":16,"./EventPluginHub":17,"./EventPluginRegistry":18,"./ExecutionEnvironment":21,"./ReactEventEmitterMixin":51,"./ViewportMetrics":94,"./invariant":122,"./isEventSupported":123,"./merge":131}],51:[function(t,e){"use strict";function n(t){o.enqueueEvents(t),o.processEventQueue()}var o=t("./EventPluginHub"),r=t("./ReactUpdates"),i={handleTopLevel:function(t,e,i,a){var s=o.extractEvents(t,e,i,a);r.batchedUpdates(n,s)}};e.exports=i},{"./EventPluginHub":17,"./ReactUpdates":78}],52:[function(t,e){"use strict";function n(t){var e=u.getID(t),n=s.getReactRootIDFromNodeID(e),o=u.findReactContainerForID(n),r=u.getFirstReactDOM(o);return r}function o(t,e,o){for(var r=u.getFirstReactDOM(c(e))||window,i=r;i;)o.ancestors.push(i),i=n(i);for(var s=0,l=o.ancestors.length;l>s;s++){r=o.ancestors[s];var p=u.getID(r)||"";a.handleTopLevel(t,r,p,e)}}function r(){this.ancestors=[]}var i=t("./PooledClass"),a=t("./ReactEventEmitter"),s=t("./ReactInstanceHandles"),u=t("./ReactMount"),c=t("./getEventTarget"),l=t("./mixInto"),p=!0;l(r,{destructor:function(){this.ancestors.length=0}}),i.addPoolingTo(r);var d={setEnabled:function(t){p=!!t},isEnabled:function(){return p},createTopLevelCallback:function(t){return function(e){if(p){var n=r.getPooled();try{o(t,e,n)}finally{r.release(n)}}}}};e.exports=d},{"./PooledClass":25,"./ReactEventEmitter":50,"./ReactInstanceHandles":55,"./ReactMount":58,"./getEventTarget":114,"./mixInto":134}],53:[function(t,e){"use strict";var n=t("./DOMProperty"),o=t("./EventPluginHub"),r=t("./ReactComponent"),i=t("./ReactCompositeComponent"),a=t("./ReactDOM"),s=t("./ReactEventEmitter"),u=t("./ReactPerf"),c=t("./ReactRootIndex"),l=t("./ReactUpdates"),p={Component:r.injection,CompositeComponent:i.injection,DOMProperty:n.injection,EventPluginHub:o.injection,DOM:a.injection,EventEmitter:s.injection,Perf:u.injection,RootIndex:c.injection,Updates:l.injection};e.exports=p},{"./DOMProperty":9,"./EventPluginHub":17,"./ReactComponent":31,"./ReactCompositeComponent":33,"./ReactDOM":36,"./ReactEventEmitter":50,"./ReactPerf":63,"./ReactRootIndex":70,"./ReactUpdates":78}],54:[function(t,e){"use strict";function n(t){return r(document.documentElement,t)}var o=t("./ReactDOMSelection"),r=t("./containsNode"),i=t("./focusNode"),a=t("./getActiveElement"),s={hasSelectionCapabilities:function(t){return t&&("INPUT"===t.nodeName&&"text"===t.type||"TEXTAREA"===t.nodeName||"true"===t.contentEditable)},getSelectionInformation:function(){var t=a();return{focusedElem:t,selectionRange:s.hasSelectionCapabilities(t)?s.getSelection(t):null}},restoreSelection:function(t){var e=a(),o=t.focusedElem,r=t.selectionRange;e!==o&&n(o)&&(s.hasSelectionCapabilities(o)&&s.setSelection(o,r),i(o))},getSelection:function(t){var e;if("selectionStart"in t)e={start:t.selectionStart,end:t.selectionEnd};else if(document.selection&&"INPUT"===t.nodeName){var n=document.selection.createRange();n.parentElement()===t&&(e={start:-n.moveStart("character",-t.value.length),end:-n.moveEnd("character",-t.value.length)})}else e=o.getOffsets(t);return e||{start:0,end:0}},setSelection:function(t,e){var n=e.start,r=e.end;if("undefined"==typeof r&&(r=n),"selectionStart"in t)t.selectionStart=n,t.selectionEnd=Math.min(r,t.value.length);else if(document.selection&&"INPUT"===t.nodeName){var i=t.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(t,e)}};e.exports=s},{"./ReactDOMSelection":45,"./containsNode":98,"./focusNode":110,"./getActiveElement":112}],55:[function(t,e){"use strict";function n(t){return d+t.toString(36)}function o(t,e){return t.charAt(e)===d||e===t.length}function r(t){return""===t||t.charAt(0)===d&&t.charAt(t.length-1)!==d}function i(t,e){return 0===e.indexOf(t)&&o(e,t.length)}function a(t){return t?t.substr(0,t.lastIndexOf(d)):""}function s(t,e){if(p(r(t)&&r(e)),p(i(t,e)),t===e)return t;for(var n=t.length+h,a=n;a<e.length&&!o(e,a);a++);return e.substr(0,a)}function u(t,e){var n=Math.min(t.length,e.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(o(t,a)&&o(e,a))i=a;else if(t.charAt(a)!==e.charAt(a))break;var s=t.substr(0,i);return p(r(s)),s}function c(t,e,n,o,r,u){t=t||"",e=e||"",p(t!==e);var c=i(e,t);p(c||i(t,e));for(var l=0,d=c?a:s,h=t;;h=d(h,e)){var m;if(r&&h===t||u&&h===e||(m=n(h,c,o)),m===!1||h===e)break;p(l++<f)}}var l=t("./ReactRootIndex"),p=t("./invariant"),d=".",h=d.length,f=100,m={createReactRootID:function(){return n(l.createReactRootIndex())},createReactID:function(t,e){return t+e},getReactRootIDFromNodeID:function(t){if(t&&t.charAt(0)===d&&t.length>1){var e=t.indexOf(d,1);return e>-1?t.substr(0,e):t}return null},traverseEnterLeave:function(t,e,n,o,r){var i=u(t,e);i!==t&&c(t,i,n,o,!1,!0),i!==e&&c(i,e,n,r,!0,!1)},traverseTwoPhase:function(t,e,n){t&&(c("",t,e,n,!0,!1),c(t,"",e,n,!1,!0))},traverseAncestors:function(t,e,n){c("",t,e,n,!0,!1)},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:d};e.exports=m},{"./ReactRootIndex":70,"./invariant":122}],56:[function(t,e){"use strict";function n(t,e){this.value=t,this.requestChange=e}e.exports=n},{}],57:[function(t,e){"use strict";var n=t("./adler32"),o={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(t){var e=n(t);return t.replace(">"," "+o.CHECKSUM_ATTR_NAME+'="'+e+'">')},canReuseMarkup:function(t,e){var r=e.getAttribute(o.CHECKSUM_ATTR_NAME);r=r&&parseInt(r,10);var i=n(t);return i===r}};e.exports=o},{"./adler32":96}],58:[function(t,e){"use strict";function n(t){var e=v(t);return e&&S.getID(e)}function o(t){var e=r(t);if(e)if(M.hasOwnProperty(e)){var n=M[e];n!==t&&(y(!s(n,e)),M[e]=t)}else M[e]=t;return e}function r(t){return t&&t.getAttribute&&t.getAttribute(R)||""}function i(t,e){var n=r(t);n!==e&&delete M[n],t.setAttribute(R,e),M[e]=t}function a(t){return M.hasOwnProperty(t)&&s(M[t],t)||(M[t]=S.findReactNodeByID(t)),M[t]}function s(t,e){if(t){y(r(t)===e);var n=S.findReactContainerForID(e);if(n&&m(n,t))return!0}return!1}function u(t){delete M[t]}function c(t){var e=M[t];return e&&s(e,t)?void(O=e):!1}function l(t){O=null,h.traverseAncestors(t,c);var e=O;return O=null,e}var p=t("./DOMProperty"),d=t("./ReactEventEmitter"),h=t("./ReactInstanceHandles"),f=t("./ReactPerf"),m=t("./containsNode"),v=t("./getReactRootElementInContainer"),g=t("./instantiateReactComponent"),y=t("./invariant"),C=t("./shouldUpdateReactComponent"),E=h.SEPARATOR,R=p.ID_ATTRIBUTE_NAME,M={},D=1,x=9,P={},T={},b=[],O=null,S={totalInstantiationTime:0,totalInjectionTime:0,useTouchEvents:!1,_instancesByReactRootID:P,scrollMonitor:function(t,e){e()},_updateRootComponent:function(t,e,n,o){var r=e.props;return S.scrollMonitor(n,function(){t.replaceProps(r,o)}),t},_registerComponent:function(t,e){y(e&&(e.nodeType===D||e.nodeType===x)),d.ensureScrollValueMonitoring();var n=S.registerContainer(e);return P[n]=t,n},_renderNewRootComponent:f.measure("ReactMount","_renderNewRootComponent",function(t,e,n){var o=g(t),r=S._registerComponent(o,e);return o.mountComponentIntoNode(r,e,n),o}),renderComponent:function(t,e,o){var r=P[n(e)];if(r){if(C(r,t))return S._updateRootComponent(r,t,e,o);S.unmountComponentAtNode(e)}var i=v(e),a=i&&S.isRenderedByReact(i),s=a&&!r,u=S._renderNewRootComponent(t,e,s);return o&&o.call(u),u},constructAndRenderComponent:function(t,e,n){return S.renderComponent(t(e),n)},constructAndRenderComponentByID:function(t,e,n){var o=document.getElementById(n);return y(o),S.constructAndRenderComponent(t,e,o)},registerContainer:function(t){var e=n(t);return e&&(e=h.getReactRootIDFromNodeID(e)),e||(e=h.createReactRootID()),T[e]=t,e},unmountComponentAtNode:function(t){var e=n(t),o=P[e];return o?(S.unmountComponentFromNode(o,t),delete P[e],delete T[e],!0):!1},unmountComponentFromNode:function(t,e){for(t.unmountComponent(),e.nodeType===x&&(e=e.documentElement);e.lastChild;)e.removeChild(e.lastChild)},findReactContainerForID:function(t){var e=h.getReactRootIDFromNodeID(t),n=T[e];return n},findReactNodeByID:function(t){var e=S.findReactContainerForID(t);return S.findComponentRoot(e,t)},isRenderedByReact:function(t){if(1!==t.nodeType)return!1;var e=S.getID(t);return e?e.charAt(0)===E:!1},getFirstReactDOM:function(t){for(var e=t;e&&e.parentNode!==e;){if(S.isRenderedByReact(e))return e;e=e.parentNode}return null},findComponentRoot:function(t,e){var n=b,o=0,r=l(e)||t;for(n[0]=r.firstChild,n.length=1;o<n.length;){for(var i,a=n[o++];a;){var s=S.getID(a);s?e===s?i=a:h.isAncestorIDOf(s,e)&&(n.length=o=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,y(!1)},getReactRootID:n,getID:o,setID:i,getNode:a,purgeID:u};e.exports=S},{"./DOMProperty":9,"./ReactEventEmitter":50,"./ReactInstanceHandles":55,"./ReactPerf":63,"./containsNode":98,"./getReactRootElementInContainer":117,"./instantiateReactComponent":121,"./invariant":122,"./shouldUpdateReactComponent":140}],59:[function(t,e){"use strict";function n(t){this._queue=t||null}var o=t("./PooledClass"),r=t("./mixInto");r(n,{enqueue:function(t,e){this._queue=this._queue||[],this._queue.push({component:t,callback:e})},notifyAll:function(){var t=this._queue;if(t){this._queue=null;for(var e=0,n=t.length;n>e;e++){var o=t[e].component,r=t[e].callback;r.call(o)}t.length=0}},reset:function(){this._queue=null},destructor:function(){this.reset()}}),o.addPoolingTo(n),e.exports=n},{"./PooledClass":25,"./mixInto":134}],60:[function(t,e){"use strict";function n(t,e,n){f.push({parentID:t,parentNode:null,type:c.INSERT_MARKUP,markupIndex:m.push(e)-1,textContent:null,fromIndex:null,toIndex:n})}function o(t,e,n){f.push({parentID:t,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:e,toIndex:n})}function r(t,e){f.push({parentID:t,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:e,toIndex:null})}function i(t,e){f.push({parentID:t,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:e,fromIndex:null,toIndex:null})}function a(){f.length&&(u.BackendIDOperations.dangerouslyProcessChildrenUpdates(f,m),s())}function s(){f.length=0,m.length=0}var u=t("./ReactComponent"),c=t("./ReactMultiChildUpdateTypes"),l=t("./flattenChildren"),p=t("./instantiateReactComponent"),d=t("./shouldUpdateReactComponent"),h=0,f=[],m=[],v={Mixin:{mountChildren:function(t,e){var n=l(t),o=[],r=0;this._renderedChildren=n;for(var i in n){var a=n[i];if(n.hasOwnProperty(i)){var s=p(a);n[i]=s;var u=this._rootNodeID+i,c=s.mountComponent(u,e,this._mountDepth+1);s._mountIndex=r,o.push(c),r++}}return o},updateTextContent:function(t){h++;var e=!0;try{var n=this._renderedChildren;for(var o in n)n.hasOwnProperty(o)&&this._unmountChildByName(n[o],o);this.setTextContent(t),e=!1}finally{h--,h||(e?s():a())}},updateChildren:function(t,e){h++;var n=!0;try{this._updateChildren(t,e),n=!1}finally{h--,h||(n?s():a())}},_updateChildren:function(t,e){var n=l(t),o=this._renderedChildren;if(n||o){var r,i=0,a=0;for(r in n)if(n.hasOwnProperty(r)){var s=o&&o[r],u=n[r];if(d(s,u))this.moveChild(s,a,i),i=Math.max(s._mountIndex,i),s.receiveComponent(u,e),s._mountIndex=a;else{s&&(i=Math.max(s._mountIndex,i),this._unmountChildByName(s,r));var c=p(u);this._mountChildByNameAtIndex(c,r,a,e)}a++}for(r in o)!o.hasOwnProperty(r)||n&&n[r]||this._unmountChildByName(o[r],r)}},unmountChildren:function(){var t=this._renderedChildren;for(var e in t){var n=t[e];n.unmountComponent&&n.unmountComponent()}this._renderedChildren=null},moveChild:function(t,e,n){t._mountIndex<n&&o(this._rootNodeID,t._mountIndex,e)},createChild:function(t,e){n(this._rootNodeID,e,t._mountIndex)},removeChild:function(t){r(this._rootNodeID,t._mountIndex)},setTextContent:function(t){i(this._rootNodeID,t)},_mountChildByNameAtIndex:function(t,e,n,o){var r=this._rootNodeID+e,i=t.mountComponent(r,o,this._mountDepth+1);t._mountIndex=n,this.createChild(t,i),this._renderedChildren=this._renderedChildren||{},this._renderedChildren[e]=t},_unmountChildByName:function(t,e){u.isValidComponent(t)&&(this.removeChild(t),t._mountIndex=null,t.unmountComponent(),delete this._renderedChildren[e])}}};e.exports=v},{"./ReactComponent":31,"./ReactMultiChildUpdateTypes":61,"./flattenChildren":109,"./instantiateReactComponent":121,"./shouldUpdateReactComponent":140}],61:[function(t,e){"use strict";var n=t("./keyMirror"),o=n({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});e.exports=o},{"./keyMirror":128}],62:[function(t,e){"use strict";var n=t("./emptyObject"),o=t("./invariant"),r={isValidOwner:function(t){return!(!t||"function"!=typeof t.attachRef||"function"!=typeof t.detachRef)},addComponentAsRefTo:function(t,e,n){o(r.isValidOwner(n)),n.attachRef(e,t)},removeComponentAsRefFrom:function(t,e,n){o(r.isValidOwner(n)),n.refs[e]===t&&n.detachRef(e)},Mixin:{construct:function(){this.refs=n},attachRef:function(t,e){o(e.isOwnedBy(this));var r=this.refs===n?this.refs={}:this.refs;r[t]=e},detachRef:function(t){delete this.refs[t]}}};e.exports=r},{"./emptyObject":107,"./invariant":122}],63:[function(t,e){"use strict";function n(t,e,n){return n}var o={enableMeasure:!1,storedMeasure:n,measure:function(t,e,n){return n},injection:{injectMeasure:function(t){o.storedMeasure=t}}};e.exports=o},{}],64:[function(t,e){"use strict";function n(t){return function(e,n,o){e[n]=e.hasOwnProperty(n)?t(e[n],o):o}}var o=t("./emptyFunction"),r=t("./invariant"),i=t("./joinClasses"),a=t("./merge"),s={children:o,className:n(i),key:o,ref:o,style:n(a)},u={TransferStrategies:s,mergeProps:function(t,e){var n=a(t);for(var o in e)if(e.hasOwnProperty(o)){var r=s[o];r&&s.hasOwnProperty(o)?r(n,o,e[o]):n.hasOwnProperty(o)||(n[o]=e[o])}return n},Mixin:{transferPropsTo:function(t){return r(t._owner===this),t.props=u.mergeProps(t.props,this.props),t}}};e.exports=u},{"./emptyFunction":106,"./invariant":122,"./joinClasses":127,"./merge":131}],65:[function(t,e){"use strict";var n={};e.exports=n},{}],66:[function(t,e){"use strict";var n=t("./keyMirror"),o=n({prop:null,context:null,childContext:null});e.exports=o},{"./keyMirror":128}],67:[function(t,e){"use strict";function n(t){switch(typeof t){case"number":case"string":return!0;case"object":if(Array.isArray(t))return t.every(n);if(f.isValidComponent(t))return!0;for(var e in t)if(!n(t[e]))return!1;return!0;default:return!1}}function o(t){var e=typeof t;return"object"===e&&Array.isArray(t)?"array":e}function r(){function t(){return!0}return h(t)}function i(t){function e(e,n){var r=o(n),i=r===t;return i}return h(e)}function a(t){function e(t,e){var o=n[e];return o}var n=m(t);return h(e)}function s(t){function e(e,n,r,i,a){var s=o(n),u="object"===s;if(u)for(var c in t){var l=t[c];if(l&&!l(n,c,i,a))return!1}return u}return h(e)}function u(t){function e(e,n){var o=n instanceof t;return o}return h(e)}function c(t){function e(e,n,o,r,i){var a=Array.isArray(n);if(a)for(var s=0;s<n.length;s++)if(!t(n,s,r,i))return!1;return a}return h(e)}function l(){function t(t,e){var o=n(e);return o}return h(t)}function p(){function t(t,e){var n=f.isValidComponent(e);return n}return h(t)}function d(t){return function(e,n,o,r){for(var i=!1,a=0;a<t.length;a++){var s=t[a];if("function"==typeof s.weak&&(s=s.weak),s(e,n,o,r)){i=!0;break}}return i}}function h(t){function e(e,n,o,r,i,a){var s=o[r];if(null!=s)return t(n,s,r,i||g,a);var u=!e;return u}var n=e.bind(null,!1,!0);return n.weak=e.bind(null,!1,!1),n.isRequired=e.bind(null,!0,!0),n.weak.isRequired=e.bind(null,!0,!1),n.isRequired.weak=n.weak.isRequired,n}var f=t("./ReactComponent"),m=(t("./ReactPropTypeLocationNames"),t("./warning"),t("./createObjectFrom")),v={array:i("array"),bool:i("boolean"),func:i("function"),number:i("number"),object:i("object"),string:i("string"),shape:s,oneOf:a,oneOfType:d,arrayOf:c,instanceOf:u,renderable:l(),component:p(),any:r()},g="<<anonymous>>";e.exports=v},{"./ReactComponent":31,"./ReactPropTypeLocationNames":65,"./createObjectFrom":103,"./warning":144}],68:[function(t,e){"use strict";function n(){this.listenersToPut=[]}var o=t("./PooledClass"),r=t("./ReactEventEmitter"),i=t("./mixInto");i(n,{enqueuePutListener:function(t,e,n){this.listenersToPut.push({rootNodeID:t,propKey:e,propValue:n})},putListeners:function(){for(var t=0;t<this.listenersToPut.length;t++){var e=this.listenersToPut[t];r.putListener(e.rootNodeID,e.propKey,e.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),o.addPoolingTo(n),e.exports=n},{"./PooledClass":25,"./ReactEventEmitter":50,"./mixInto":134}],69:[function(t,e){"use strict";function n(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=a.getPooled(null),this.putListenerQueue=s.getPooled()}var o=t("./PooledClass"),r=t("./ReactEventEmitter"),i=t("./ReactInputSelection"),a=t("./ReactMountReady"),s=t("./ReactPutListenerQueue"),u=t("./Transaction"),c=t("./mixInto"),l={initialize:i.getSelectionInformation,close:i.restoreSelection},p={initialize:function(){var t=r.isEnabled();return r.setEnabled(!1),t},close:function(t){r.setEnabled(t)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h={initialize:function(){this.putListenerQueue.reset()},close:function(){this.putListenerQueue.putListeners()}},f=[h,l,p,d],m={getTransactionWrappers:function(){return f},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){a.release(this.reactMountReady),this.reactMountReady=null,s.release(this.putListenerQueue),this.putListenerQueue=null}};c(n,u.Mixin),c(n,m),o.addPoolingTo(n),e.exports=n},{"./PooledClass":25,"./ReactEventEmitter":50,"./ReactInputSelection":54,"./ReactMountReady":59,"./ReactPutListenerQueue":68,"./Transaction":93,"./mixInto":134}],70:[function(t,e){"use strict";var n={injectCreateReactRootIndex:function(t){o.createReactRootIndex=t}},o={createReactRootIndex:null,injection:n};e.exports=o},{}],71:[function(t,e){"use strict";function n(t){c(r.isValidComponent(t)),c(!(2===arguments.length&&"function"==typeof arguments[1]));var e;try{var n=i.createReactRootID();return e=s.getPooled(!1),e.perform(function(){var o=u(t),r=o.mountComponent(n,e,0);return a.addChecksumToMarkup(r)},null)}finally{s.release(e)}}function o(t){c(r.isValidComponent(t));var e;try{var n=i.createReactRootID();return e=s.getPooled(!0),e.perform(function(){var o=u(t);return o.mountComponent(n,e,0)},null)}finally{s.release(e)}}var r=t("./ReactComponent"),i=t("./ReactInstanceHandles"),a=t("./ReactMarkupChecksum"),s=t("./ReactServerRenderingTransaction"),u=t("./instantiateReactComponent"),c=t("./invariant");e.exports={renderComponentToString:n,renderComponentToStaticMarkup:o}},{"./ReactComponent":31,"./ReactInstanceHandles":55,"./ReactMarkupChecksum":57,"./ReactServerRenderingTransaction":72,"./instantiateReactComponent":121,"./invariant":122}],72:[function(t,e){"use strict";function n(t){this.reinitializeTransaction(),this.renderToStaticMarkup=t,this.reactMountReady=r.getPooled(null),this.putListenerQueue=i.getPooled()}var o=t("./PooledClass"),r=t("./ReactMountReady"),i=t("./ReactPutListenerQueue"),a=t("./Transaction"),s=t("./emptyFunction"),u=t("./mixInto"),c={initialize:function(){this.reactMountReady.reset()},close:s},l={initialize:function(){this.putListenerQueue.reset()},close:s},p=[l,c],d={getTransactionWrappers:function(){return p},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null,i.release(this.putListenerQueue),this.putListenerQueue=null}};u(n,a.Mixin),u(n,d),o.addPoolingTo(n),e.exports=n},{"./PooledClass":25,"./ReactMountReady":59,"./ReactPutListenerQueue":68,"./Transaction":93,"./emptyFunction":106,"./mixInto":134}],73:[function(t,e){"use strict";function n(t,e){var n={};return function(o){n[e]=o,t.setState(n)}}var o={createStateSetter:function(t,e){return function(n,o,r,i,a,s){var u=e.call(t,n,o,r,i,a,s);u&&t.setState(u)}},createStateKeySetter:function(t,e){var o=t.__keySetters||(t.__keySetters={});return o[e]||(o[e]=n(t,e))}};o.Mixin={createStateSetter:function(t){return o.createStateSetter(this,t)},createStateKeySetter:function(t){return o.createStateKeySetter(this,t)}},e.exports=o},{}],74:[function(t,e){"use strict";var n=t("./DOMPropertyOperations"),o=t("./ReactBrowserComponentMixin"),r=t("./ReactComponent"),i=t("./escapeTextForBrowser"),a=t("./mixInto"),s=function(t){this.construct({text:t})};s.ConvenienceConstructor=function(t){return new s(t.text)},a(s,r.Mixin),a(s,o),a(s,{mountComponent:function(t,e,o){r.Mixin.mountComponent.call(this,t,e,o);var a=i(this.props.text);return e.renderToStaticMarkup?a:"<span "+n.createMarkupForID(t)+">"+a+"</span>"},receiveComponent:function(t){var e=t.props;e.text!==this.props.text&&(this.props.text=e.text,r.BackendIDOperations.updateTextContentByID(this._rootNodeID,e.text))}}),s.type=s,s.prototype.type=s,e.exports=s},{"./DOMPropertyOperations":10,"./ReactBrowserComponentMixin":27,"./ReactComponent":31,"./escapeTextForBrowser":108,"./mixInto":134}],75:[function(t,e){"use strict";var n=t("./ReactChildren"),o={getChildMapping:function(t){return n.map(t,function(t){return t})},mergeChildMappings:function(t,e){function n(n){return e.hasOwnProperty(n)?e[n]:t[n]}t=t||{},e=e||{};var o={},r=[];for(var i in t)e[i]?r.length&&(o[i]=r,r=[]):r.push(i);var a,s={};for(var u in e){if(o[u])for(a=0;a<o[u].length;a++){var c=o[u][a];s[o[u][a]]=n(c)}s[u]=n(u)}for(a=0;a<r.length;a++)s[r[a]]=n(r[a]);return s}};e.exports=o},{"./ReactChildren":30}],76:[function(t,e){"use strict";function n(){var t=document.createElement("div"),e=t.style;for(var n in a){var o=a[n];for(var r in o)if(r in e){s.push(o[r]);break}}}function o(t,e,n){t.addEventListener(e,n,!1)}function r(t,e,n){t.removeEventListener(e,n,!1)}var i=t("./ExecutionEnvironment"),a={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},s=[];i.canUseDOM&&n();var u={addEndEventListener:function(t,e){return 0===s.length?void window.setTimeout(e,0):void s.forEach(function(n){o(t,n,e)})},removeEndEventListener:function(t,e){0!==s.length&&s.forEach(function(n){r(t,n,e)})}};e.exports=u},{"./ExecutionEnvironment":21}],77:[function(t,e){"use strict";var n=t("./React"),o=t("./ReactTransitionChildMapping"),r=t("./cloneWithProps"),i=t("./emptyFunction"),a=t("./merge"),s=n.createClass({propTypes:{component:n.PropTypes.func,childFactory:n.PropTypes.func},getDefaultProps:function(){return{component:n.DOM.span,childFactory:i.thatReturnsArgument}},getInitialState:function(){return{children:o.getChildMapping(this.props.children)}},componentWillReceiveProps:function(t){var e=o.getChildMapping(t.children),n=this.state.children;this.setState({children:o.mergeChildMappings(n,e)});var r;for(r in e)n.hasOwnProperty(r)||this.currentlyTransitioningKeys[r]||this.keysToEnter.push(r);for(r in n)e.hasOwnProperty(r)||this.currentlyTransitioningKeys[r]||this.keysToLeave.push(r)},componentWillMount:function(){this.currentlyTransitioningKeys={},this.keysToEnter=[],this.keysToLeave=[]},componentDidUpdate:function(){var t=this.keysToEnter;this.keysToEnter=[],t.forEach(this.performEnter);var e=this.keysToLeave;this.keysToLeave=[],e.forEach(this.performLeave)},performEnter:function(t){this.currentlyTransitioningKeys[t]=!0;var e=this.refs[t];e.componentWillEnter?e.componentWillEnter(this._handleDoneEntering.bind(this,t)):this._handleDoneEntering(t)},_handleDoneEntering:function(t){var e=this.refs[t];e.componentDidEnter&&e.componentDidEnter(),delete this.currentlyTransitioningKeys[t];var n=o.getChildMapping(this.props.children);n.hasOwnProperty(t)||this.performLeave(t)},performLeave:function(t){this.currentlyTransitioningKeys[t]=!0;var e=this.refs[t];e.componentWillLeave?e.componentWillLeave(this._handleDoneLeaving.bind(this,t)):this._handleDoneLeaving(t)},_handleDoneLeaving:function(t){var e=this.refs[t];e.componentDidLeave&&e.componentDidLeave(),delete this.currentlyTransitioningKeys[t];var n=o.getChildMapping(this.props.children);if(n.hasOwnProperty(t))this.performEnter(t);else{var r=a(this.state.children);delete r[t],this.setState({children:r})}},render:function(){var t={};for(var e in this.state.children){var n=this.state.children[e];n&&(t[e]=r(this.props.childFactory(n),{ref:e}))}return this.transferPropsTo(this.props.component(null,t))}});e.exports=s},{"./React":26,"./ReactTransitionChildMapping":75,"./cloneWithProps":97,"./emptyFunction":106,"./merge":131}],78:[function(t,e){"use strict";function n(){c(p)}function o(t,e){n(),p.batchedUpdates(t,e)}function r(t,e){return t._mountDepth-e._mountDepth}function i(){l.sort(r);for(var t=0;t<l.length;t++){var e=l[t];if(e.isMounted()){var n=e._pendingCallbacks;if(e._pendingCallbacks=null,e.performUpdateIfNecessary(),n)for(var o=0;o<n.length;o++)n[o].call(e)}}}function a(){l.length=0}function s(t,e){return c(!e||"function"==typeof e),n(),p.isBatchingUpdates?(l.push(t),void(e&&(t._pendingCallbacks?t._pendingCallbacks.push(e):t._pendingCallbacks=[e]))):(t.performUpdateIfNecessary(),void(e&&e.call(t)))}var u=t("./ReactPerf"),c=t("./invariant"),l=[],p=null,d=u.measure("ReactUpdates","flushBatchedUpdates",function(){try{i()}finally{a()}}),h={injectBatchingStrategy:function(t){c(t),c("function"==typeof t.batchedUpdates),c("boolean"==typeof t.isBatchingUpdates),p=t}},f={batchedUpdates:o,enqueueUpdate:s,flushBatchedUpdates:d,injection:h};e.exports=f},{"./ReactPerf":63,"./invariant":122}],79:[function(t,e){"use strict";var n=t("./LinkedStateMixin"),o=t("./React"),r=t("./ReactCSSTransitionGroup"),i=t("./ReactTransitionGroup"),r=t("./ReactCSSTransitionGroup"),a=t("./cx"),s=t("./cloneWithProps"),u=t("./update");o.addons={LinkedStateMixin:n,CSSTransitionGroup:r,TransitionGroup:i,classSet:a,cloneWithProps:s,update:u},e.exports=o},{"./LinkedStateMixin":22,"./React":26,"./ReactCSSTransitionGroup":28,"./ReactTransitionGroup":77,"./cloneWithProps":97,"./cx":104,"./update":143}],80:[function(t,e){"use strict";function n(t){if("selectionStart"in t&&a.hasSelectionCapabilities(t))return{start:t.selectionStart,end:t.selectionEnd};if(document.selection){var e=document.selection.createRange();return{parentElement:e.parentElement(),text:e.text,top:e.boundingTop,left:e.boundingLeft}}var n=window.getSelection();return{anchorNode:n.anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset}}function o(t){if(!g&&null!=f&&f==u()){var e=n(f);if(!v||!p(v,e)){v=e;var o=s.getPooled(h.select,m,t);return o.type="select",o.target=f,i.accumulateTwoPhaseDispatches(o),o}}}var r=t("./EventConstants"),i=t("./EventPropagators"),a=t("./ReactInputSelection"),s=t("./SyntheticEvent"),u=t("./getActiveElement"),c=t("./isTextInputElement"),l=t("./keyOf"),p=t("./shallowEqual"),d=r.topLevelTypes,h={select:{phasedRegistrationNames:{bubbled:l({onSelect:null}),captured:l({onSelectCapture:null})},dependencies:[d.topBlur,d.topContextMenu,d.topFocus,d.topKeyDown,d.topMouseDown,d.topMouseUp,d.topSelectionChange]}},f=null,m=null,v=null,g=!1,y={eventTypes:h,extractEvents:function(t,e,n,r){switch(t){case d.topFocus:(c(e)||"true"===e.contentEditable)&&(f=e,m=n,v=null);break;case d.topBlur:f=null,m=null,v=null;break;case d.topMouseDown:g=!0;break;case d.topContextMenu:case d.topMouseUp:return g=!1,o(r);case d.topSelectionChange:case d.topKeyDown:case d.topKeyUp:return o(r)}}};e.exports=y},{"./EventConstants":15,"./EventPropagators":20,"./ReactInputSelection":54,"./SyntheticEvent":86,"./getActiveElement":112,"./isTextInputElement":125,"./keyOf":129,"./shallowEqual":139}],81:[function(t,e){"use strict";var n=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};e.exports=o},{}],82:[function(t,e){"use strict";var n=t("./EventConstants"),o=t("./EventPluginUtils"),r=t("./EventPropagators"),i=t("./SyntheticClipboardEvent"),a=t("./SyntheticEvent"),s=t("./SyntheticFocusEvent"),u=t("./SyntheticKeyboardEvent"),c=t("./SyntheticMouseEvent"),l=t("./SyntheticDragEvent"),p=t("./SyntheticTouchEvent"),d=t("./SyntheticUIEvent"),h=t("./SyntheticWheelEvent"),f=t("./invariant"),m=t("./keyOf"),v=n.topLevelTypes,g={blur:{phasedRegistrationNames:{bubbled:m({onBlur:!0}),captured:m({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:m({onClick:!0}),captured:m({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:m({onContextMenu:!0}),captured:m({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:m({onCopy:!0}),captured:m({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:m({onCut:!0}),captured:m({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:m({onDoubleClick:!0}),captured:m({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:m({onDrag:!0}),captured:m({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:m({onDragEnd:!0}),captured:m({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:m({onDragEnter:!0}),captured:m({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:m({onDragExit:!0}),captured:m({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:m({onDragLeave:!0}),captured:m({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:m({onDragOver:!0}),captured:m({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:m({onDragStart:!0}),captured:m({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:m({onDrop:!0}),captured:m({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:m({onFocus:!0}),captured:m({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:m({onInput:!0}),captured:m({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:m({onKeyDown:!0}),captured:m({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:m({onKeyPress:!0}),captured:m({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:m({onKeyUp:!0}),captured:m({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:m({onLoad:!0}),captured:m({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:m({onError:!0}),captured:m({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:m({onMouseDown:!0}),captured:m({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:m({onMouseMove:!0}),captured:m({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:m({onMouseOut:!0}),captured:m({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:m({onMouseOver:!0}),captured:m({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:m({onMouseUp:!0}),captured:m({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:m({onPaste:!0}),captured:m({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:m({onReset:!0}),captured:m({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:m({onScroll:!0}),captured:m({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:m({onSubmit:!0}),captured:m({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:m({onTouchCancel:!0}),captured:m({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:m({onTouchEnd:!0}),captured:m({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:m({onTouchMove:!0}),captured:m({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:m({onTouchStart:!0}),captured:m({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:m({onWheel:!0}),captured:m({onWheelCapture:!0})}}},y={topBlur:g.blur,topClick:g.click,topContextMenu:g.contextMenu,topCopy:g.copy,topCut:g.cut,topDoubleClick:g.doubleClick,topDrag:g.drag,topDragEnd:g.dragEnd,topDragEnter:g.dragEnter,topDragExit:g.dragExit,topDragLeave:g.dragLeave,topDragOver:g.dragOver,topDragStart:g.dragStart,topDrop:g.drop,topError:g.error,topFocus:g.focus,topInput:g.input,topKeyDown:g.keyDown,topKeyPress:g.keyPress,topKeyUp:g.keyUp,topLoad:g.load,topMouseDown:g.mouseDown,topMouseMove:g.mouseMove,topMouseOut:g.mouseOut,topMouseOver:g.mouseOver,topMouseUp:g.mouseUp,topPaste:g.paste,topReset:g.reset,topScroll:g.scroll,topSubmit:g.submit,topTouchCancel:g.touchCancel,topTouchEnd:g.touchEnd,topTouchMove:g.touchMove,topTouchStart:g.touchStart,topWheel:g.wheel}; for(var C in y)y[C].dependencies=[C];var E={eventTypes:g,executeDispatch:function(t,e,n){var r=o.executeDispatch(t,e,n);r===!1&&(t.stopPropagation(),t.preventDefault())},extractEvents:function(t,e,n,o){var m=y[t];if(!m)return null;var g;switch(t){case v.topInput:case v.topLoad:case v.topError:case v.topReset:case v.topSubmit:g=a;break;case v.topKeyDown:case v.topKeyPress:case v.topKeyUp:g=u;break;case v.topBlur:case v.topFocus:g=s;break;case v.topClick:if(2===o.button)return null;case v.topContextMenu:case v.topDoubleClick:case v.topMouseDown:case v.topMouseMove:case v.topMouseOut:case v.topMouseOver:case v.topMouseUp:g=c;break;case v.topDrag:case v.topDragEnd:case v.topDragEnter:case v.topDragExit:case v.topDragLeave:case v.topDragOver:case v.topDragStart:case v.topDrop:g=l;break;case v.topTouchCancel:case v.topTouchEnd:case v.topTouchMove:case v.topTouchStart:g=p;break;case v.topScroll:g=d;break;case v.topWheel:g=h;break;case v.topCopy:case v.topCut:case v.topPaste:g=i}f(g);var C=g.getPooled(m,n,o);return r.accumulateTwoPhaseDispatches(C),C}};e.exports=E},{"./EventConstants":15,"./EventPluginUtils":19,"./EventPropagators":20,"./SyntheticClipboardEvent":83,"./SyntheticDragEvent":85,"./SyntheticEvent":86,"./SyntheticFocusEvent":87,"./SyntheticKeyboardEvent":88,"./SyntheticMouseEvent":89,"./SyntheticTouchEvent":90,"./SyntheticUIEvent":91,"./SyntheticWheelEvent":92,"./invariant":122,"./keyOf":129}],83:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticEvent"),r={clipboardData:function(t){return"clipboardData"in t?t.clipboardData:window.clipboardData}};o.augmentClass(n,r),e.exports=n},{"./SyntheticEvent":86}],84:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticEvent"),r={data:null};o.augmentClass(n,r),e.exports=n},{"./SyntheticEvent":86}],85:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticMouseEvent"),r={dataTransfer:null};o.augmentClass(n,r),e.exports=n},{"./SyntheticMouseEvent":89}],86:[function(t,e){"use strict";function n(t,e,n){this.dispatchConfig=t,this.dispatchMarker=e,this.nativeEvent=n;var o=this.constructor.Interface;for(var i in o)if(o.hasOwnProperty(i)){var a=o[i];this[i]=a?a(n):n[i]}var s=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;this.isDefaultPrevented=s?r.thatReturnsTrue:r.thatReturnsFalse,this.isPropagationStopped=r.thatReturnsFalse}var o=t("./PooledClass"),r=t("./emptyFunction"),i=t("./getEventTarget"),a=t("./merge"),s=t("./mergeInto"),u={type:null,target:i,currentTarget:r.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(t){return t.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};s(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var t=this.nativeEvent;t.preventDefault?t.preventDefault():t.returnValue=!1,this.isDefaultPrevented=r.thatReturnsTrue},stopPropagation:function(){var t=this.nativeEvent;t.stopPropagation?t.stopPropagation():t.cancelBubble=!0,this.isPropagationStopped=r.thatReturnsTrue},persist:function(){this.isPersistent=r.thatReturnsTrue},isPersistent:r.thatReturnsFalse,destructor:function(){var t=this.constructor.Interface;for(var e in t)this[e]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=u,n.augmentClass=function(t,e){var n=this,r=Object.create(n.prototype);s(r,t.prototype),t.prototype=r,t.prototype.constructor=t,t.Interface=a(n.Interface,e),t.augmentClass=n.augmentClass,o.addPoolingTo(t,o.threeArgumentPooler)},o.addPoolingTo(n,o.threeArgumentPooler),e.exports=n},{"./PooledClass":25,"./emptyFunction":106,"./getEventTarget":114,"./merge":131,"./mergeInto":133}],87:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticUIEvent"),r={relatedTarget:null};o.augmentClass(n,r),e.exports=n},{"./SyntheticUIEvent":91}],88:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticUIEvent"),r=t("./getEventKey"),i={key:r,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,"char":null,charCode:null,keyCode:null,which:null};o.augmentClass(n,i),e.exports=n},{"./SyntheticUIEvent":91,"./getEventKey":113}],89:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticUIEvent"),r=t("./ViewportMetrics"),i={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,button:function(t){var e=t.button;return"which"in t?e:2===e?2:4===e?1:0},buttons:null,relatedTarget:function(t){return t.relatedTarget||(t.fromElement===t.srcElement?t.toElement:t.fromElement)},pageX:function(t){return"pageX"in t?t.pageX:t.clientX+r.currentScrollLeft},pageY:function(t){return"pageY"in t?t.pageY:t.clientY+r.currentScrollTop}};o.augmentClass(n,i),e.exports=n},{"./SyntheticUIEvent":91,"./ViewportMetrics":94}],90:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticUIEvent"),r={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null};o.augmentClass(n,r),e.exports=n},{"./SyntheticUIEvent":91}],91:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticEvent"),r={view:null,detail:null};o.augmentClass(n,r),e.exports=n},{"./SyntheticEvent":86}],92:[function(t,e){"use strict";function n(t,e,n){o.call(this,t,e,n)}var o=t("./SyntheticMouseEvent"),r={deltaX:function(t){return"deltaX"in t?t.deltaX:"wheelDeltaX"in t?-t.wheelDeltaX:0},deltaY:function(t){return"deltaY"in t?t.deltaY:"wheelDeltaY"in t?-t.wheelDeltaY:"wheelDelta"in t?-t.wheelDelta:0},deltaZ:null,deltaMode:null};o.augmentClass(n,r),e.exports=n},{"./SyntheticMouseEvent":89}],93:[function(t,e){"use strict";var n=t("./invariant"),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this.timingMetrics||(this.timingMetrics={}),this.timingMetrics.methodInvocationTime=0,this.timingMetrics.wrapperInitTimes?this.timingMetrics.wrapperInitTimes.length=0:this.timingMetrics.wrapperInitTimes=[],this.timingMetrics.wrapperCloseTimes?this.timingMetrics.wrapperCloseTimes.length=0:this.timingMetrics.wrapperCloseTimes=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(t,e,o,r,i,a,s,u){n(!this.isInTransaction());var c,l,p=Date.now();try{this._isInTransaction=!0,c=!0,this.initializeAll(0),l=t.call(e,o,r,i,a,s,u),c=!1}finally{var d=Date.now();this.methodInvocationTime+=d-p;try{if(c)try{this.closeAll(0)}catch(h){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return l},initializeAll:function(t){for(var e=this.transactionWrappers,n=this.timingMetrics.wrapperInitTimes,o=t;o<e.length;o++){var i=Date.now(),a=e[o];try{this.wrapperInitData[o]=r.OBSERVED_ERROR,this.wrapperInitData[o]=a.initialize?a.initialize.call(this):null}finally{var s=n[o],u=Date.now();if(n[o]=(s||0)+(u-i),this.wrapperInitData[o]===r.OBSERVED_ERROR)try{this.initializeAll(o+1)}catch(c){}}}},closeAll:function(t){n(this.isInTransaction());for(var e=this.transactionWrappers,o=this.timingMetrics.wrapperCloseTimes,i=t;i<e.length;i++){var a,s=e[i],u=Date.now(),c=this.wrapperInitData[i];try{a=!0,c!==r.OBSERVED_ERROR&&s.close&&s.close.call(this,c),a=!1}finally{var l=Date.now(),p=o[i];if(o[i]=(p||0)+(l-u),a)try{this.closeAll(i+1)}catch(d){}}}this.wrapperInitData.length=0}},r={Mixin:o,OBSERVED_ERROR:{}};e.exports=r},{"./invariant":122}],94:[function(t,e){"use strict";var n=t("./getUnboundedScrollPosition"),o={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var t=n(window);o.currentScrollLeft=t.x,o.currentScrollTop=t.y}};e.exports=o},{"./getUnboundedScrollPosition":119}],95:[function(t,e){"use strict";function n(t,e){if(o(null!=e),null==t)return e;var n=Array.isArray(t),r=Array.isArray(e);return n?t.concat(e):r?[t].concat(e):[t,e]}var o=t("./invariant");e.exports=n},{"./invariant":122}],96:[function(t,e){"use strict";function n(t){for(var e=1,n=0,r=0;r<t.length;r++)e=(e+t.charCodeAt(r))%o,n=(n+e)%o;return e|n<<16}var o=65521;e.exports=n},{}],97:[function(t,e){"use strict";function n(t,e){var n=o.mergeProps(e,t.props);return!n.hasOwnProperty(i)&&t.props.hasOwnProperty(i)&&(n.children=t.props.children),t.constructor.ConvenienceConstructor(n)}var o=t("./ReactPropTransferer"),r=t("./keyOf"),i=(t("./warning"),r({children:null}));e.exports=n},{"./ReactPropTransferer":64,"./keyOf":129,"./warning":144}],98:[function(t,e){function n(t,e){return t&&e?t===e?!0:o(t)?!1:o(e)?n(t,e.parentNode):t.contains?t.contains(e):t.compareDocumentPosition?!!(16&t.compareDocumentPosition(e)):!1:!1}var o=t("./isTextNode");e.exports=n},{"./isTextNode":126}],99:[function(t,e){function n(t,e,n,o,r,i){t=t||{};for(var a,s=[e,n,o,r,i],u=0;s[u];){a=s[u++];for(var c in a)t[c]=a[c];a.hasOwnProperty&&a.hasOwnProperty("toString")&&"undefined"!=typeof a.toString&&t.toString!==a.toString&&(t.toString=a.toString)}return t}e.exports=n},{}],100:[function(t,e){function n(t){return!!t&&("object"==typeof t||"function"==typeof t)&&"length"in t&&!("setInterval"in t)&&"number"!=typeof t.nodeType&&(Array.isArray(t)||"callee"in t||"item"in t)}function o(t){return n(t)?Array.isArray(t)?t.slice():r(t):[t]}var r=t("./toArray");e.exports=o},{"./toArray":141}],101:[function(t,e){"use strict";function n(t){var e=o.createClass({displayName:"ReactFullPageComponent"+(t.componentConstructor.displayName||""),componentWillUnmount:function(){r(!1)},render:function(){return this.transferPropsTo(t(null,this.props.children))}});return e}var o=t("./ReactCompositeComponent"),r=t("./invariant");e.exports=n},{"./ReactCompositeComponent":33,"./invariant":122}],102:[function(t,e){function n(t){var e=t.match(c);return e&&e[1].toLowerCase()}function o(t,e){var o=u;s(!!u);var r=n(t),c=r&&a(r);if(c){o.innerHTML=c[1]+t+c[2];for(var l=c[0];l--;)o=o.lastChild}else o.innerHTML=t;var p=o.getElementsByTagName("script");p.length&&(s(e),i(p).forEach(e));for(var d=i(o.childNodes);o.lastChild;)o.removeChild(o.lastChild);return d}var r=t("./ExecutionEnvironment"),i=t("./createArrayFrom"),a=t("./getMarkupWrap"),s=t("./invariant"),u=r.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;e.exports=o},{"./ExecutionEnvironment":21,"./createArrayFrom":100,"./getMarkupWrap":115,"./invariant":122}],103:[function(t,e){function n(t,e){var n={},o=Array.isArray(e);"undefined"==typeof e&&(e=!0);for(var r=t.length;r--;)n[t[r]]=o?e[r]:e;return n}e.exports=n},{}],104:[function(t,e){function n(t){return"object"==typeof t?Object.keys(t).filter(function(e){return t[e]}).join(" "):Array.prototype.join.call(arguments," ")}e.exports=n},{}],105:[function(t,e){"use strict";function n(t,e){var n=null==e||"boolean"==typeof e||""===e;if(n)return"";var r=isNaN(e);return r||0===e||o.isUnitlessNumber[t]?""+e:e+"px"}var o=t("./CSSProperty");e.exports=n},{"./CSSProperty":3}],106:[function(t,e){function n(t){return function(){return t}}function o(){}var r=t("./copyProperties");r(o,{thatReturns:n,thatReturnsFalse:n(!1),thatReturnsTrue:n(!0),thatReturnsNull:n(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(t){return t}}),e.exports=o},{"./copyProperties":99}],107:[function(t,e){"use strict";var n={};e.exports=n},{}],108:[function(t,e){"use strict";function n(t){return r[t]}function o(t){return(""+t).replace(i,n)}var r={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;","/":"&#x2f;"},i=/[&><"'\/]/g;e.exports=o},{}],109:[function(t,e){"use strict";function n(t,e,n){var o=t;r(!o.hasOwnProperty(n)),null!=e&&(o[n]=e)}function o(t){if(null==t)return t;var e={};return i(t,n,e),e}var r=t("./invariant"),i=t("./traverseAllChildren");e.exports=o},{"./invariant":122,"./traverseAllChildren":142}],110:[function(t,e){"use strict";function n(t){t.disabled||t.focus()}e.exports=n},{}],111:[function(t,e){"use strict";var n=function(t,e,n){Array.isArray(t)?t.forEach(e,n):t&&e.call(n,t)};e.exports=n},{}],112:[function(t,e){function n(){try{return document.activeElement||document.body}catch(t){return document.body}}e.exports=n},{}],113:[function(t,e){"use strict";function n(t){return"key"in t?o[t.key]||t.key:r[t.which||t.keyCode]||"Unidentified"}var o={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},r={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"};e.exports=n},{}],114:[function(t,e){"use strict";function n(t){var e=t.target||t.srcElement||window;return 3===e.nodeType?e.parentNode:e}e.exports=n},{}],115:[function(t,e){function n(t){return r(!!i),p.hasOwnProperty(t)||(t="*"),a.hasOwnProperty(t)||(i.innerHTML="*"===t?"<link />":"<"+t+"></"+t+">",a[t]=!i.firstChild),a[t]?p[t]:null}var o=t("./ExecutionEnvironment"),r=t("./invariant"),i=o.canUseDOM?document.createElement("div"):null,a={circle:!0,defs:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],l=[1,"<svg>","</svg>"],p={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:c,th:c,circle:l,defs:l,g:l,line:l,linearGradient:l,path:l,polygon:l,polyline:l,radialGradient:l,rect:l,stop:l,text:l};e.exports=n},{"./ExecutionEnvironment":21,"./invariant":122}],116:[function(t,e){"use strict";function n(t){for(;t&&t.firstChild;)t=t.firstChild;return t}function o(t){for(;t;){if(t.nextSibling)return t.nextSibling;t=t.parentNode}}function r(t,e){for(var r=n(t),i=0,a=0;r;){if(3==r.nodeType){if(a=i+r.textContent.length,e>=i&&a>=e)return{node:r,offset:e-i};i=a}r=n(o(r))}}e.exports=r},{}],117:[function(t,e){"use strict";function n(t){return t?t.nodeType===o?t.documentElement:t.firstChild:null}var o=9;e.exports=n},{}],118:[function(t,e){"use strict";function n(){return!r&&o.canUseDOM&&(r="textContent"in document.createElement("div")?"textContent":"innerText"),r}var o=t("./ExecutionEnvironment"),r=null;e.exports=n},{"./ExecutionEnvironment":21}],119:[function(t,e){"use strict";function n(t){return t===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:t.scrollLeft,y:t.scrollTop}}e.exports=n},{}],120:[function(t,e){function n(t){return t.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;e.exports=n},{}],121:[function(t,e){"use strict";function n(t){return t._descriptor=t,t}t("./warning");e.exports=n},{"./warning":144}],122:[function(t,e){"use strict";var n=function(t){if(!t){var e=new Error("Minified exception occured; use the non-minified dev environment for the full error message and additional helpful warnings.");throw e.framesToPop=1,e}};e.exports=n},{}],123:[function(t,e){"use strict";function n(t,e){if(!r.canUseDOM||e&&!("addEventListener"in document))return!1;var n="on"+t,i=n in document;if(!i){var a=document.createElement("div");a.setAttribute(n,"return;"),i="function"==typeof a[n]}return!i&&o&&"wheel"===t&&(i=document.implementation.hasFeature("Events.wheel","3.0")),i}var o,r=t("./ExecutionEnvironment");r.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=n},{"./ExecutionEnvironment":21}],124:[function(t,e){function n(t){return!(!t||!("function"==typeof Node?t instanceof Node:"object"==typeof t&&"number"==typeof t.nodeType&&"string"==typeof t.nodeName))}e.exports=n},{}],125:[function(t,e){"use strict";function n(t){return t&&("INPUT"===t.nodeName&&o[t.type]||"TEXTAREA"===t.nodeName)}var o={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};e.exports=n},{}],126:[function(t,e){function n(t){return o(t)&&3==t.nodeType}var o=t("./isNode");e.exports=n},{"./isNode":124}],127:[function(t,e){"use strict";function n(t){t||(t="");var e,n=arguments.length;if(n>1)for(var o=1;n>o;o++)e=arguments[o],e&&(t+=" "+e);return t}e.exports=n},{}],128:[function(t,e){"use strict";var n=t("./invariant"),o=function(t){var e,o={};n(t instanceof Object&&!Array.isArray(t));for(e in t)t.hasOwnProperty(e)&&(o[e]=e);return o};e.exports=o},{"./invariant":122}],129:[function(t,e){var n=function(t){var e;for(e in t)if(t.hasOwnProperty(e))return e;return null};e.exports=n},{}],130:[function(t,e){"use strict";function n(t){var e={};return function(n){return e.hasOwnProperty(n)?e[n]:e[n]=t.call(this,n)}}e.exports=n},{}],131:[function(t,e){"use strict";var n=t("./mergeInto"),o=function(t,e){var o={};return n(o,t),n(o,e),o};e.exports=o},{"./mergeInto":133}],132:[function(t,e){"use strict";var n=t("./invariant"),o=t("./keyMirror"),r=36,i=function(t){return"object"!=typeof t||null===t},a={MAX_MERGE_DEPTH:r,isTerminal:i,normalizeMergeArg:function(t){return void 0===t||null===t?{}:t},checkMergeArrayArgs:function(t,e){n(Array.isArray(t)&&Array.isArray(e))},checkMergeObjectArgs:function(t,e){a.checkMergeObjectArg(t),a.checkMergeObjectArg(e)},checkMergeObjectArg:function(t){n(!i(t)&&!Array.isArray(t))},checkMergeLevel:function(t){n(r>t)},checkArrayStrategy:function(t){n(void 0===t||t in a.ArrayStrategies)},ArrayStrategies:o({Clobber:!0,IndexByIndex:!0})};e.exports=a},{"./invariant":122,"./keyMirror":128}],133:[function(t,e){"use strict";function n(t,e){if(r(t),null!=e){r(e);for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])}}var o=t("./mergeHelpers"),r=o.checkMergeObjectArg;e.exports=n},{"./mergeHelpers":132}],134:[function(t,e){"use strict";var n=function(t,e){var n;for(n in e)e.hasOwnProperty(n)&&(t.prototype[n]=e[n])};e.exports=n},{}],135:[function(t,e){"use strict";function n(t){o(t&&!/[^a-z0-9_]/.test(t))}var o=t("./invariant");e.exports=n},{"./invariant":122}],136:[function(t,e){"use strict";function n(t,e,n){if(!t)return null;var o=0,r={};for(var i in t)t.hasOwnProperty(i)&&(r[i]=e.call(n,t[i],i,o++));return r}e.exports=n},{}],137:[function(t,e){"use strict";function n(t,e,n){if(!t)return null;var o=0,r={};for(var i in t)t.hasOwnProperty(i)&&(r[i]=e.call(n,i,t[i],o++));return r}e.exports=n},{}],138:[function(t,e){"use strict";function n(t){return r(o.isValidComponent(t)),t}var o=t("./ReactComponent"),r=t("./invariant");e.exports=n},{"./ReactComponent":31,"./invariant":122}],139:[function(t,e){"use strict";function n(t,e){if(t===e)return!0;var n;for(n in t)if(t.hasOwnProperty(n)&&(!e.hasOwnProperty(n)||t[n]!==e[n]))return!1;for(n in e)if(e.hasOwnProperty(n)&&!t.hasOwnProperty(n))return!1;return!0}e.exports=n},{}],140:[function(t,e){"use strict";function n(t,e){return t&&e&&t.constructor===e.constructor&&(t.props&&t.props.key)===(e.props&&e.props.key)&&t._owner===e._owner?!0:!1}e.exports=n},{}],141:[function(t,e){function n(t){var e=t.length;if(o(!Array.isArray(t)&&("object"==typeof t||"function"==typeof t)),o("number"==typeof e),o(0===e||e-1 in t),t.hasOwnProperty)try{return Array.prototype.slice.call(t)}catch(n){}for(var r=Array(e),i=0;e>i;i++)r[i]=t[i];return r}var o=t("./invariant");e.exports=n},{"./invariant":122}],142:[function(t,e){"use strict";function n(t){return d[t]}function o(t,e){return t&&t.props&&null!=t.props.key?i(t.props.key):e.toString(36)}function r(t){return(""+t).replace(h,n)}function i(t){return"$"+r(t)}function a(t,e,n){null!==t&&void 0!==t&&f(t,"",0,e,n)}var s=t("./ReactInstanceHandles"),u=t("./ReactTextComponent"),c=t("./invariant"),l=s.SEPARATOR,p=":",d={"=":"=0",".":"=1",":":"=2"},h=/[=.:]/g,f=function(t,e,n,r,a){var s=0;if(Array.isArray(t))for(var d=0;d<t.length;d++){var h=t[d],m=e+(e?p:l)+o(h,d),v=n+s;s+=f(h,m,v,r,a)}else{var g=typeof t,y=""===e,C=y?l+o(t,0):e;if(null==t||"boolean"===g)r(a,null,C,n),s=1;else if(t.type&&t.type.prototype&&t.type.prototype.mountComponentIntoNode)r(a,t,C,n),s=1;else if("object"===g){c(!t||1!==t.nodeType);for(var E in t)t.hasOwnProperty(E)&&(s+=f(t[E],e+(e?p:l)+i(E)+p+o(t[E],0),n+s,r,a))}else if("string"===g){var R=new u(t);r(a,R,C,n),s+=1}else if("number"===g){var M=new u(""+t);r(a,M,C,n),s+=1}}return s};e.exports=a},{"./ReactInstanceHandles":55,"./ReactTextComponent":74,"./invariant":122}],143:[function(t,e){"use strict";function n(t){return Array.isArray(t)?t.concat():t&&"object"==typeof t?i(new t.constructor,t):t}function o(t,e,n){s(Array.isArray(t));var o=e[n];s(Array.isArray(o))}function r(t,e){if(s("object"==typeof e),e.hasOwnProperty(p))return s(1===Object.keys(e).length),e[p];var a=n(t);if(e.hasOwnProperty(d)){var h=e[d];s(h&&"object"==typeof h),s(a&&"object"==typeof a),i(a,e[d])}e.hasOwnProperty(u)&&(o(t,e,u),e[u].forEach(function(t){a.push(t)})),e.hasOwnProperty(c)&&(o(t,e,c),e[c].forEach(function(t){a.unshift(t)})),e.hasOwnProperty(l)&&(s(Array.isArray(t)),s(Array.isArray(e[l])),e[l].forEach(function(t){s(Array.isArray(t)),a.splice.apply(a,t)}));for(var m in e)f[m]||(a[m]=r(t[m],e[m]));return a}var i=t("./copyProperties"),a=t("./keyOf"),s=t("./invariant"),u=a({$push:null}),c=a({$unshift:null}),l=a({$splice:null}),p=a({$set:null}),d=a({$merge:null}),h=[u,c,l,p,d],f={};h.forEach(function(t){f[t]=!0}),e.exports=r},{"./copyProperties":99,"./invariant":122,"./keyOf":129}],144:[function(t,e){"use strict";var n=t("./emptyFunction"),o=n;e.exports=o},{"./emptyFunction":106}]},{},[79])(79)});
src/scripts/views/header.js
IronNation/NCI-trial-search
import React from 'react' class Header extends React.Component { render() { return ( <div className = 'header'> <h1>Welcome to DTST!</h1> <p>Search for a clinical drug trial near you!</p> <Navigation /> </div> ) } } class Navigation extends React.Component { render() { return ( <div className = 'navBar'> <a href = '#home'>Home</a> <a href = '#search'>Search</a> <a href = '#login'>Login</a> </div> ) } } export default Header
node_modules/babel-plugin-react-transform/test/fixtures/options-with-imports-with-render-method/expected.js
Kgiberson/welp
import _reactDom from "react-dom"; import _react from "react"; import _transformLib from "transform-lib"; const _components = { Foo: { displayName: "Foo" } }; const _transformLib2 = _transformLib({ filename: "%FIXTURE_PATH%", components: _components, locals: [], imports: [_react, _reactDom] }); function _wrapComponent(id) { return function (Component) { return _transformLib2(Component, id); }; } const Foo = _wrapComponent("Foo")(class Foo extends React.Component { render() {} });
project-templates/reactfiber/externals/react-fiber/fixtures/ssr/server/render.js
ItsAsbreuk/itsa-cli
import React from 'react'; import {renderToString} from 'react-dom/server'; import App from '../src/components/App'; let assets; if (process.env.NODE_ENV === 'development') { // Use the bundle from create-react-app's server in development mode. assets = { 'main.js': '/static/js/bundle.js', 'main.css': '', }; } else { assets = require('../build/asset-manifest.json'); } export default function render() { var html = renderToString(<App assets={assets} />); // There's no way to render a doctype in React so prepend manually. // Also append a bootstrap script tag. return '<!DOCTYPE html>' + html; };
src/svg-icons/notification/sync.js
ngbrown/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationSync = (props) => ( <SvgIcon {...props}> <path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/> </SvgIcon> ); NotificationSync = pure(NotificationSync); NotificationSync.displayName = 'NotificationSync'; NotificationSync.muiName = 'SvgIcon'; export default NotificationSync;
ajax/libs/material-ui/5.0.0-alpha.12/esm/Backdrop/Backdrop.js
cdnjs/cdnjs
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties"; import * as React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import Fade from '../Fade'; export var styles = { /* Styles applied to the root element. */ root: { // Improve scrollable dialog support. zIndex: -1, position: 'fixed', display: 'flex', alignItems: 'center', justifyContent: 'center', right: 0, bottom: 0, top: 0, left: 0, backgroundColor: 'rgba(0, 0, 0, 0.5)', WebkitTapHighlightColor: 'transparent' }, /* Styles applied to the root element if `invisible={true}`. */ invisible: { backgroundColor: 'transparent' } }; var Backdrop = /*#__PURE__*/React.forwardRef(function Backdrop(props, ref) { var children = props.children, classes = props.classes, className = props.className, _props$invisible = props.invisible, invisible = _props$invisible === void 0 ? false : _props$invisible, open = props.open, transitionDuration = props.transitionDuration, _props$TransitionComp = props.TransitionComponent, TransitionComponent = _props$TransitionComp === void 0 ? Fade : _props$TransitionComp, other = _objectWithoutProperties(props, ["children", "classes", "className", "invisible", "open", "transitionDuration", "TransitionComponent"]); return /*#__PURE__*/React.createElement(TransitionComponent, _extends({ in: open, timeout: transitionDuration }, other), /*#__PURE__*/React.createElement("div", { className: clsx(classes.root, className, invisible && classes.invisible), "aria-hidden": true, ref: ref }, children)); }); process.env.NODE_ENV !== "production" ? Backdrop.propTypes = { // ----------------------------- Warning -------------------------------- // | These PropTypes are generated from the TypeScript type definitions | // | To update them edit the d.ts file and run "yarn proptypes" | // ---------------------------------------------------------------------- /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. */ classes: PropTypes.object, /** * @ignore */ className: PropTypes.string, /** * If `true`, the backdrop is invisible. * It can be used when rendering a popover or a custom select component. * @default false */ invisible: PropTypes.bool, /** * If `true`, the backdrop is open. */ open: PropTypes.bool.isRequired, /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. */ transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({ appear: PropTypes.number, enter: PropTypes.number, exit: PropTypes.number })]) } : void 0; export default withStyles(styles, { name: 'MuiBackdrop' })(Backdrop);
jspm_packages/npm/react-router@2.6.1/es6/RoutingContext.js
Imms/imms.github.io
/* */ "format cjs"; import React from 'react'; import RouterContext from './RouterContext'; import warning from './routerWarning'; var RoutingContext = React.createClass({ displayName: 'RoutingContext', componentWillMount: function componentWillMount() { process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0; }, render: function render() { return React.createElement(RouterContext, this.props); } }); export default RoutingContext;
ajax/libs/zeroclipboard/2.0.0-beta.6/ZeroClipboard.js
kartikrao31/cdnjs
/*! * ZeroClipboard * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface. * Copyright (c) 2014 Jon Rohan, James M. Greene * Licensed MIT * http://zeroclipboard.org/ * v2.0.0-beta.6 */ (function(window, undefined) { "use strict"; /** * Store references to critically important global functions that may be * overridden on certain web pages. */ var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _encodeURIComponent = _window.encodeURIComponent, _slice = _window.Array.prototype.slice, _keys = _window.Object.keys, _hasOwn = _window.Object.prototype.hasOwnProperty, _defineProperty = _window.Object.defineProperty, _Math = _window.Math, _Date = _window.Date, _ActiveXObject = _window.ActiveXObject; /** * Convert an `arguments` object into an Array. * * @returns The arguments as an Array * @private */ var _args = function(argumentsObj) { return _slice.call(argumentsObj, 0); }; /** * Get the index of an item in an Array. * * @returns The index of an item in the Array, or `-1` if not found. * @private */ var _inArray = function(item, array, fromIndex) { if (typeof array.indexOf === "function") { return array.indexOf(item, fromIndex); } var i, len = array.length; if (typeof fromIndex === "undefined") { fromIndex = 0; } else if (fromIndex < 0) { fromIndex = len + fromIndex; } for (i = fromIndex; i < len; i++) { if (_hasOwn.call(array, i) && array[i] === item) { return i; } } return -1; }; /** * Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`. * * @returns The target object, augmented * @private */ var _extend = function() { var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {}; for (i = 1, len = args.length; i < len; i++) { if ((arg = args[i]) != null) { for (prop in arg) { if (_hasOwn.call(arg, prop)) { src = target[prop]; copy = arg[prop]; if (target === copy) { continue; } if (copy !== undefined) { target[prop] = copy; } } } } } return target; }; /** * Return a deep copy of the source object or array. * * @returns Object or Array * @private */ var _deepCopy = function(source) { var copy, i, len, prop; if (typeof source !== "object" || source == null) { copy = source; } else if (typeof source.length === "number") { copy = []; for (i = 0, len = source.length; i < len; i++) { if (_hasOwn.call(source, i)) { copy[i] = _deepCopy(source[i]); } } } else { copy = {}; for (prop in source) { if (_hasOwn.call(source, prop)) { copy[prop] = _deepCopy(source[prop]); } } } return copy; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep. * The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to * be kept. * * @returns A new filtered object. * @private */ var _pick = function(obj, keys) { var newObj = {}; for (var i = 0, len = keys.length; i < len; i++) { if (keys[i] in obj) { newObj[keys[i]] = obj[keys[i]]; } } return newObj; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit. * The inverse of `_pick`. * * @returns A new filtered object. * @private */ var _omit = function(obj, keys) { var newObj = {}; for (var prop in obj) { if (_inArray(prop, keys) === -1) { newObj[prop] = obj[prop]; } } return newObj; }; /** * Get all of an object's owned, enumerable property names. Does NOT include prototype properties. * * @returns An Array of property names. * @private */ var _objectKeys = function(obj) { if (obj == null) { return []; } if (_keys) { return _keys(obj); } var keys = []; for (var prop in obj) { if (_hasOwn.call(obj, prop)) { keys.push(prop); } } return keys; }; /** * Remove all owned, enumerable properties from an object. * * @returns The original object without its owned, enumerable properties. * @private */ var _deleteOwnProperties = function(obj) { if (obj) { for (var prop in obj) { if (_hasOwn.call(obj, prop)) { delete obj[prop]; } } } return obj; }; /** * Mark an existing property as read-only. * @private */ var _makeReadOnly = function(obj, prop) { if (prop in obj && typeof _defineProperty === "function") { _defineProperty(obj, prop, { value: obj[prop], writable: false, configurable: true, enumerable: true }); } }; /** * Get the current time in milliseconds since the epoch. * * @returns Number * @private */ var _now = function(Date) { return function() { var time; if (Date.now) { time = Date.now(); } else { time = new Date().getTime(); } return time; }; }(_Date); /** * Keep track of the state of the Flash object. * @private */ var _flashState = { bridge: null, version: "0.0.0", pluginType: "unknown", disabled: null, outdated: null, unavailable: null, deactivated: null, overdue: null, ready: null }; /** * * @private */ var _minimumFlashVersion = "11.0.0"; /** * Keep track of all event listener registrations. * @private */ var _handlers = {}; /** * Keep track of the currently activated element. * @private */ var _currentElement; /** * Keep track of data for the pending clipboard transaction. * @private */ var _clipData = {}; /** * Keep track of data formats for the pending clipboard transaction. * @private */ var _clipDataFormatMap = null; /** * The `message` store for events * @private */ var _eventMessages = { ready: "Flash communication is established", error: { "flash-disabled": "Flash is disabled or not installed", "flash-outdated": "Flash is too outdated to support ZeroClipboard", "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript", "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate", "flash-overdue": "Flash communication was established but NOT within the acceptable time limit" } }; /** * The presumed location of the "ZeroClipboard.swf" file, based on the location * of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.). * @private */ var _swfPath = function() { var i, jsDir, tmpJsPath, jsPath, swfPath = "ZeroClipboard.swf"; if (!(_document.currentScript && (jsPath = _document.currentScript.src))) { var scripts = _document.getElementsByTagName("script"); if ("readyState" in scripts[0]) { for (i = scripts.length; i--; ) { if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) { break; } } } else if (_document.readyState === "loading") { jsPath = scripts[scripts.length - 1].src; } else { for (i = scripts.length; i--; ) { tmpJsPath = scripts[i].src; if (!tmpJsPath) { jsDir = null; break; } tmpJsPath = tmpJsPath.split("#")[0].split("?")[0]; tmpJsPath = tmpJsPath.slice(0, tmpJsPath.lastIndexOf("/") + 1); if (jsDir == null) { jsDir = tmpJsPath; } else if (jsDir !== tmpJsPath) { jsDir = null; break; } } if (jsDir !== null) { jsPath = jsDir; } } } if (jsPath) { jsPath = jsPath.split("#")[0].split("?")[0]; swfPath = jsPath.slice(0, jsPath.lastIndexOf("/") + 1) + swfPath; } return swfPath; }(); /** * ZeroClipboard configuration defaults for the Core module. * @private */ var _globalConfig = { swfPath: _swfPath, trustedDomains: _window.location.host ? [ _window.location.host ] : [], cacheBust: true, forceEnhancedClipboard: false, flashLoadTimeout: 3e4, forceHandCursor: false, title: null, zIndex: 999999999, /** * @deprecated in [v1.3.0], slated for removal in [v2.0.0]. See docs for alternatives. */ hoverClass: "zeroclipboard-is-hover", /** * @deprecated in [v1.3.0], slated for removal in [v2.0.0]. See docs for alternatives. */ activeClass: "zeroclipboard-is-active" }; /** * The underlying implementation of `ZeroClipboard.config`. * @private */ var _config = function(options) { if (typeof options === "object" && options !== null) { _extend(_globalConfig, options); } if (typeof options === "string" && options) { if (_hasOwn.call(_globalConfig, options)) { return _globalConfig[options]; } return; } return _deepCopy(_globalConfig); }; /** * The underlying implementation of `ZeroClipboard.state`. * @private */ var _state = function() { return { browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]), flash: _omit(_flashState, [ "bridge" ]), zeroclipboard: { version: ZeroClipboard.version, config: ZeroClipboard.config() } }; }; /** * The underlying implementation of `ZeroClipboard.isFlashUnusable`. * @private */ var _isFlashUnusable = function() { return !!(_flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated); }; /** * The underlying implementation of `ZeroClipboard.on`. * @private */ var _on = function(eventType, listener) { var i, len, events, added = {}; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!_handlers[eventType]) { _handlers[eventType] = []; } _handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { ZeroClipboard.emit({ type: "ready" }); } if (added.error) { var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ]; for (i = 0, len = errorTypes.length; i < len; i++) { if (_flashState[errorTypes[i]] === true) { ZeroClipboard.emit({ type: "error", name: "flash-" + errorTypes[i] }); break; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.off`. * @private */ var _off = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers; if (arguments.length === 0) { events = _objectKeys(_handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = _handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = _inArray(listener, perEventHandlers); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = _inArray(listener, perEventHandlers, foundIndex); } } else { perEventHandlers.length = 0; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.handlers`. * @private */ var _listeners = function(eventType) { var copy; if (typeof eventType === "string" && eventType) { copy = _deepCopy(_handlers[eventType]) || null; } else { copy = _deepCopy(_handlers); } return copy; }; /** * The underlying implementation of `ZeroClipboard.emit`. * @private */ var _emit = function(event) { var eventCopy, returnVal, tmp; event = _createEvent(event); if (!event) { return; } _preprocessEvent(event); if (event.type === "ready" && _flashState.overdue === true) { return ZeroClipboard.emit({ type: "error", name: "flash-overdue" }); } eventCopy = _extend({}, event); _dispatchCallbacks(eventCopy); if (event.type === "copy") { tmp = _mapClipDataToFlash(_clipData); returnVal = tmp.data; _clipDataFormatMap = tmp.formatMap; } return returnVal; }; /** * The underlying implementation of `ZeroClipboard.create`. * @private */ var _create = function() { if (typeof _flashState.ready !== "boolean") { _flashState.ready = false; } if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) { var maxWait = _globalConfig.flashLoadTimeout; if (typeof maxWait === "number" && maxWait >= 0) { _setTimeout(function() { if (typeof _flashState.deactivated !== "boolean") { _flashState.deactivated = true; } if (_flashState.deactivated === true) { ZeroClipboard.emit({ type: "error", name: "flash-deactivated" }); } }, maxWait); } _flashState.overdue = false; _embedSwf(); } }; /** * The underlying implementation of `ZeroClipboard.destroy`. * @private */ var _destroy = function() { ZeroClipboard.clearData(); ZeroClipboard.deactivate(); ZeroClipboard.emit("destroy"); _unembedSwf(); ZeroClipboard.off(); }; /** * The underlying implementation of `ZeroClipboard.setData`. * @private */ var _setData = function(format, data) { var dataObj; if (typeof format === "object" && format && typeof data === "undefined") { dataObj = format; ZeroClipboard.clearData(); } else if (typeof format === "string" && format) { dataObj = {}; dataObj[format] = data; } else { return; } for (var dataFormat in dataObj) { if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) { _clipData[dataFormat] = dataObj[dataFormat]; } } }; /** * The underlying implementation of `ZeroClipboard.clearData`. * @private */ var _clearData = function(format) { if (typeof format === "undefined") { _deleteOwnProperties(_clipData); _clipDataFormatMap = null; } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { delete _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.activate`. * @private */ var _activate = function(element) { if (!(element && element.nodeType === 1)) { return; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); } _currentElement = element; _addClass(element, _globalConfig.hoverClass); _reposition(); var newTitle = element.getAttribute("title") || _globalConfig.title; if (typeof newTitle === "string" && newTitle) { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.setAttribute("title", newTitle); } } var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer"; _setHandCursor(useHandCursor); }; /** * The underlying implementation of `ZeroClipboard.deactivate`. * @private */ var _deactivate = function() { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.removeAttribute("title"); htmlBridge.style.left = "0px"; htmlBridge.style.top = "-9999px"; htmlBridge.style.width = "1px"; htmlBridge.style.top = "1px"; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); _currentElement = null; } }; /** * Create or update an `event` object, based on the `eventType`. * @private */ var _createEvent = function(event) { var eventType; if (typeof event === "string" && event) { eventType = event; event = {}; } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) { eventType = event.type; } if (!eventType) { return; } _extend(event, { type: eventType.toLowerCase(), target: event.target || _currentElement || null, relatedTarget: event.relatedTarget || null, currentTarget: _flashState && _flashState.bridge || null, timeStamp: event.timeStamp || _now() || null }); var msg = _eventMessages[event.type]; if (event.type === "error" && event.name && msg) { msg = msg[event.name]; } if (msg) { event.message = msg; } if (event.type === "ready") { _extend(event, { target: null, version: _flashState.version }); } if (event.type === "error") { if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { target: null, version: _flashState.version, minimumVersion: _minimumFlashVersion }); } } if (event.type === "copy") { event.clipboardData = { setData: ZeroClipboard.setData, clearData: ZeroClipboard.clearData }; } if (event.type === "aftercopy") { event = _mapClipResultsFromFlash(event, _clipDataFormatMap); } if (event.target && !event.relatedTarget) { event.relatedTarget = _getRelatedTarget(event.target); } return event; }; /** * Get a relatedTarget from the target's `data-clipboard-target` attribute * @private */ var _getRelatedTarget = function(targetEl) { var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target"); return relatedTargetId ? _document.getElementById(relatedTargetId) : null; }; /** * Determine if an event's registered handlers should be execute synchronously or asynchronously. * * @returns {boolean} * @private */ var _shouldPerformAsync = function(event) { var eventType = event && typeof event.type === "string" && event.type || ""; return !/^(?:(?:before)?copy|destroy)$/.test(eventType); }; /** * Control if a callback should be executed asynchronously or not. * * @returns `undefined` * @private */ var _dispatchCallback = function(func, context, args, async) { if (async) { _setTimeout(function() { func.apply(context, args); }, 0); } else { func.apply(context, args); } }; /** * Handle the actual dispatching of events to client instances. * * @returns `undefined` * @private */ var _dispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = _handlers["*"] || []; var specificTypeHandlers = _handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } return this; }; /** * Preprocess any special behaviors, reactions, or state changes after receiving this event. * Executes only once per event emitted, NOT once per client. * @private */ var _preprocessEvent = function(event) { var element = event.target || _currentElement || null; switch (event.type) { case "error": if (_inArray(event.name, [ "flash-disabled", "flash-outdated", "flash-deactivated", "flash-overdue" ])) { _extend(_flashState, { disabled: event.name === "flash-disabled", outdated: event.name === "flash-outdated", unavailable: event.name === "flash-unavailable", deactivated: event.name === "flash-deactivated", overdue: event.name === "flash-overdue", ready: false }); } break; case "ready": var wasDeactivated = _flashState.deactivated === true; _extend(_flashState, { disabled: false, outdated: false, unavailable: false, deactivated: false, overdue: wasDeactivated, ready: !wasDeactivated }); break; case "copy": var textContent, htmlContent, targetEl = event.relatedTarget; if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); if (htmlContent !== textContent) { event.clipboardData.setData("text/html", htmlContent); } } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); } break; case "aftercopy": ZeroClipboard.clearData(); if (element && element !== _safeActiveElement() && element.focus) { element.focus(); } break; } }; /** * Create the HTML bridge element to embed the Flash object into. * @private */ var _createHtmlBridge = function() { var container = _document.createElement("div"); container.id = "global-zeroclipboard-html-bridge"; container.className = "global-zeroclipboard-container"; container.style.position = "absolute"; container.style.left = "0px"; container.style.top = "-9999px"; container.style.width = "1px"; container.style.height = "1px"; container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); return container; }; /** * Get the HTML element container that wraps the Flash bridge object/element. * @private */ var _getHtmlBridge = function(flashBridge) { var htmlBridge = flashBridge && flashBridge.parentNode; while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) { htmlBridge = htmlBridge.parentNode; } return htmlBridge || null; }; /** * Create the SWF object. * * @returns The SWF object reference. * @private */ var _embedSwf = function() { var len, container = _document.getElementById("global-zeroclipboard-html-bridge"), flashBridge = _flashState.bridge; if (!flashBridge) { var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig); var allowNetworking = allowScriptAccess === "never" ? "none" : "all"; var flashvars = _vars(_globalConfig); var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig); container = _createHtmlBridge(); var divToBeReplaced = _document.createElement("div"); container.appendChild(divToBeReplaced); _document.body.appendChild(container); var tmpDiv = _document.createElement("div"); var oldIE = _flashState.pluginType === "activex"; tmpDiv.innerHTML = '<object id="global-zeroclipboard-flash-bridge" name="global-zeroclipboard-flash-bridge" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + "</object>"; flashBridge = tmpDiv.firstChild; tmpDiv = null; flashBridge.ZeroClipboard = ZeroClipboard; container.replaceChild(flashBridge, divToBeReplaced); } if (!flashBridge) { flashBridge = _document["global-zeroclipboard-flash-bridge"]; if (flashBridge && (len = flashBridge.length)) { flashBridge = flashBridge[len - 1]; } if (!flashBridge && container) { flashBridge = container.firstChild; } } _flashState.bridge = flashBridge || null; return flashBridge; }; /** * Destroy the SWF object. * @private */ var _unembedSwf = function() { var flashBridge = _flashState.bridge; if (flashBridge) { var htmlBridge = _getHtmlBridge(flashBridge); if (htmlBridge) { if (_flashState.pluginType === "activex" && "readyState" in flashBridge) { flashBridge.style.display = "none"; (function removeSwfFromIE() { if (flashBridge.readyState === 4) { for (var prop in flashBridge) { if (typeof flashBridge[prop] === "function") { flashBridge[prop] = null; } } if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } else { _setTimeout(removeSwfFromIE, 10); } })(); } else { if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } } _flashState.ready = null; _flashState.bridge = null; _flashState.deactivated = null; } }; /** * Map the data format names of the "clipData" to Flash-friendly names. * * @returns A new transformed object. * @private */ var _mapClipDataToFlash = function(clipData) { var newClipData = {}, formatMap = {}; if (!(typeof clipData === "object" && clipData)) { return; } for (var dataFormat in clipData) { if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) { switch (dataFormat.toLowerCase()) { case "text/plain": case "text": case "air:text": case "flash:text": newClipData.text = clipData[dataFormat]; formatMap.text = dataFormat; break; case "text/html": case "html": case "air:html": case "flash:html": newClipData.html = clipData[dataFormat]; formatMap.html = dataFormat; break; case "application/rtf": case "text/rtf": case "rtf": case "richtext": case "air:rtf": case "flash:rtf": newClipData.rtf = clipData[dataFormat]; formatMap.rtf = dataFormat; break; default: break; } } } return { data: newClipData, formatMap: formatMap }; }; /** * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping). * * @returns A new transformed object. * @private */ var _mapClipResultsFromFlash = function(clipResults, formatMap) { if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) { return clipResults; } var newResults = {}; for (var prop in clipResults) { if (_hasOwn.call(clipResults, prop)) { if (prop !== "success" && prop !== "data") { newResults[prop] = clipResults[prop]; continue; } newResults[prop] = {}; var tmpHash = clipResults[prop]; for (var dataFormat in tmpHash) { if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) { newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat]; } } } } return newResults; }; /** * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}" * query param string to return. Does NOT append that string to the original path. * This is useful because ExternalInterface often breaks when a Flash SWF is cached. * * @returns The `noCache` query param with necessary "?"/"&" prefix. * @private */ var _cacheBust = function(path, options) { var cacheBust = options == null || options && options.cacheBust === true; if (cacheBust) { return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now(); } else { return ""; } }; /** * Creates a query string for the FlashVars param. * Does NOT include the cache-busting query param. * * @returns FlashVars query string * @private */ var _vars = function(options) { var i, len, domain, domains, str = "", trustedOriginsExpanded = []; if (options.trustedDomains) { if (typeof options.trustedDomains === "string") { domains = [ options.trustedDomains ]; } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) { domains = options.trustedDomains; } } if (domains && domains.length) { for (i = 0, len = domains.length; i < len; i++) { if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") { domain = _extractDomain(domains[i]); if (!domain) { continue; } if (domain === "*") { trustedOriginsExpanded = [ domain ]; break; } trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]); } } } if (trustedOriginsExpanded.length) { str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(",")); } if (options.forceEnhancedClipboard === true) { str += (str ? "&" : "") + "forceEnhancedClipboard=true"; } return str; }; /** * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/"). * * @returns the domain * @private */ var _extractDomain = function(originOrUrl) { if (originOrUrl == null || originOrUrl === "") { return null; } originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, ""); if (originOrUrl === "") { return null; } var protocolIndex = originOrUrl.indexOf("//"); originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2); var pathIndex = originOrUrl.indexOf("/"); originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex); if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") { return null; } return originOrUrl || null; }; /** * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`. * * @returns The appropriate script access level. * @private */ var _determineScriptAccess = function() { var _extractAllDomains = function(origins, resultsArray) { var i, len, tmp; if (origins == null || resultsArray[0] === "*") { return; } if (typeof origins === "string") { origins = [ origins ]; } if (!(typeof origins === "object" && typeof origins.length === "number")) { return; } for (i = 0, len = origins.length; i < len; i++) { if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) { if (tmp === "*") { resultsArray.length = 0; resultsArray.push("*"); break; } if (_inArray(tmp, resultsArray) === -1) { resultsArray.push(tmp); } } } }; return function(currentDomain, configOptions) { var swfDomain = _extractDomain(configOptions.swfPath); if (swfDomain === null) { swfDomain = currentDomain; } var trustedDomains = []; _extractAllDomains(configOptions.trustedOrigins, trustedDomains); _extractAllDomains(configOptions.trustedDomains, trustedDomains); var len = trustedDomains.length; if (len > 0) { if (len === 1 && trustedDomains[0] === "*") { return "always"; } if (_inArray(currentDomain, trustedDomains) !== -1) { if (len === 1 && currentDomain === swfDomain) { return "sameDomain"; } return "always"; } } return "never"; }; }(); /** * Get the currently active/focused DOM element. * * @returns the currently active/focused element, or `null` * @private */ var _safeActiveElement = function() { try { return _document.activeElement; } catch (err) { return null; } }; /** * @deprecated * * Add a class to an element, if it doesn't already have it. * * @returns The element, with its new class added. * @private */ var _addClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (!element.classList.contains(value)) { element.classList.add(value); } return element; } if (value && typeof value === "string") { var classNames = (value || "").split(/\s+/); if (element.nodeType === 1) { if (!element.className) { element.className = value; } else { var className = " " + element.className + " ", setClass = element.className; for (var c = 0, cl = classNames.length; c < cl; c++) { if (className.indexOf(" " + classNames[c] + " ") < 0) { setClass += " " + classNames[c]; } } element.className = setClass.replace(/^\s+|\s+$/g, ""); } } } return element; }; /** * @deprecated * * Remove a class from an element, if it has it. * * @returns The element, with its class removed. * @private */ var _removeClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (element.classList.contains(value)) { element.classList.remove(value); } return element; } if (typeof value === "string" && value) { var classNames = value.split(/\s+/); if (element.nodeType === 1 && element.className) { var className = (" " + element.className + " ").replace(/[\n\t]/g, " "); for (var c = 0, cl = classNames.length; c < cl; c++) { className = className.replace(" " + classNames[c] + " ", " "); } element.className = className.replace(/^\s+|\s+$/g, ""); } } return element; }; /** * Convert standard CSS property names into the equivalent CSS property names * for use by oldIE and/or `el.style.{prop}`. * * NOTE: oldIE has other special cases that are not accounted for here, * e.g. "float" -> "styleFloat" * * @example _camelizeCssPropName("z-index") -> "zIndex" * * @returns The CSS property name for oldIE and/or `el.style.{prop}` * @private */ var _camelizeCssPropName = function() { var matcherRegex = /\-([a-z])/g, replacerFn = function(match, group) { return group.toUpperCase(); }; return function(prop) { return prop.replace(matcherRegex, replacerFn); }; }(); /** * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`, * then we assume that it should be a hand ("pointer") cursor if the element * is an anchor element ("a" tag). * * @returns The computed style property. * @private */ var _getStyle = function(el, prop) { var value, camelProp, tagName; if (_window.getComputedStyle) { value = _window.getComputedStyle(el, null).getPropertyValue(prop); } else { camelProp = _camelizeCssPropName(prop); if (el.currentStyle) { value = el.currentStyle[camelProp]; } else { value = el.style[camelProp]; } } if (prop === "cursor") { if (!value || value === "auto") { tagName = el.tagName.toLowerCase(); if (tagName === "a") { return "pointer"; } } } return value; }; /** * Get the zoom factor of the browser. Always returns `1.0`, except at * non-default zoom levels in IE<8 and some older versions of WebKit. * * @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`). * @private */ var _getZoomFactor = function() { var rect, physicalWidth, logicalWidth, zoomFactor = 1; if (typeof _document.body.getBoundingClientRect === "function") { rect = _document.body.getBoundingClientRect(); physicalWidth = rect.right - rect.left; logicalWidth = _document.body.offsetWidth; zoomFactor = _Math.round(physicalWidth / logicalWidth * 100) / 100; } return zoomFactor; }; /** * Get the DOM positioning info of an element. * * @returns Object containing the element's position, width, and height. * @private */ var _getDOMObjectPosition = function(obj) { var info = { left: 0, top: 0, width: 0, height: 0 }; if (obj.getBoundingClientRect) { var rect = obj.getBoundingClientRect(); var pageXOffset, pageYOffset, zoomFactor; if ("pageXOffset" in _window && "pageYOffset" in _window) { pageXOffset = _window.pageXOffset; pageYOffset = _window.pageYOffset; } else { zoomFactor = _getZoomFactor(); pageXOffset = _Math.round(_document.documentElement.scrollLeft / zoomFactor); pageYOffset = _Math.round(_document.documentElement.scrollTop / zoomFactor); } var leftBorderWidth = _document.documentElement.clientLeft || 0; var topBorderWidth = _document.documentElement.clientTop || 0; info.left = rect.left + pageXOffset - leftBorderWidth; info.top = rect.top + pageYOffset - topBorderWidth; info.width = "width" in rect ? rect.width : rect.right - rect.left; info.height = "height" in rect ? rect.height : rect.bottom - rect.top; } return info; }; /** * Reposition the Flash object to cover the currently activated element. * * @returns `undefined` * @private */ var _reposition = function() { var htmlBridge; if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) { var pos = _getDOMObjectPosition(_currentElement); htmlBridge.style.width = pos.width + "px"; htmlBridge.style.height = pos.height + "px"; htmlBridge.style.top = pos.top + "px"; htmlBridge.style.left = pos.left + "px"; htmlBridge.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); } }; /** * Sends a signal to the Flash object to display the hand cursor if `true`. * * @returns `undefined` * @private */ var _setHandCursor = function(enabled) { if (_flashState.ready === true) { if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") { _flashState.bridge.setHandCursor(enabled); } else { _flashState.ready = false; } } }; /** * Get a safe value for `zIndex` * * @returns an integer, or "auto" * @private */ var _getSafeZIndex = function(val) { if (/^(?:auto|inherit)$/.test(val)) { return val; } var zIndex; if (typeof val === "number" && !_isNaN(val)) { zIndex = val; } else if (typeof val === "string") { zIndex = _getSafeZIndex(_parseInt(val, 10)); } return typeof zIndex === "number" ? zIndex : "auto"; }; /** * Detect the Flash Player status, version, and plugin type. * * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code} * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript} * * @returns `undefined` * @private */ var _detectFlashSupport = function(ActiveXObject) { var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = ""; /** * Derived from Apple's suggested sniffer. * @param {String} desc e.g. "Shockwave Flash 7.0 r61" * @returns {String} "7.0.61" * @private */ function parseFlashVersion(desc) { var matches = desc.match(/[\d]+/g); matches.length = 3; return matches.join("."); } function isPepperFlash(flashPlayerFileName) { return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin"); } function inspectPlugin(plugin) { if (plugin) { hasFlash = true; if (plugin.version) { flashVersion = parseFlashVersion(plugin.version); } if (!flashVersion && plugin.description) { flashVersion = parseFlashVersion(plugin.description); } if (plugin.filename) { isPPAPI = isPepperFlash(plugin.filename); } } } if (_navigator.plugins && _navigator.plugins.length) { plugin = _navigator.plugins["Shockwave Flash"]; inspectPlugin(plugin); if (_navigator.plugins["Shockwave Flash 2.0"]) { hasFlash = true; flashVersion = "2.0.0.11"; } } else if (_navigator.mimeTypes && _navigator.mimeTypes.length) { mimeType = _navigator.mimeTypes["application/x-shockwave-flash"]; plugin = mimeType && mimeType.enabledPlugin; inspectPlugin(plugin); } else if (typeof ActiveXObject !== "undefined") { isActiveX = true; try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e1) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); hasFlash = true; flashVersion = "6.0.21"; } catch (e2) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e3) { isActiveX = false; } } } } _flashState.disabled = hasFlash !== true; _flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion); _flashState.version = flashVersion || "0.0.0"; _flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown"; }; /** * Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later. */ _detectFlashSupport(_ActiveXObject); /** * A shell constructor for `ZeroClipboard` client instances. * * @constructor */ var ZeroClipboard = function() { if (!(this instanceof ZeroClipboard)) { return new ZeroClipboard(); } if (typeof ZeroClipboard._createClient === "function") { ZeroClipboard._createClient.apply(this, _args(arguments)); } }; /** * The ZeroClipboard library's version number. * * @static * @readonly * @property {string} */ ZeroClipboard.version = "2.0.0-beta.6"; _makeReadOnly(ZeroClipboard, "version"); /** * Update or get a copy of the ZeroClipboard global configuration. * Returns a copy of the current/updated configuration. * * @returns Object * @static */ ZeroClipboard.config = function() { return _config.apply(this, _args(arguments)); }; /** * Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard. * * @returns Object * @static */ ZeroClipboard.state = function() { return _state.apply(this, _args(arguments)); }; /** * Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc. * * @returns Boolean * @static */ ZeroClipboard.isFlashUnusable = function() { return _isFlashUnusable.apply(this, _args(arguments)); }; /** * Register an event listener. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.on = function() { return _on.apply(this, _args(arguments)); }; /** * Unregister an event listener. * If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`. * If no `eventType` is provided, it will unregister all listeners for every event type. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.off = function() { return _off.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType`. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.handlers = function() { return _listeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. * @static */ ZeroClipboard.emit = function() { return _emit.apply(this, _args(arguments)); }; /** * Create and embed the Flash object. * * @returns The Flash object * @static */ ZeroClipboard.create = function() { return _create.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything, including the embedded Flash object. * * @returns `undefined` * @static */ ZeroClipboard.destroy = function() { return _destroy.apply(this, _args(arguments)); }; /** * Set the pending data for clipboard injection. * * @returns `undefined` * @static */ ZeroClipboard.setData = function() { return _setData.apply(this, _args(arguments)); }; /** * Clear the pending data for clipboard injection. * If no `format` is provided, all pending data formats will be cleared. * * @returns `undefined` * @static */ ZeroClipboard.clearData = function() { return _clearData.apply(this, _args(arguments)); }; /** * Sets the current HTML object that the Flash object should overlay. This will put the global * Flash object on top of the current element; depending on the setup, this may also set the * pending clipboard text data as well as the Flash object's wrapping element's title attribute * based on the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.activate = function() { return _activate.apply(this, _args(arguments)); }; /** * Un-overlays the Flash object. This will put the global Flash object off-screen; depending on * the setup, this may also unset the Flash object's wrapping element's title attribute based on * the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.deactivate = function() { return _deactivate.apply(this, _args(arguments)); }; /** * Keep track of the ZeroClipboard client instance counter. */ var _clientIdCounter = 0; /** * Keep track of the state of the client instances. * * Entry structure: * _clientMeta[client.id] = { * instance: client, * elements: [], * handlers: {} * }; */ var _clientMeta = {}; /** * Keep track of the ZeroClipboard clipped elements counter. */ var _elementIdCounter = 0; /** * Keep track of the state of the clipped element relationships to clients. * * Entry structure: * _elementMeta[element.zcClippingId] = [client1.id, client2.id]; */ var _elementMeta = {}; /** * Keep track of the state of the mouse event handlers for clipped elements. * * Entry structure: * _mouseHandlers[element.zcClippingId] = { * mouseover: function(event) {}, * mouseout: function(event) {} * }; */ var _mouseHandlers = {}; /** * Extending the ZeroClipboard configuration defaults for the Client module. */ _extend(_globalConfig, { autoActivate: true }); /** * The real constructor for `ZeroClipboard` client instances. * @private */ var _clientConstructor = function(elements) { var client = this; client.id = "" + _clientIdCounter++; _clientMeta[client.id] = { instance: client, elements: [], handlers: {} }; if (elements) { client.clip(elements); } ZeroClipboard.on("*", function(event) { return client.emit(event); }); ZeroClipboard.on("destroy", function() { client.destroy(); }); ZeroClipboard.create(); }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.on`. * @private */ var _clientOn = function(eventType, listener) { var i, len, events, added = {}, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { this.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!handlers[eventType]) { handlers[eventType] = []; } handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { this.emit({ type: "ready", client: this }); } if (added.error) { var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ]; for (i = 0, len = errorTypes.length; i < len; i++) { if (_flashState[errorTypes[i]]) { this.emit({ type: "error", name: "flash-" + errorTypes[i], client: this }); break; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.off`. * @private */ var _clientOff = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers; if (arguments.length === 0) { events = _objectKeys(handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { this.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = _inArray(listener, perEventHandlers); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = _inArray(listener, perEventHandlers, foundIndex); } } else { perEventHandlers.length = 0; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.handlers`. * @private */ var _clientListeners = function(eventType) { var copy = null, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers; if (handlers) { if (typeof eventType === "string" && eventType) { copy = handlers[eventType] ? handlers[eventType].slice(0) : []; } else { copy = _deepCopy(handlers); } } return copy; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.emit`. * @private */ var _clientEmit = function(event) { if (_clientShouldEmit.call(this, event)) { if (typeof event === "object" && event && typeof event.type === "string" && event.type) { event = _extend({}, event); } var eventCopy = _extend({}, _createEvent(event), { client: this }); _clientDispatchCallbacks.call(this, eventCopy); } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.clip`. * @private */ var _clientClip = function(elements) { elements = _prepClip(elements); for (var i = 0; i < elements.length; i++) { if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) { if (!elements[i].zcClippingId) { elements[i].zcClippingId = "zcClippingId_" + _elementIdCounter++; _elementMeta[elements[i].zcClippingId] = [ this.id ]; if (_globalConfig.autoActivate === true) { _addMouseHandlers(elements[i]); } } else if (_inArray(this.id, _elementMeta[elements[i].zcClippingId]) === -1) { _elementMeta[elements[i].zcClippingId].push(this.id); } var clippedElements = _clientMeta[this.id] && _clientMeta[this.id].elements; if (_inArray(elements[i], clippedElements) === -1) { clippedElements.push(elements[i]); } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.unclip`. * @private */ var _clientUnclip = function(elements) { var meta = _clientMeta[this.id]; if (!meta) { return this; } var clippedElements = meta.elements; var arrayIndex; if (typeof elements === "undefined") { elements = clippedElements.slice(0); } else { elements = _prepClip(elements); } for (var i = elements.length; i--; ) { if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) { arrayIndex = 0; while ((arrayIndex = _inArray(elements[i], clippedElements, arrayIndex)) !== -1) { clippedElements.splice(arrayIndex, 1); } var clientIds = _elementMeta[elements[i].zcClippingId]; if (clientIds) { arrayIndex = 0; while ((arrayIndex = _inArray(this.id, clientIds, arrayIndex)) !== -1) { clientIds.splice(arrayIndex, 1); } if (clientIds.length === 0) { if (_globalConfig.autoActivate === true) { _removeMouseHandlers(elements[i]); } delete elements[i].zcClippingId; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.elements`. * @private */ var _clientElements = function() { var meta = _clientMeta[this.id]; return meta && meta.elements ? meta.elements.slice(0) : []; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.destroy`. * @private */ var _clientDestroy = function() { this.unclip(); this.off(); delete _clientMeta[this.id]; }; /** * Inspect an Event to see if the Client (`this`) should honor it for emission. * @private */ var _clientShouldEmit = function(event) { if (!(event && event.type)) { return false; } if (event.client && event.client !== this) { return false; } var clippedEls = _clientMeta[this.id] && _clientMeta[this.id].elements; var hasClippedEls = !!clippedEls && clippedEls.length > 0; var goodTarget = !event.target || hasClippedEls && _inArray(event.target, clippedEls) !== -1; var goodRelTarget = event.relatedTarget && hasClippedEls && _inArray(event.relatedTarget, clippedEls) !== -1; var goodClient = event.client && event.client === this; if (!(goodTarget || goodRelTarget || goodClient)) { return false; } return true; }; /** * Handle the actual dispatching of events to a client instance. * * @returns `this` * @private */ var _clientDispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = _clientMeta[this.id] && _clientMeta[this.id].handlers["*"] || []; var specificTypeHandlers = _clientMeta[this.id] && _clientMeta[this.id].handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } return this; }; /** * Prepares the elements for clipping/unclipping. * * @returns An Array of elements. * @private */ var _prepClip = function(elements) { if (typeof elements === "string") { elements = []; } return typeof elements.length !== "number" ? [ elements ] : elements; }; /** * Add an event listener to a DOM element (because IE<9 sucks). * * @returns The element. * @private */ var _addEventHandler = function(element, method, func) { if (!element || element.nodeType !== 1) { return element; } if (element.addEventListener) { element.addEventListener(method, func, false); } else if (element.attachEvent) { element.attachEvent("on" + method, func); } return element; }; /** * Remove an event listener from a DOM element (because IE<9 sucks). * * @returns The element. * @private */ var _removeEventHandler = function(element, method, func) { if (!element || element.nodeType !== 1) { return element; } if (element.removeEventListener) { element.removeEventListener(method, func, false); } else if (element.detachEvent) { element.detachEvent("on" + method, func); } return element; }; /** * Add `mouseover`, `mousedown`, `mouseup`, and `mouseout` handler functions for a clipped element. * * @returns `undefined` * @private */ var _addMouseHandlers = function(element) { if (!(element && element.nodeType === 1)) { return; } var _elementMouseOver, _elementMouseDown, _elementMouseUp, _elementMouseOut; _elementMouseDown = function() { _addClass(element, _globalConfig.activeClass); }; _elementMouseUp = function() { _removeClass(element, _globalConfig.activeClass); }; _elementMouseOut = function(event) { if (!event) { event = _window.event; } if (!event) { return; } var relTarget = event.relatedTarget || event.toElement || null; if (!(relTarget && relTarget.nodeType === 1)) { return; } var htmlBridge; if (_flashState.bridge != null && (relTarget === _flashState.bridge || (htmlBridge = _getHtmlBridge(_flashState.bridge)) && relTarget === htmlBridge)) { return; } ZeroClipboard.deactivate(); _removeEventHandler(element, "mouseup", _elementMouseUp); _removeEventHandler(element, "mousedown", _elementMouseDown); _removeEventHandler(element, "mouseout", _elementMouseOut); ZeroClipboard.off("mouseup", _elementMouseUp); ZeroClipboard.off("mousedown", _elementMouseDown); ZeroClipboard.off("mouseout", _elementMouseOut); }; _elementMouseOver = function(event) { if (!event) { event = _window.event; } if (!event) { return; } ZeroClipboard.activate(element); _addEventHandler(element, "mouseout", _elementMouseOut); _addEventHandler(element, "mousedown", _elementMouseDown); _addEventHandler(element, "mouseup", _elementMouseUp); ZeroClipboard.on("mouseout", _elementMouseOut); ZeroClipboard.on("mousedown", _elementMouseDown); ZeroClipboard.on("mouseup", _elementMouseUp); }; _addEventHandler(element, "mouseover", _elementMouseOver); ZeroClipboard.on("mouseover", _elementMouseOver); _mouseHandlers[element.zcClippingId] = { mouseover: _elementMouseOver, mouseout: _elementMouseOut, mousedown: _elementMouseDown, mouseup: _elementMouseUp }; }; /** * Remove `mouseover`, `mousedown`, `mouseup`, and `mouseout` handler functions for a clipped element. * * @returns `undefined` * @private */ var _removeMouseHandlers = function(element) { if (!(element && element.nodeType === 1)) { return; } var mouseHandlers = _mouseHandlers[element.zcClippingId]; if (!(typeof mouseHandlers === "object" && mouseHandlers)) { return; } if (typeof mouseHandlers.mouseup === "function") { _removeEventHandler(element, "mouseup", mouseHandlers.mouseup); } if (typeof mouseHandlers.mousedown === "function") { _removeEventHandler(element, "mousedown", mouseHandlers.mousedown); } if (typeof mouseHandlers.mouseout === "function") { _removeEventHandler(element, "mouseout", mouseHandlers.mouseout); } if (typeof mouseHandlers.mouseover === "function") { _removeEventHandler(element, "mouseover", mouseHandlers.mouseover); } ZeroClipboard.off("mouseup", mouseHandlers.mouseup); ZeroClipboard.off("mousedown", mouseHandlers.mousedown); ZeroClipboard.off("mouseout", mouseHandlers.mouseout); ZeroClipboard.off("mouseover", mouseHandlers.mouseover); delete _mouseHandlers[element.zcClippingId]; }; /** * Creates a new ZeroClipboard client instance. * Optionally, auto-`clip` an element or collection of elements. * * @constructor */ ZeroClipboard._createClient = function() { _clientConstructor.apply(this, _args(arguments)); }; /** * Register an event listener to the client. * * @returns `this` */ ZeroClipboard.prototype.on = function() { return _clientOn.apply(this, _args(arguments)); }; /** * Unregister an event handler from the client. * If no `listener` function/object is provided, it will unregister all handlers for the provided `eventType`. * If no `eventType` is provided, it will unregister all handlers for every event type. * * @returns `this` */ ZeroClipboard.prototype.off = function() { return _clientOff.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType` from the client. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.prototype.handlers = function() { return _clientListeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object for this client's registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. */ ZeroClipboard.prototype.emit = function() { return _clientEmit.apply(this, _args(arguments)); }; /** * Register clipboard actions for new element(s) to the client. * * @returns `this` */ ZeroClipboard.prototype.clip = function() { return _clientClip.apply(this, _args(arguments)); }; /** * Unregister the clipboard actions of previously registered element(s) on the page. * If no elements are provided, ALL registered elements will be unregistered. * * @returns `this` */ ZeroClipboard.prototype.unclip = function() { return _clientUnclip.apply(this, _args(arguments)); }; /** * Get all of the elements to which this client is clipped. * * @returns array of clipped elements */ ZeroClipboard.prototype.elements = function() { return _clientElements.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything for a single client. * This will NOT destroy the embedded Flash object. * * @returns `undefined` */ ZeroClipboard.prototype.destroy = function() { return _clientDestroy.apply(this, _args(arguments)); }; /** * Stores the pending plain text to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setText = function(text) { ZeroClipboard.setData("text/plain", text); return this; }; /** * Stores the pending HTML text to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setHtml = function(html) { ZeroClipboard.setData("text/html", html); return this; }; /** * Stores the pending rich text (RTF) to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setRichText = function(richText) { ZeroClipboard.setData("application/rtf", richText); return this; }; /** * Stores the pending data to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setData = function() { ZeroClipboard.setData.apply(this, _args(arguments)); return this; }; /** * Clears the pending data to inject into the clipboard. * If no `format` is provided, all pending data formats will be cleared. * * @returns `this` */ ZeroClipboard.prototype.clearData = function() { ZeroClipboard.clearData.apply(this, _args(arguments)); return this; }; if (typeof define === "function" && define.amd) { define(function() { return ZeroClipboard; }); } else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) { module.exports = ZeroClipboard; } else { window.ZeroClipboard = ZeroClipboard; } })(function() { return this; }());
packages/material-ui-icons/src/ChildCareRounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><circle cx="14.5" cy="10.5" r="1.25" /><circle cx="9.5" cy="10.5" r="1.25" /><path d="M16.1 14H7.9c-.19 0-.32.2-.23.37C8.5 15.94 10.13 17 12 17s3.5-1.06 4.33-2.63c.08-.17-.05-.37-.23-.37z" /><path d="M22.94 11.34c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66 0 .23.02.45.06.66.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17.04-.21.06-.43.06-.66 0-.23-.02-.45-.06-.66zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2z" /></React.Fragment> , 'ChildCareRounded');
app/javascript/mastodon/features/ui/components/media_modal.js
3846masa/mastodon
import React from 'react'; import LoadingIndicator from '../../../components/loading_indicator'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ExtendedVideoPlayer from '../../../components/extended_video_player'; import ImageLoader from 'react-imageloader'; import { defineMessages, injectIntl } from 'react-intl'; import IconButton from '../../../components/icon_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ close: { id: 'lightbox.close', defaultMessage: 'Close' }, }); class MediaModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.list.isRequired, index: PropTypes.number.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; state = { index: null, }; handleNextClick = () => { this.setState({ index: (this.getIndex() + 1) % this.props.media.size}); } handlePrevClick = () => { this.setState({ index: (this.getIndex() - 1) % this.props.media.size}); } handleKeyUp = (e) => { switch(e.key) { case 'ArrowLeft': this.handlePrevClick(); break; case 'ArrowRight': this.handleNextClick(); break; } } componentDidMount () { window.addEventListener('keyup', this.handleKeyUp, false); } componentWillUnmount () { window.removeEventListener('keyup', this.handleKeyUp); } getIndex () { return this.state.index !== null ? this.state.index : this.props.index; } render () { const { media, intl, onClose } = this.props; const index = this.getIndex(); const attachment = media.get(index); const url = attachment.get('url'); let leftNav, rightNav, content; leftNav = rightNav = content = ''; if (media.size > 1) { leftNav = <div role='button' tabIndex='0' className='modal-container__nav modal-container__nav--left' onClick={this.handlePrevClick}><i className='fa fa-fw fa-chevron-left' /></div>; rightNav = <div role='button' tabIndex='0' className='modal-container__nav modal-container__nav--right' onClick={this.handleNextClick}><i className='fa fa-fw fa-chevron-right' /></div>; } if (attachment.get('type') === 'image') { content = <ImageLoader src={url} imgProps={{ style: { display: 'block' } }} />; } else if (attachment.get('type') === 'gifv') { content = <ExtendedVideoPlayer src={url} muted={true} controls={false} />; } return ( <div className='modal-root__modal media-modal'> {leftNav} <div className='media-modal__content'> <IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} /> {content} </div> {rightNav} </div> ); } } export default injectIntl(MediaModal);
lib/cli/generators/REACT_SCRIPTS/template/src/stories/index.js
enjoylife/storybook
/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */ import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { linkTo } from '@storybook/addon-links'; import Button from './Button'; import Welcome from './Welcome'; storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />); storiesOf('Button', module) .add('with text', () => <Button onClick={action('clicked')}>Hello Button</Button>) .add('with some emoji', () => <Button onClick={action('clicked')}>😀 😎 👍 💯</Button>);
src/svg-icons/av/featured-video.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvFeaturedVideo = (props) => ( <SvgIcon {...props}> <path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 9H3V5h9v7z"/> </SvgIcon> ); AvFeaturedVideo = pure(AvFeaturedVideo); AvFeaturedVideo.displayName = 'AvFeaturedVideo'; AvFeaturedVideo.muiName = 'SvgIcon'; export default AvFeaturedVideo;
resources/_assets/svg/LogoAndrewTJohnston.js
AndrewTJohnston/andrewtjohnston.com
// Returns SVG of the AndrewTJohnston logo import React from 'react' export default React.createClass({ render() { var transform = "translate(" + this.props.deltax + "," + this.props.deltay + ") scale(" + this.props.scale + ")"; return ( <svg version="1.1" viewBox="0 0 1000 1000" preserveAspectRatio="xMinYMin meet" className={ this.props.classes }> <g transform={ transform }> <rect width="1000" height="176.471"/> <path d="M784.616,264.706V712.27c0,52.967-48.216,95.909-107.69,95.909c-59.477,0-107.693-42.942-107.693-95.909H353.849c0,158.907,144.648,287.73,323.077,287.73C855.353,1000,1000,871.177,1000,712.27V264.706H784.616z"/> <polygon points="215.384,1000 353.849,712.27 461.541,488.487 569.232,712.27 784.616,712.27 569.232,264.706 353.849,264.706 0,1000 "/> </g> </svg> ) } })
src/components/topic/header.js
nickhsine/twreporter-react
import { Link } from 'react-router-dom' import mq from '../../utils/media-query' import React from 'react' import SearchBox from './search-box' import styled from 'styled-components' import WhiteDonationIcon from '../../../static/asset/white-donation-icon.svg' import WhiteLogoIcon from '../../../static/asset/logo-white-s.svg' // @twreporter import { sourceHanSansTC as fontWeight } from '@twreporter/core/lib/constants/font-weight' import DonationLink from '@twreporter/react-components/lib/donation-link-with-utm' const Container = styled.div` position: absolute; z-index: 100; top: 24px; left: 0; width: 100%; text-align: center; > *:nth-child(1) { position: absolute; left: 34px; top: 50%; transform: translateY(-50%); } > *:nth-child(2) { display: inline-block; } > *:nth-child(3) { position: absolute; right: 34px; top: 50%; transform: translateY(-50%); } ` const DonationBtn = styled.div` > svg { margin-right: 8px; width: 24px; } > span { ${mq.mobileOnly` display: none; `} vertical-align: 22%; font-size: 16px; color: #ffffff; letter-spacing: 1px; font-weight: ${fontWeight.normal}; } ` const LogoLink = styled(Link)` svg { height: 48px; width: auto; } ` // TBD fixed on the top needs to be implement function Header() { return ( <Container> <DonationLink utmMedium="topic"> <DonationBtn> <WhiteDonationIcon /> <span>贊助我們</span> </DonationBtn> </DonationLink> <LogoLink to="/"> <WhiteLogoIcon /> </LogoLink> <SearchBox /> </Container> ) } export default Header
src/components/Modal/ModalHeader.js
nolawi/champs-dialog-sg
/** * Copyright 2017 dialog LLC <info@dlg.im> * @flow */ import React from 'react'; import classNames from 'classnames'; import styles from './Modal.css'; export type Props = { className?: string, withBorder?: boolean, children?: React.Element<any> }; function ModalHeader(props: Props): React.Element<any> { const className = classNames(styles.header, { [styles.border]: props.withBorder }, props.className); return ( <header className={className}> {props.children} </header> ); } export default ModalHeader;
ajax/libs/primereact/6.5.1/editor/editor.esm.js
cdnjs/cdnjs
import React, { Component } from 'react'; import { classNames } from 'primereact/core'; 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 _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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 _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } 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; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { 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 _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var Editor = /*#__PURE__*/function (_Component) { _inherits(Editor, _Component); var _super = _createSuper(Editor); function Editor() { _classCallCheck(this, Editor); return _super.apply(this, arguments); } _createClass(Editor, [{ key: "getQuill", value: function getQuill() { return this.quill; } }, { key: "componentDidMount", value: function componentDidMount() { var _this = this; import('quill').then(function (module) { if (module && module.default) { _this.quill = new module.default(_this.editorElement, { modules: _objectSpread({ toolbar: _this.toolbarElement }, _this.props.modules), placeholder: _this.props.placeholder, readOnly: _this.props.readOnly, theme: _this.props.theme, formats: _this.props.formats }); if (_this.props.value) { _this.quill.setContents(_this.quill.clipboard.convert(_this.props.value)); } _this.quill.on('text-change', function (delta, source) { var html = _this.editorElement.children[0].innerHTML; var text = _this.quill.getText(); if (html === '<p><br></p>') { html = null; } if (_this.props.onTextChange) { _this.props.onTextChange({ htmlValue: html, textValue: text, delta: delta, source: source }); } }); _this.quill.on('selection-change', function (range, oldRange, source) { if (_this.props.onSelectionChange) { _this.props.onSelectionChange({ range: range, oldRange: oldRange, source: source }); } }); } }).then(function () { if (_this.quill && _this.quill.getModule('toolbar')) { _this.props.onLoad && _this.props.onLoad(_this.quill); } }); } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.value !== prevProps.value && this.quill && !this.quill.hasFocus()) { if (this.props.value) this.quill.setContents(this.quill.clipboard.convert(this.props.value));else this.quill.setText(''); } } }, { key: "render", value: function render() { var _this2 = this; var containerClass = classNames('p-component p-editor-container', this.props.className); var toolbarHeader = null; if (this.props.headerTemplate) { toolbarHeader = /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.toolbarElement = el; }, className: "p-editor-toolbar" }, this.props.headerTemplate); } else { toolbarHeader = /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.toolbarElement = el; }, className: "p-editor-toolbar" }, /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("select", { className: "ql-header", defaultValue: "0" }, /*#__PURE__*/React.createElement("option", { value: "1" }, "Heading"), /*#__PURE__*/React.createElement("option", { value: "2" }, "Subheading"), /*#__PURE__*/React.createElement("option", { value: "0" }, "Normal")), /*#__PURE__*/React.createElement("select", { className: "ql-font" }, /*#__PURE__*/React.createElement("option", null), /*#__PURE__*/React.createElement("option", { value: "serif" }), /*#__PURE__*/React.createElement("option", { value: "monospace" }))), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-bold", "aria-label": "Bold" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-italic", "aria-label": "Italic" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-underline", "aria-label": "Underline" })), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("select", { className: "ql-color" }), /*#__PURE__*/React.createElement("select", { className: "ql-background" })), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-list", value: "ordered", "aria-label": "Ordered List" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-list", value: "bullet", "aria-label": "Unordered List" }), /*#__PURE__*/React.createElement("select", { className: "ql-align" }, /*#__PURE__*/React.createElement("option", { defaultValue: true }), /*#__PURE__*/React.createElement("option", { value: "center" }), /*#__PURE__*/React.createElement("option", { value: "right" }), /*#__PURE__*/React.createElement("option", { value: "justify" }))), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-link", "aria-label": "Insert Link" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-image", "aria-label": "Insert Image" }), /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-code-block", "aria-label": "Insert Code Block" })), /*#__PURE__*/React.createElement("span", { className: "ql-formats" }, /*#__PURE__*/React.createElement("button", { type: "button", className: "ql-clean", "aria-label": "Remove Styles" }))); } var content = /*#__PURE__*/React.createElement("div", { ref: function ref(el) { return _this2.editorElement = el; }, className: "p-editor-content", style: this.props.style }); return /*#__PURE__*/React.createElement("div", { id: this.props.id, className: containerClass }, toolbarHeader, content); } }]); return Editor; }(Component); _defineProperty(Editor, "defaultProps", { id: null, value: null, style: null, className: null, placeholder: null, readOnly: false, modules: null, formats: null, theme: 'snow', headerTemplate: null, onTextChange: null, onSelectionChange: null, onLoad: null }); export { Editor };
app/javascript/mastodon/components/collapsable.js
alarky/mastodon
import React from 'react'; import Motion from 'react-motion/lib/Motion'; import spring from 'react-motion/lib/spring'; import PropTypes from 'prop-types'; const Collapsable = ({ fullHeight, isVisible, children }) => ( <Motion defaultStyle={{ opacity: !isVisible ? 0 : 100, height: isVisible ? fullHeight : 0 }} style={{ opacity: spring(!isVisible ? 0 : 100), height: spring(!isVisible ? 0 : fullHeight) }}> {({ opacity, height }) => <div style={{ height: `${height}px`, overflow: 'hidden', opacity: opacity / 100, display: Math.floor(opacity) === 0 ? 'none' : 'block' }}> {children} </div> } </Motion> ); Collapsable.propTypes = { fullHeight: PropTypes.number.isRequired, isVisible: PropTypes.bool.isRequired, children: PropTypes.node.isRequired, }; export default Collapsable;
src/svg-icons/device/signal-cellular-connected-no-internet-2-bar.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet2Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M14 22V10L2 22h12zm6-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet2Bar = pure(DeviceSignalCellularConnectedNoInternet2Bar); DeviceSignalCellularConnectedNoInternet2Bar.displayName = 'DeviceSignalCellularConnectedNoInternet2Bar'; DeviceSignalCellularConnectedNoInternet2Bar.muiName = 'SvgIcon'; export default DeviceSignalCellularConnectedNoInternet2Bar;
node_modules/react-bootstrap/es/Modal.js
joekay/awebb
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 _extends from 'babel-runtime/helpers/extends'; import classNames from 'classnames'; import events from 'dom-helpers/events'; import ownerDocument from 'dom-helpers/ownerDocument'; import canUseDOM from 'dom-helpers/util/inDOM'; import getScrollbarSize from 'dom-helpers/util/scrollbarSize'; import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import BaseModal from 'react-overlays/lib/Modal'; import isOverflowing from 'react-overlays/lib/utils/isOverflowing'; import elementType from 'react-prop-types/lib/elementType'; import Fade from './Fade'; import Body from './ModalBody'; import ModalDialog from './ModalDialog'; import Footer from './ModalFooter'; import Header from './ModalHeader'; import Title from './ModalTitle'; import { bsClass, bsSizes, prefix } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; import splitComponentProps from './utils/splitComponentProps'; import { Size } from './utils/StyleConfig'; var propTypes = _extends({}, BaseModal.propTypes, ModalDialog.propTypes, { /** * Include a backdrop component. Specify 'static' for a backdrop that doesn't * trigger an "onHide" when clicked. */ backdrop: PropTypes.oneOf(['static', true, false]), /** * Close the modal when escape key is pressed */ keyboard: PropTypes.bool, /** * Open and close the Modal with a slide and fade animation. */ animation: PropTypes.bool, /** * A Component type that provides the modal content Markup. This is a useful * prop when you want to use your own styles and markup to create a custom * modal component. */ dialogComponentClass: elementType, /** * When `true` The modal will automatically shift focus to itself when it * opens, and replace it to the last focused element when it closes. * Generally this should never be set to false as it makes the Modal less * accessible to assistive technologies, like screen-readers. */ autoFocus: PropTypes.bool, /** * When `true` The modal will prevent focus from leaving the Modal while * open. Consider leaving the default value here, as it is necessary to make * the Modal work well with assistive technologies, such as screen readers. */ enforceFocus: PropTypes.bool, /** * When `true` The modal will restore focus to previously focused element once * modal is hidden */ restoreFocus: PropTypes.bool, /** * When `true` The modal will show itself. */ show: PropTypes.bool, /** * A callback fired when the header closeButton or non-static backdrop is * clicked. Required if either are specified. */ onHide: PropTypes.func, /** * Callback fired before the Modal transitions in */ onEnter: PropTypes.func, /** * Callback fired as the Modal begins to transition in */ onEntering: PropTypes.func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: PropTypes.func, /** * Callback fired right before the Modal transitions out */ onExit: PropTypes.func, /** * Callback fired as the Modal begins to transition out */ onExiting: PropTypes.func, /** * Callback fired after the Modal finishes transitioning out */ onExited: PropTypes.func, /** * @private */ container: BaseModal.propTypes.container }); var defaultProps = _extends({}, BaseModal.defaultProps, { animation: true, dialogComponentClass: ModalDialog }); var childContextTypes = { $bs_modal: PropTypes.shape({ onHide: PropTypes.func }) }; var Modal = function (_React$Component) { _inherits(Modal, _React$Component); function Modal(props, context) { _classCallCheck(this, Modal); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleEntering = _this.handleEntering.bind(_this); _this.handleExited = _this.handleExited.bind(_this); _this.handleWindowResize = _this.handleWindowResize.bind(_this); _this.handleDialogClick = _this.handleDialogClick.bind(_this); _this.state = { style: {} }; return _this; } Modal.prototype.getChildContext = function getChildContext() { return { $bs_modal: { onHide: this.props.onHide } }; }; Modal.prototype.componentWillUnmount = function componentWillUnmount() { // Clean up the listener if we need to. this.handleExited(); }; Modal.prototype.handleEntering = function handleEntering() { // FIXME: This should work even when animation is disabled. events.on(window, 'resize', this.handleWindowResize); this.updateStyle(); }; Modal.prototype.handleExited = function handleExited() { // FIXME: This should work even when animation is disabled. events.off(window, 'resize', this.handleWindowResize); }; Modal.prototype.handleWindowResize = function handleWindowResize() { this.updateStyle(); }; Modal.prototype.handleDialogClick = function handleDialogClick(e) { if (e.target !== e.currentTarget) { return; } this.props.onHide(); }; Modal.prototype.updateStyle = function updateStyle() { if (!canUseDOM) { return; } var dialogNode = this._modal.getDialogElement(); var dialogHeight = dialogNode.scrollHeight; var document = ownerDocument(dialogNode); var bodyIsOverflowing = isOverflowing(ReactDOM.findDOMNode(this.props.container || document.body)); var modalIsOverflowing = dialogHeight > document.documentElement.clientHeight; this.setState({ style: { paddingRight: bodyIsOverflowing && !modalIsOverflowing ? getScrollbarSize() : undefined, paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? getScrollbarSize() : undefined } }); }; Modal.prototype.render = function render() { var _this2 = this; var _props = this.props, backdrop = _props.backdrop, animation = _props.animation, show = _props.show, Dialog = _props.dialogComponentClass, className = _props.className, style = _props.style, children = _props.children, onEntering = _props.onEntering, onExited = _props.onExited, props = _objectWithoutProperties(_props, ['backdrop', 'animation', 'show', 'dialogComponentClass', 'className', 'style', 'children', 'onEntering', 'onExited']); var _splitComponentProps = splitComponentProps(props, BaseModal), baseModalProps = _splitComponentProps[0], dialogProps = _splitComponentProps[1]; var inClassName = show && !animation && 'in'; return React.createElement( BaseModal, _extends({}, baseModalProps, { ref: function ref(c) { _this2._modal = c; }, show: show, onEntering: createChainedFunction(onEntering, this.handleEntering), onExited: createChainedFunction(onExited, this.handleExited), backdrop: backdrop, backdropClassName: classNames(prefix(props, 'backdrop'), inClassName), containerClassName: prefix(props, 'open'), transition: animation ? Fade : undefined, dialogTransitionTimeout: Modal.TRANSITION_DURATION, backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION }), React.createElement( Dialog, _extends({}, dialogProps, { style: _extends({}, this.state.style, style), className: classNames(className, inClassName), onClick: backdrop === true ? this.handleDialogClick : null }), children ) ); }; return Modal; }(React.Component); Modal.propTypes = propTypes; Modal.defaultProps = defaultProps; Modal.childContextTypes = childContextTypes; Modal.Body = Body; Modal.Header = Header; Modal.Title = Title; Modal.Footer = Footer; Modal.Dialog = ModalDialog; Modal.TRANSITION_DURATION = 300; Modal.BACKDROP_TRANSITION_DURATION = 150; export default bsClass('modal', bsSizes([Size.LARGE, Size.SMALL], Modal));
src/routes/account/index.js
terryli1643/daoke-react-c
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'dva' import { Row, Col } from 'antd' import { routerRedux } from 'dva/router' const Account = ({ dispatch, app }) => { const { user } = app const goAddressbook = (type) => { dispatch( routerRedux.push({ pathname: '/account/addressbook', query: { type, }, }) ) } return ( <div className="content-inner"> <Row> <Col span={4}>登录名</Col> <Col>{user.username}</Col> </Row> <Row> <Col span={8}><a href="#" onClick={() => goAddressbook(1)}>收件人管理</a></Col> </Row> <Row> <Col span={8}><a href="#" onClick={() => goAddressbook(2)}>发件人管理</a></Col> </Row> </div> ) } Account.propTypes = { app: PropTypes.object, contact: PropTypes.object, location: PropTypes.object, dispatch: PropTypes.func, loading: PropTypes.object, } export default connect(({ app, contact }) => ({ app, contact }))(Account)
ajax/libs/highcharts/4.1.9/highcharts.src.js
dlueth/cdnjs
// ==ClosureCompiler== // @compilation_level SIMPLE_OPTIMIZATIONS /** * @license Highcharts JS v4.1.9 (2015-10-07) * * (c) 2009-2014 Torstein Honsi * * License: www.highcharts.com/license */ // JSLint options: /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */ /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */ (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, isMS = /(msie|trident|edge)/i.test(userAgent) && !isOpera, docMode8 = doc.documentMode === 8, isWebKit = !isMS && /AppleWebKit/.test(userAgent), isFirefox = /Firefox/.test(userAgent), isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent), SVG_NS = 'http://www.w3.org/2000/svg', hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect, hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38 useCanVG = !hasSVG && !isMS && !!doc.createElement('canvas').getContext, Renderer, hasTouch, symbolSizes = {}, idCounter = 0, garbageBin, defaultOptions, dateFormat, // function pathAnim, timeUnits, noop = function () { return UNDEFINED; }, charts = [], chartCount = 0, PRODUCT = 'Highcharts', VERSION = '4.1.9', // some constants for frequently used strings DIV = 'div', ABSOLUTE = 'absolute', RELATIVE = 'relative', HIDDEN = 'hidden', PREFIX = 'highcharts-', VISIBLE = 'visible', PX = 'px', NONE = 'none', M = 'M', L = 'L', numRegex = /^[0-9]+$/, NORMAL_STATE = '', HOVER_STATE = 'hover', SELECT_STATE = 'select', marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'], // Object for extending Axis AxisPlotLineOrBandExtension, // constants for attributes STROKE_WIDTH = 'stroke-width', // time methods, changed based on whether or not UTC is used Date, // Allow using a different Date class makeTime, timezoneOffset, getTimezoneOffset, getMinutes, getHours, getDay, getDate, getMonth, getFullYear, setMilliseconds, setSeconds, setMinutes, setHours, setDate, setMonth, setFullYear, // lookup over the types and the associated classes seriesTypes = {}, Highcharts; // The Highcharts namespace Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {}; Highcharts.seriesTypes = seriesTypes; /** * Extend an object with the members of another * @param {Object} a The object to be extended * @param {Object} b The object to add to the first one */ var extend = Highcharts.extend = function (a, b) { var n; if (!a) { a = {}; } for (n in b) { a[n] = b[n]; } return a; }; /** * Deep merge two or more objects and return a third object. If the first argument is * true, the contents of the second object is copied into the first object. * Previously this function redirected to jQuery.extend(true), but this had two limitations. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second, * it copied properties from extended prototypes. */ function merge() { var i, args = arguments, len, ret = {}, doCopy = function (copy, original) { var value, key; // An object is replacing a primitive if (typeof copy !== 'object') { copy = {}; } for (key in original) { if (original.hasOwnProperty(key)) { value = original[key]; // Copy the contents of objects, but not arrays or DOM nodes if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' && key !== 'renderTo' && typeof value.nodeType !== 'number') { copy[key] = doCopy(copy[key] || {}, value); // Primitives and arrays are copied over directly } else { copy[key] = original[key]; } } } return copy; }; // If first argument is true, copy into the existing object. Used in setOptions. if (args[0] === true) { ret = args[1]; args = Array.prototype.slice.call(args, 2); } // For each argument, extend the return len = args.length; for (i = 0; i < len; i++) { ret = doCopy(ret, args[i]); } return ret; } /** * Shortcut for parseInt * @param {Object} s * @param {Number} mag Magnitude */ function pInt(s, mag) { return parseInt(s, mag || 10); } /** * Check for string * @param {Object} s */ function isString(s) { return typeof s === 'string'; } /** * Check for object * @param {Object} obj */ function isObject(obj) { return obj && typeof obj === 'object'; } /** * Check for array * @param {Object} obj */ function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } /** * Check for number * @param {Object} n */ function isNumber(n) { return typeof n === 'number'; } function log2lin(num) { return math.log(num) / math.LN10; } function lin2log(num) { return math.pow(10, num); } /** * Remove last occurence of an item from an array * @param {Array} arr * @param {Mixed} item */ function erase(arr, item) { var i = arr.length; while (i--) { if (arr[i] === item) { arr.splice(i, 1); break; } } //return arr; } /** * Returns true if the object is not null or undefined. 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, 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. */ var pick = Highcharts.pick = function () { var args = arguments, i, arg, length = args.length; for (i = 0; i < length; i++) { arg = args[i]; if (arg !== UNDEFINED && arg !== null) { return arg; } } }; /** * Set CSS on a given element * @param {Object} el * @param {Object} styles Style object with camel case property names */ function css(el, styles) { if (isMS && !hasSVG) { // #2686 if (styles && styles.opacity !== UNDEFINED) { styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')'; } } extend(el.style, styles); } /** * Utility function to create element with attributes and styles * @param {Object} tag * @param {Object} attribs * @param {Object} styles * @param {Object} parent * @param {Object} nopad */ function createElement(tag, attribs, styles, parent, nopad) { var el = doc.createElement(tag); if (attribs) { extend(el, attribs); } if (nopad) { css(el, {padding: 0, border: NONE, margin: 0}); } if (styles) { css(el, styles); } if (parent) { parent.appendChild(el); } return el; } /** * Extend a prototyped class by new members * @param {Object} parent * @param {Object} members */ function extendClass(parent, members) { var object = function () { return UNDEFINED; }; object.prototype = new parent(); extend(object.prototype, members); return object; } /** * Pad a string to a given length by adding 0 to the beginning * @param {Number} number * @param {Number} length */ function pad(number, length) { // 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; } /** * Return a length based on either the integer value, or a percentage of a base. */ function relativeLength (value, base) { return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value); } /** * Wrap a method with extended functionality, preserving the original function * @param {Object} obj The context object that the method belongs to * @param {String} method The name of the method to extend * @param {Function} func A wrapper function callback. This function is called with the same arguments * as the original function, except that the original function is unshifted and passed as the first * argument. */ var wrap = Highcharts.wrap = function (obj, method, func) { var proceed = obj[method]; obj[method] = function () { var args = Array.prototype.slice.call(arguments); args.unshift(proceed); return func.apply(this, args); }; }; function getTZOffset(timestamp) { return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000; } /** * Based on http://www.php.net/manual/en/function.strftime.php * @param {String} format * @param {Number} timestamp * @param {Boolean} capitalize */ dateFormat = function (format, timestamp, capitalize) { if (!defined(timestamp) || isNaN(timestamp)) { return defaultOptions.lang.invalidDate || ''; } format = pick(format, '%Y-%m-%d %H:%M:%S'); var date = new Date(timestamp - getTZOffset(timestamp)), key, // used in for constuct below // get the basic time values hours = date[getHours](), day = date[getDay](), dayOfMonth = date[getDate](), month = date[getMonth](), fullYear = date[getFullYear](), lang = defaultOptions.lang, langWeekdays = lang.weekdays, // List all format keys. Custom formats can be added from the outside. replacements = extend({ // Day 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon' 'A': langWeekdays[day], // Long weekday, like 'Monday' 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 'e': dayOfMonth, // Day of the month, 1 through 31 'w': day, // Week (none implemented) //'W': weekNumber(), // Month 'b': lang.shortMonths[month], // Short month, like 'Jan' 'B': lang.months[month], // Long month, like 'January' 'm': pad(month + 1), // Two digit month number, 01 through 12 // Year 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009 'Y': fullYear, // Four digits year, like 2009 // Time 'H': pad(hours), // Two digits hours in 24h format, 00 through 23 'k': hours, // Hours in 24h format, 0 through 23 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby) }, Highcharts.dateFormats); // do the replaces for (key in replacements) { while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]); } } // Optionally capitalize the string and return return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format; }; /** * Format a single variable. Similar to sprintf, without the % prefix. */ function formatSingle(format, val) { var floatRegex = /f$/, decRegex = /\.([0-9])/, lang = defaultOptions.lang, decimals; if (floatRegex.test(format)) { // float decimals = format.match(decRegex); decimals = decimals ? decimals[1] : -1; if (val !== null) { val = Highcharts.numberFormat( val, decimals, lang.decimalPoint, format.indexOf(',') > -1 ? lang.thousandsSep : '' ); } } else { val = dateFormat(format, val); } return val; } /** * Format a string according to a subset of the rules of Python's String.format method. */ function format(str, ctx) { var splitter = '{', isInside = false, segment, valueAndFormat, path, i, len, ret = [], val, index; while ((index = str.indexOf(splitter)) !== -1) { segment = str.slice(0, index); if (isInside) { // we're on the closing bracket looking back valueAndFormat = segment.split(':'); path = valueAndFormat.shift().split('.'); // get first and leave format len = path.length; val = ctx; // Assign deeper paths for (i = 0; i < len; i++) { val = val[path[i]]; } // Format the replacement if (valueAndFormat.length) { val = formatSingle(valueAndFormat.join(':'), val); } // Push the result and advance the cursor ret.push(val); } else { ret.push(segment); } str = str.slice(index + 1); // the rest isInside = !isInside; // toggle splitter = isInside ? '}' : '{'; // now look for next matching bracket } ret.push(str); return ret.join(''); } /** * Get the magnitude of a number */ function getMagnitude(num) { return math.pow(10, mathFloor(math.log(num) / math.LN10)); } /** * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5 * @param {Number} interval * @param {Array} multiples * @param {Number} magnitude * @param {Object} options */ function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) { var normalized, i, retInterval = interval; // round to a tenfold of 1, 2, 2.5 or 5 magnitude = pick(magnitude, 1); normalized = interval / magnitude; // multiples for a linear scale if (!multiples) { multiples = [1, 2, 2.5, 5, 10]; // the allowDecimals option if (allowDecimals === false) { if (magnitude === 1) { multiples = [1, 2, 5, 10]; } else if (magnitude <= 0.1) { multiples = [1 / magnitude]; } } } // normalize the interval to the nearest multiple for (i = 0; i < multiples.length; i++) { retInterval = multiples[i]; if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) { break; } } // multiply back to the correct magnitude retInterval *= magnitude; return retInterval; } /** * Utility method that sorts an object array and keeping the order of equal items. * ECMA script standard does not specify the behaviour when items are equal. */ function stableSort(arr, sortFunction) { var length = arr.length, sortValue, i; // Add index to each item for (i = 0; i < length; i++) { arr[i].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, prec) { return parseFloat( num.toPrecision(prec || 14) ); } /** * Set the global animation to either a given value, or fall back to the * given chart's animation option * @param {Object} animation * @param {Object} chart */ function setAnimation(animation, chart) { chart.renderer.globalAnimation = pick(animation, chart.animation); } /** * The time unit lookup */ timeUnits = { millisecond: 1, second: 1000, minute: 60000, hour: 3600000, day: 24 * 3600000, week: 7 * 24 * 3600000, month: 28 * 24 * 3600000, year: 364 * 24 * 3600000 }; /** * Format a number and return a string based on input settings * @param {Number} number The input number to format * @param {Number} decimals The amount of decimals * @param {String} 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 */ Highcharts.numberFormat = function (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 ? mathMin((n.toString().split('.')[1] || '').length, 20) : // Preserve decimals. Not huge numbers (#3793). (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) : "")); }; /** * 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; /*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 = Fx.step, base; // 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 = $.Tween.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) { var elem; // 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($.cssHooks.opacity, 'get', function (proceed, elem, computed) { return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed); }); // Define the setter function for d (path definitions) this.addAnimSetter('d', 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)); }); /** * 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, len = arr.length; for (i = 0; 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 (this[0]) { 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; }; }, /** * Add an animation setter for a specific property */ addAnimSetter: function (prop, setter) { // jQuery 1.8 style if ($.Tween) { $.Tween.propHooks[prop] = { set: setter }; // pre 1.8 } else { $.fx.step[prop] = setter; } }, /** * 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 returnValue (#2790), 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 (!isMS && eventArguments) { delete eventArguments.layerX; delete eventArguments.layerY; delete eventArguments.returnValue; } 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.hasAnim = 1; // #3342 $el.animate(params, options); }, /** * Stop running animation */ stop: function (el) { if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy $(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 = Highcharts.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 * *****************************************************************************/ defaultOptions = { colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'], symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'], lang: { loading: 'Loading...', months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // invalidDate: '', decimalPoint: '.', numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels resetZoom: 'Reset zoom', resetZoomTitle: 'Reset zoom level 1:1', thousandsSep: ' ' }, global: { useUTC: true, //timezoneOffset: 0, canvasToolsURL: 'http://code.highcharts.com/4.1.9/modules/canvas-tools.js', VMLRadialGradientURL: 'http://code.highcharts.com/4.1.9/gfx/vml-radial-gradient.png' }, chart: { //animation: true, //alignTicks: false, //reflow: true, //className: null, //events: { load, selection }, //margin: [null], //marginTop: null, //marginRight: null, //marginBottom: null, //marginLeft: null, borderColor: '#4572A7', //borderWidth: 0, borderRadius: 0, defaultSeriesType: 'line', ignoreHiddenSeries: true, //inverted: false, //shadow: false, spacing: [10, 10, 15, 10], //spacingTop: 10, //spacingRight: 10, //spacingBottom: 15, //spacingLeft: 10, //style: { // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font // fontSize: '12px' //}, backgroundColor: '#FFFFFF', //plotBackgroundColor: null, plotBorderColor: '#C0C0C0', //plotBorderWidth: 0, //plotShadow: false, //zoomType: '' resetZoomButton: { theme: { zIndex: 20 }, position: { align: 'right', x: -10, //verticalAlign: 'top', y: 10 } // relativeTo: 'plot' } }, title: { text: 'Chart title', align: 'center', // floating: false, margin: 15, // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#333333', fontSize: '18px' } }, subtitle: { text: '', align: 'center', // floating: false // x: 0, // verticalAlign: 'top', // y: null, style: { color: '#555555' } }, plotOptions: { line: { // base series options allowPointSelect: false, showCheckbox: false, animation: { duration: 1000 }, //connectNulls: false, //cursor: 'default', //clip: true, //dashStyle: null, //enableMouseTracking: true, events: {}, //legendIndex: 0, //linecap: 'round', lineWidth: 2, //shadow: false, // stacking: null, marker: { //enabled: true, //symbol: null, lineWidth: 0, radius: 4, lineColor: '#FFFFFF', //fillColor: null, states: { // states for a single point hover: { enabled: true, lineWidthPlus: 1, radiusPlus: 2 }, select: { fillColor: '#FFFFFF', lineColor: '#000000', lineWidth: 2 } } }, point: { events: {} }, dataLabels: { align: 'center', // defer: true, // enabled: false, formatter: function () { return this.y === null ? '' : Highcharts.numberFormat(this.y, -1); }, style: { color: 'contrast', fontSize: '11px', fontWeight: 'bold', textShadow: '0 0 6px contrast, 0 0 3px contrast' }, verticalAlign: 'bottom', // above singular point x: 0, y: 0, // backgroundColor: undefined, // borderColor: undefined, // borderRadius: undefined, // borderWidth: undefined, padding: 5 // shadow: false }, cropThreshold: 300, // draw points outside the plot area when the number of points is less than this pointRange: 0, //pointStart: 0, //pointInterval: 1, //showInLegend: null, // auto: true for standalone series, false for linked series softThreshold: true, states: { // states for the entire series hover: { //enabled: false, lineWidthPlus: 1, marker: { // lineWidth: base + 1, // radius: base + 1 }, halo: { size: 10, opacity: 0.25 } }, select: { marker: {} } }, stickyTracking: true, //tooltip: { //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>' //valueDecimals: null, //xDateFormat: '%A, %b %e, %Y', //valuePrefix: '', //ySuffix: '' //} turboThreshold: 1000 // zIndex: null } }, labels: { //items: [], style: { //font: defaultFont, position: ABSOLUTE, color: '#3E576F' } }, legend: { enabled: true, align: 'center', //floating: false, layout: 'horizontal', labelFormatter: function () { return this.name; }, //borderWidth: 0, borderColor: '#909090', borderRadius: 0, navigation: { // animation: true, activeColor: '#274b6d', // arrowSize: 12 inactiveColor: '#CCC' // style: {} // text styles }, // margin: 20, // reversed: false, shadow: false, // backgroundColor: null, /*style: { padding: '5px' },*/ itemStyle: { color: '#333333', fontSize: '12px', fontWeight: 'bold' }, itemHoverStyle: { //cursor: 'pointer', removed as of #601 color: '#000' }, itemHiddenStyle: { color: '#CCC' }, itemCheckboxStyle: { position: ABSOLUTE, width: '13px', // for IE precision height: '13px' }, // itemWidth: undefined, // symbolRadius: 0, // symbolWidth: 16, symbolPadding: 5, verticalAlign: 'bottom', // width: undefined, x: 0, y: 0, title: { //text: null, style: { fontWeight: 'bold' } } }, loading: { // hideDuration: 100, labelStyle: { fontWeight: 'bold', position: RELATIVE, top: '45%' }, // showDuration: 0, style: { position: ABSOLUTE, backgroundColor: 'white', opacity: 0.5, textAlign: 'center' } }, tooltip: { enabled: true, animation: hasSVG, //crosshairs: null, backgroundColor: 'rgba(249, 249, 249, .85)', borderWidth: 1, borderRadius: 3, dateTimeLabelFormats: { millisecond: '%A, %b %e, %H:%M:%S.%L', second: '%A, %b %e, %H:%M:%S', minute: '%A, %b %e, %H:%M', hour: '%A, %b %e, %H:%M', day: '%A, %b %e, %Y', week: 'Week from %A, %b %e, %Y', month: '%B %Y', year: '%Y' }, footerFormat: '', //formatter: defaultFormatter, headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>', pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', shadow: true, //shape: 'callout', //shared: false, snap: isTouchDevice ? 25 : 10, style: { color: '#333333', cursor: 'default', fontSize: '12px', padding: '8px', pointerEvents: 'none', // #1686 http://caniuse.com/#feat=pointer-events whiteSpace: 'nowrap' } //xDateFormat: '%A, %b %e, %Y', //valueDecimals: null, //valuePrefix: '', //valueSuffix: '' }, credits: { enabled: true, text: 'Highcharts.com', href: 'http://www.highcharts.com', position: { align: 'right', x: -10, verticalAlign: 'bottom', y: -5 }, style: { cursor: 'pointer', color: '#909090', fontSize: '9px' } } }; // 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 globalOptions = defaultOptions.global, useUTC = globalOptions.useUTC, GET = useUTC ? 'getUTC' : 'get', SET = useUTC ? 'setUTC' : 'set'; Date = globalOptions.Date || window.Date; timezoneOffset = useUTC && globalOptions.timezoneOffset; getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset; makeTime = function (year, month, date, hours, minutes, seconds) { var d; if (useUTC) { d = Date.UTC.apply(0, arguments); d += getTZOffset(d); } else { d = new Date( year, month, pick(date, 1), pick(hours, 0), pick(minutes, 0), pick(seconds, 0) ).getTime(); } return d; }; getMinutes = GET + 'Minutes'; getHours = GET + 'Hours'; getDay = GET + 'Day'; getDate = GET + 'Date'; getMonth = GET + 'Month'; getFullYear = GET + 'FullYear'; setMilliseconds = SET + 'Milliseconds'; setSeconds = SET + 'Seconds'; setMinutes = SET + 'Minutes'; setHours = SET + 'Hours'; setDate = SET + 'Date'; setMonth = SET + 'Month'; setFullYear = SET + 'FullYear'; } /** * Merge the default options with custom options and return the new options structure * @param {Object} options The new custom options */ function setOptions(options) { // Copy in the default options defaultOptions = merge(true, defaultOptions, options); // Apply UTC setTimeMethods(); return defaultOptions; } /** * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules * wasn't enough because the setOptions method created a new object. */ function getOptions() { return defaultOptions; } /** * Handle color operations. The object methods are chainable. * @param {String} input The input color in either rbga or hex format */ var rgbaRegEx = /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*\)/, hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/, rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; 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 = rgbaRegEx.exec(input); if (result) { rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)]; } else { // hex result = hexRegEx.exec(input); if (result) { rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1]; } else { // rgb result = rgbRegEx.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, raw: input }; }; /** * A wrapper object for SVG elements */ function SVGElement() {} SVGElement.prototype = { // Default base for animation opacity: 1, // For labels, these CSS properties are applied to the <text> node directly textProps: ['fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color', 'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'], /** * Initialize the SVG renderer * @param {Object} renderer * @param {String} nodeName */ init: function (renderer, nodeName) { var wrapper = this; wrapper.element = nodeName === 'span' ? createElement(nodeName) : doc.createElementNS(SVG_NS, nodeName); wrapper.renderer = renderer; }, /** * Animate a given attribute * @param {Object} params * @param {Number} options 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, this.renderer.globalAnimation, true); stop(this); // stop regardless of animation actually running, or reverting to .attr (#607) if (animOptions) { animOptions = merge(animOptions, {}); //#2625 if (complete) { // allows using a callback with the global animation without overwriting it animOptions.complete = complete; } animate(this, params, animOptions); } else { this.attr(params, null, complete); } return this; }, /** * Build an SVG gradient out of a common JavaScript configuration object */ colorGradient: function (color, prop, elem) { var renderer = this.renderer, colorObject, gradName, gradAttr, radAttr, gradients, gradientObject, stops, stopColor, stopOpacity, radialReference, n, id, key = []; // Apply linear or radial gradients if (color.linearGradient) { gradName = 'linearGradient'; } else if (color.radialGradient) { gradName = 'radialGradient'; } if (gradName) { gradAttr = color[gradName]; gradients = renderer.gradients; stops = color.stops; radialReference = elem.radialReference; // Keep < 2.2 kompatibility if (isArray(gradAttr)) { color[gradName] = gradAttr = { x1: gradAttr[0], y1: gradAttr[1], x2: gradAttr[2], y2: gradAttr[3], gradientUnits: 'userSpaceOnUse' }; } // Correct the radial gradient for the radial reference system if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) { radAttr = gradAttr; // Save the radial attributes for updating gradAttr = merge(gradAttr, renderer.getRadialAttr(radialReference, radAttr), { gradientUnits: 'userSpaceOnUse' } ); } // Build the unique key to detect whether we need to create a new element (#1282) for (n in gradAttr) { if (n !== 'id') { key.push(n, gradAttr[n]); } } for (n in stops) { key.push(stops[n]); } key = key.join(','); // Check if a gradient object with the same config object is created within this renderer if (gradients[key]) { id = gradients[key].attr('id'); } else { // Set the id and create the element gradAttr.id = id = PREFIX + idCounter++; gradients[key] = gradientObject = renderer.createElement(gradName) .attr(gradAttr) .add(renderer.defs); gradientObject.radAttr = radAttr; // The gradient needs to keep a list of stops to be able to destroy them gradientObject.stops = []; each(stops, function (stop) { var stopObject; if (stop[1].indexOf('rgba') === 0) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } stopObject = renderer.createElement('stop').attr({ offset: stop[0], 'stop-color': stopColor, 'stop-opacity': stopOpacity }).add(gradientObject); // Add the stop element to the gradient gradientObject.stops.push(stopObject); }); } // Set the reference to the gradient object elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')'); elem.gradient = key; } }, /** * Apply a polyfill to the text-stroke CSS property, by copying the text element * and apply strokes to the copy. * * Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/ * * docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color */ applyTextShadow: function (textShadow) { var elem = this.element, tspans, hasContrast = textShadow.indexOf('contrast') !== -1, styles = {}, forExport = this.renderer.forExport, // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check // this again with new IE release. In exports, the rendering is passed to PhantomJS. supports = forExport || (elem.style.textShadow !== UNDEFINED && !isMS); // When the text shadow is set to contrast, use dark stroke for light text and vice versa if (hasContrast) { styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill)); } // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this, // it removes the text shadows. if (isWebKit || forExport) { styles.textRendering = 'geometricPrecision'; } /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/) if (elem.textContent.indexOf('2.') === 0) { elem.style['text-shadow'] = 'none'; supports = false; } // */ // No reason to polyfill, we've got native support if (supports) { this.css(styles); // Apply altered textShadow or textRendering workaround } else { this.fakeTS = true; // Fake text shadow // In order to get the right y position of the clones, // copy over the y setter this.ySetter = this.xSetter; tspans = [].slice.call(elem.getElementsByTagName('tspan')); each(textShadow.split(/\s?,\s?/g), function (textShadow) { var firstChild = elem.firstChild, color, strokeWidth; textShadow = textShadow.split(' '); color = textShadow[textShadow.length - 1]; // Approximately tune the settings to the text-shadow behaviour strokeWidth = textShadow[textShadow.length - 2]; if (strokeWidth) { each(tspans, function (tspan, y) { var clone; // Let the first line start at the correct X position if (y === 0) { tspan.setAttribute('x', elem.getAttribute('x')); y = elem.getAttribute('y'); tspan.setAttribute('y', y || 0); if (y === null) { elem.setAttribute('y', 0); } } // Create the clone and apply shadow properties clone = tspan.cloneNode(1); attr(clone, { 'class': PREFIX + 'text-shadow', 'fill': color, 'stroke': color, 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3), 'stroke-width': strokeWidth, 'stroke-linejoin': 'round' }); elem.insertBefore(clone, firstChild); }); } }); } }, /** * Set or get a given attribute * @param {Object|String} hash * @param {Mixed|Undefined} val */ attr: function (hash, val, complete) { var key, value, element = this.element, hasSetSymbolSize, ret = this, skipAttr; // single key-value pair if (typeof hash === 'string' && val !== UNDEFINED) { key = hash; hash = {}; hash[key] = val; } // used as a getter: first argument is a string, second is undefined if (typeof hash === 'string') { ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element); // setter } else { for (key in hash) { value = hash[key]; skipAttr = false; if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) { if (!hasSetSymbolSize) { this.symbolAttr(hash); hasSetSymbolSize = true; } skipAttr = true; } if (this.rotation && (key === 'x' || key === 'y')) { this.doTransform = true; } if (!skipAttr) { (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element); } // Let the shadow follow the main element if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) { this.updateShadows(key, value); } } // Update transform. Do this outside the loop to prevent redundant updating for batch setting // of attributes. if (this.doTransform) { this.updateTransform(); this.doTransform = false; } } // In accordance with animate, run a complete callback if (complete) { complete(); } return ret; }, updateShadows: function (key, value) { var shadows = this.shadows, i = shadows.length; while (i--) { shadows[i].setAttribute( key, key === 'height' ? mathMax(value - (shadows[i].cutHeight || 0), 0) : key === 'd' ? this.d : value ); } }, /** * Add a class name to an element */ addClass: function (className) { var element = this.element, currentClassName = attr(element, 'class') || ''; if (currentClassName.indexOf(className) === -1) { attr(element, 'class', currentClassName + ' ' + className); } return this; }, /* hasClass and removeClass are not (yet) needed hasClass: function (className) { return attr(this.element, 'class').indexOf(className) !== -1; }, removeClass: function (className) { attr(this.element, 'class', attr(this.element, 'class').replace(className, '')); return this; }, */ /** * If one of the symbol size affecting parameters are changed, * check all the others only once for each call to an element's * .attr() method * @param {Object} hash */ symbolAttr: function (hash) { var wrapper = this; each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) { wrapper[key] = pick(hash[key], wrapper[key]); }); wrapper.attr({ d: wrapper.renderer.symbols[wrapper.symbolName]( wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper ) }); }, /** * Apply a clipping path to this object * @param {String} id */ clip: function (clipRect) { return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE); }, /** * Calculate the coordinates needed for drawing a rectangle crisply and return the * calculated attributes * @param {Number} strokeWidth * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ crisp: function (rect) { var wrapper = this, key, attribs = {}, normalizer, strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0; normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors // normalize for crisp edges rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer; rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer; rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer); rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer); rect.strokeWidth = strokeWidth; for (key in rect) { if (wrapper[key] !== rect[key]) { // only set attribute if changed wrapper[key] = attribs[key] = rect[key]; } } return attribs; }, /** * Set styles for the element * @param {Object} styles */ css: function (styles) { var elemWrapper = this, oldStyles = elemWrapper.styles, newStyles = {}, elem = elemWrapper.element, textWidth, n, serializedCss = '', hyphenate, hasNew = !oldStyles; // convert legacy if (styles && styles.color) { styles.fill = styles.color; } // Filter out existing styles to increase performance (#2640) if (oldStyles) { for (n in styles) { if (styles[n] !== oldStyles[n]) { newStyles[n] = styles[n]; hasNew = true; } } } if (hasNew) { textWidth = elemWrapper.textWidth = (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) || elemWrapper.textWidth; // #3501 // Merge the new styles with the old ones if (oldStyles) { styles = extend( oldStyles, newStyles ); } // store object elemWrapper.styles = styles; if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) { delete styles.width; } // serialize and set style attribute if (isMS && !hasSVG) { css(elemWrapper.element, styles); } else { /*jslint unparam: true*/ hyphenate = function (a, b) { return '-' + b.toLowerCase(); }; /*jslint unparam: false*/ for (n in styles) { serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';'; } attr(elem, 'style', serializedCss); // #1881 } // re-build text if (textWidth && elemWrapper.added) { elemWrapper.renderer.buildText(elemWrapper); } } return elemWrapper; }, /** * Add an event listener * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { var svgElement = this, element = svgElement.element; // touch if (hasTouch && eventType === 'click') { element.ontouchstart = function (e) { svgElement.touchEventFired = Date.now(); e.preventDefault(); handler.call(element, e); }; element.onclick = function (e) { if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269 handler.call(element, e); } }; } else { // simplest possible event model for internal use element['on' + eventType] = handler; } return this; }, /** * Set the coordinates needed to draw a consistent radial gradient across * pie slices regardless of positioning inside the chart. The format is * [centerX, centerY, diameter] in pixels. */ setRadialReference: function (coordinates) { var existingGradient = this.renderer.gradients[this.element.gradient]; this.element.radialReference = coordinates; // On redrawing objects with an existing gradient, the gradient needs // to be repositioned (#3801) if (existingGradient && existingGradient.radAttr) { existingGradient.animate( this.renderer.getRadialAttr( coordinates, existingGradient.radAttr ) ); } return this; }, /** * Move an object and its children by x and y values * @param {Number} x * @param {Number} y */ translate: function (x, y) { return this.attr({ translateX: x, translateY: y }); }, /** * Invert a group, rotate and flip */ invert: function () { var wrapper = this; wrapper.inverted = true; wrapper.updateTransform(); return wrapper; }, /** * Private method to update the transform attribute based on internal * properties */ updateTransform: function () { var wrapper = this, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, scaleX = wrapper.scaleX, scaleY = wrapper.scaleY, inverted = wrapper.inverted, rotation = wrapper.rotation, element = wrapper.element, transform; // flipping affects translate as adjustment for flipping around the group's axis if (inverted) { translateX += wrapper.attr('width'); translateY += wrapper.attr('height'); } // Apply translate. Nearly all transformed elements have translation, so instead // of checking for translate = 0, do it always (#1767, #1846). transform = ['translate(' + translateX + ',' + translateY + ')']; // apply rotation if (inverted) { transform.push('rotate(90) scale(-1,1)'); } else if (rotation) { // text rotation transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')'); // Delete bBox memo when the rotation changes //delete wrapper.bBox; } // apply scale if (defined(scaleX) || defined(scaleY)) { transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')'); } if (transform.length) { element.setAttribute('transform', transform.join(' ')); } }, /** * Bring the element to the front */ toFront: function () { var element = this.element; element.parentNode.appendChild(element); return this; }, /** * Break down alignment options like align, verticalAlign, x and y * to x and y relative to the chart. * * @param {Object} alignOptions * @param {Boolean} alignByTranslate * @param {String[Object} box The box to align to, needs a width and height. When the * box is a string, it refers to an object in the Renderer. For example, when * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height * x and y properties. * */ align: function (alignOptions, alignByTranslate, box) { var align, vAlign, x, y, attribs = {}, alignTo, renderer = this.renderer, alignedObjects = renderer.alignedObjects; // First call on instanciate if (alignOptions) { this.alignOptions = alignOptions; this.alignByTranslate = alignByTranslate; if (!box || isString(box)) { // boxes other than renderer handle this internally this.alignTo = alignTo = box || 'renderer'; erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize alignedObjects.push(this); box = null; // reassign it below } // When called on resize, no arguments are supplied } else { alignOptions = this.alignOptions; alignByTranslate = this.alignByTranslate; alignTo = this.alignTo; } box = pick(box, renderer[alignTo], renderer); // Assign variables align = alignOptions.align; vAlign = alignOptions.verticalAlign; x = (box.x || 0) + (alignOptions.x || 0); // default: left align y = (box.y || 0) + (alignOptions.y || 0); // default: top align // Align if (align === 'right' || align === 'center') { x += (box.width - (alignOptions.width || 0)) / { right: 1, center: 2 }[align]; } attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x); // Vertical align if (vAlign === 'bottom' || vAlign === 'middle') { y += (box.height - (alignOptions.height || 0)) / ({ bottom: 1, middle: 2 }[vAlign] || 1); } attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y); // Animate only if already placed this[this.placed ? 'animate' : 'attr'](attribs); this.placed = true; this.alignAttr = attribs; return this; }, /** * Get the bounding box (width, height, x and y) for the element */ getBBox: function (reload) { var wrapper = this, bBox,// = wrapper.bBox, renderer = wrapper.renderer, width, height, rotation = wrapper.rotation, element = wrapper.element, styles = wrapper.styles, rad = rotation * deg2rad, textStr = wrapper.textStr, textShadow, elemStyle = element.style, toggleTextShadowShim, cacheKey; if (textStr !== UNDEFINED) { // Properties that affect bounding box cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(','); // Since numbers are monospaced, and numerical labels appear a lot in a chart, // we assume that a label of n characters has the same bounding box as others // of the same length. if (textStr === '' || numRegex.test(textStr)) { cacheKey = 'num:' + textStr.toString().length + cacheKey; // Caching all strings reduces rendering time by 4-5%. } else { cacheKey = textStr + cacheKey; } } if (cacheKey && !reload) { bBox = renderer.cache[cacheKey]; } // No cache found if (!bBox) { // SVG elements if (element.namespaceURI === SVG_NS || renderer.forExport) { try { // Fails in Firefox if the container has display: none. // When the text shadow shim is used, we need to hide the fake shadows // to get the correct bounding box (#3872) toggleTextShadowShim = this.fakeTS && function (display) { each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) { tspan.style.display = display; }); }; // Workaround for #3842, Firefox reporting wrong bounding box for shadows if (isFirefox && elemStyle.textShadow) { textShadow = elemStyle.textShadow; elemStyle.textShadow = ''; } else if (toggleTextShadowShim) { toggleTextShadowShim(NONE); } bBox = element.getBBox ? // SVG: use extend because IE9 is not allowed to change width and height in case // of rotation (below) extend({}, element.getBBox()) : // Canvas renderer and legacy IE in export mode { width: element.offsetWidth, height: element.offsetHeight }; // #3842 if (textShadow) { elemStyle.textShadow = textShadow; } else if (toggleTextShadowShim) { toggleTextShadowShim(''); } } catch (e) {} // If the bBox is not set, the try-catch block above failed. The other condition // is for Opera that returns a width of -Infinity on hidden elements. if (!bBox || bBox.width < 0) { bBox = { width: 0, height: 0 }; } // VML Renderer or useHTML within SVG } else { bBox = wrapper.htmlGetBBox(); } // True SVG elements as well as HTML elements in modern browsers using the .useHTML option // need to compensated for rotation if (renderer.isSVG) { width = bBox.width; height = bBox.height; // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568) if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') { bBox.height = height = 14; } // Adjust for rotated text if (rotation) { bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad)); bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad)); } } // Cache it if (cacheKey) { renderer.cache[cacheKey] = bBox; } } return bBox; }, /** * Show the element */ show: function (inherit) { return this.attr({ visibility: inherit ? 'inherit' : VISIBLE }); }, /** * Hide the element */ hide: function () { return this.attr({ visibility: HIDDEN }); }, fadeOut: function (duration) { var elemWrapper = this; elemWrapper.animate({ opacity: 0 }, { duration: duration || 150, complete: function () { elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips } }); }, /** * Add the element * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined * to append the element to the renderer.box. */ add: function (parent) { var renderer = this.renderer, element = this.element, inserted; if (parent) { this.parentGroup = parent; } // mark as inverted this.parentInverted = parent && parent.inverted; // build formatted text if (this.textStr !== undefined) { renderer.buildText(this); } // Mark as added this.added = true; // If we're adding to renderer root, or other elements in the group // have a z index, we need to handle it if (!parent || parent.handleZ || this.zIndex) { inserted = this.zIndexSetter(); } // If zIndex is not handled, append at the end if (!inserted) { (parent ? parent.element : renderer.box).appendChild(element); } // fire an event for internal hooks if (this.onAdd) { this.onAdd(); } return this; }, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { var parentNode = element.parentNode; if (parentNode) { parentNode.removeChild(element); } }, /** * Destroy the element and element wrapper */ destroy: function () { var wrapper = this, element = wrapper.element || {}, shadows = wrapper.shadows, parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup, grandParent, key, i; // remove events element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null; stop(wrapper); // stop running animations if (wrapper.clipPath) { wrapper.clipPath = wrapper.clipPath.destroy(); } // Destroy stops in case this is a gradient object if (wrapper.stops) { for (i = 0; i < wrapper.stops.length; i++) { wrapper.stops[i] = wrapper.stops[i].destroy(); } wrapper.stops = null; } // remove element wrapper.safeRemoveChild(element); // destroy shadows if (shadows) { each(shadows, function (shadow) { wrapper.safeRemoveChild(shadow); }); } // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697). while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) { grandParent = parentToClean.parentGroup; wrapper.safeRemoveChild(parentToClean.div); delete parentToClean.div; parentToClean = grandParent; } // remove from alignObjects if (wrapper.alignTo) { erase(wrapper.renderer.alignedObjects, wrapper); } for (key in wrapper) { delete wrapper[key]; } return null; }, /** * Add a shadow to the element. Must be done after the element is added to the DOM * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, shadow, element = this.element, strokeWidth, shadowWidth, shadowElementOpacity, // compensate for inverted plot area transform; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; transform = this.parentInverted ? '(-1,-1)' : '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')'; for (i = 1; i <= shadowWidth; i++) { shadow = element.cloneNode(0); strokeWidth = (shadowWidth * 2) + 1 - (2 * i); attr(shadow, { 'isShadow': 'true', 'stroke': shadowOptions.color || 'black', 'stroke-opacity': shadowElementOpacity * i, 'stroke-width': strokeWidth, 'transform': 'translate' + transform, 'fill': NONE }); if (cutOff) { attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0)); shadow.cutHeight = strokeWidth; } if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } shadows.push(shadow); } this.shadows = shadows; } return this; }, xGetter: function (key) { if (this.element.nodeName === 'circle') { key = { x: 'cx', y: 'cy' }[key] || key; } return this._defaultGetter(key); }, /** * Get the current value of an attribute or pseudo attribute, used mainly * for animation. */ _defaultGetter: function (key) { var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0); if (/^[\-0-9\.]+$/.test(ret)) { // is numerical ret = parseFloat(ret); } return ret; }, dSetter: function (value, key, element) { if (value && value.join) { // join path value = value.join(' '); } if (/(NaN| {2}|^$)/.test(value)) { value = 'M 0 0'; } element.setAttribute(key, value); this[key] = value; }, dashstyleSetter: function (value) { var i; value = value && value.toLowerCase(); if (value) { value = value .replace('shortdashdotdot', '3,1,1,1,1,1,') .replace('shortdashdot', '3,1,1,1') .replace('shortdot', '1,1,') .replace('shortdash', '3,1,') .replace('longdash', '8,3,') .replace(/dot/g, '1,3,') .replace('dash', '4,3,') .replace(/,$/, '') .split(','); // ending comma i = value.length; while (i--) { value[i] = pInt(value[i]) * this['stroke-width']; } value = value.join(',') .replace('NaN', 'none'); // #3226 this.element.setAttribute('stroke-dasharray', value); } }, alignSetter: function (value) { this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]); }, opacitySetter: function (value, key, element) { this[key] = value; element.setAttribute(key, value); }, titleSetter: function (value) { var titleNode = this.element.getElementsByTagName('title')[0]; if (!titleNode) { titleNode = doc.createElementNS(SVG_NS, 'title'); this.element.appendChild(titleNode); } titleNode.appendChild( doc.createTextNode( (String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895 ) ); }, textSetter: function (value) { if (value !== this.textStr) { // Delete bBox memo when the text changes delete this.bBox; this.textStr = value; if (this.added) { this.renderer.buildText(this); } } }, fillSetter: function (value, key, element) { if (typeof value === 'string') { element.setAttribute(key, value); } else if (value) { this.colorGradient(value, key, element); } }, visibilitySetter: function (value, key, element) { // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909) if (value === 'inherit') { element.removeAttribute(key); } else { element.setAttribute(key, value); } }, zIndexSetter: function (value, key) { var renderer = this.renderer, parentGroup = this.parentGroup, parentWrapper = parentGroup || renderer, parentNode = parentWrapper.element || renderer.box, childNodes, otherElement, otherZIndex, element = this.element, inserted, run = this.added, i; if (defined(value)) { element.setAttribute(key, value); // So we can read it for other elements in the group value = +value; if (this[key] === value) { // Only update when needed (#3865) run = false; } this[key] = value; } // Insert according to this and other elements' zIndex. Before .add() is called, // nothing is done. Then on add, or by later calls to zIndexSetter, the node // is placed on the right place in the DOM. if (run) { value = this.zIndex; if (value && parentGroup) { parentGroup.handleZ = true; } childNodes = parentNode.childNodes; for (i = 0; i < childNodes.length && !inserted; i++) { otherElement = childNodes[i]; otherZIndex = attr(otherElement, 'zIndex'); if (otherElement !== element && ( // Insert before the first element with a higher zIndex pInt(otherZIndex) > value || // If no zIndex given, insert before the first element with a zIndex (!defined(value) && defined(otherZIndex)) )) { parentNode.insertBefore(element, otherElement); inserted = true; } } if (!inserted) { parentNode.appendChild(element); } } return inserted; }, _defaultSetter: function (value, key, element) { element.setAttribute(key, value); } }; // Some shared setters and getters SVGElement.prototype.yGetter = SVGElement.prototype.xGetter; SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter = SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter = SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) { this[key] = value; this.doTransform = true; }; // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the // stroke attribute altogether. #1270, #1369, #3065, #3072. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) { this[key] = value; // Only apply the stroke attribute if the stroke width is defined and larger than 0 if (this.stroke && this['stroke-width']) { this.strokeWidth = this['stroke-width']; SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden element.setAttribute('stroke-width', this['stroke-width']); this.hasStroke = true; } else if (key === 'stroke-width' && value === 0 && this.hasStroke) { element.removeAttribute('stroke'); this.hasStroke = false; } }; /** * The default SVG renderer */ var SVGRenderer = function () { this.init.apply(this, arguments); }; SVGRenderer.prototype = { Element: SVGElement, /** * Initialize the SVGRenderer * @param {Object} container * @param {Number} width * @param {Number} height * @param {Boolean} forExport */ init: function (container, width, height, style, forExport, allowHTML) { var renderer = this, loc = location, boxWrapper, element, desc; boxWrapper = renderer.createElement('svg') .attr({ version: '1.1' }) .css(this.getStyle(style)); element = boxWrapper.element; container.appendChild(element); // For browsers other than IE, add the namespace attribute (#1978) if (container.innerHTML.indexOf('xmlns') === -1) { attr(element, 'xmlns', SVG_NS); } // object properties renderer.isSVG = true; renderer.box = element; renderer.boxWrapper = boxWrapper; renderer.alignedObjects = []; // Page url used for internal references. #24, #672, #1070 renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ? 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.allowHTML = allowHTML; renderer.forExport = forExport; renderer.gradients = {}; // Object where gradient SvgElements are stored renderer.cache = {}; // Cache for numerical bounding boxes renderer.setSize(width, height, false); // Issue 110 workaround: // In Firefox, if a div is positioned by percentage, its pixel position may land // between pixels. The container itself doesn't display this, but an SVG element // inside this container will be drawn at subpixel precision. In order to draw // sharp lines, this must be compensated for. This doesn't seem to work inside // iframes though (like in jsFiddle). var subPixelFix, rect; if (isFirefox && container.getBoundingClientRect) { renderer.subPixelFix = subPixelFix = function () { css(container, { left: 0, top: 0 }); rect = container.getBoundingClientRect(); css(container, { left: (mathCeil(rect.left) - rect.left) + PX, top: (mathCeil(rect.top) - rect.top) + PX }); }; // run the fix now subPixelFix(); // run it on resize addEvent(win, 'resize', subPixelFix); } }, getStyle: function (style) { return (this.style = extend({ fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font fontSize: '12px' }, style)); }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none. #608. */ isHidden: function () { return !this.boxWrapper.getBBox().width; }, /** * Destroys the renderer and its allocated members. */ destroy: function () { var renderer = this, rendererDefs = renderer.defs; renderer.box = null; renderer.boxWrapper = renderer.boxWrapper.destroy(); // Call destroy on all gradient elements destroyObjectProperties(renderer.gradients || {}); renderer.gradients = null; // Defs are null in VMLRenderer // Otherwise, destroy them here. if (rendererDefs) { renderer.defs = rendererDefs.destroy(); } // Remove sub pixel fix handler // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed // See issue #982 if (renderer.subPixelFix) { removeEvent(win, 'resize', renderer.subPixelFix); } renderer.alignedObjects = null; return null; }, /** * Create a wrapper for an SVG element * @param {Object} nodeName */ createElement: function (nodeName) { var wrapper = new this.Element(); wrapper.init(this, nodeName); return wrapper; }, /** * Dummy function for use in canvas renderer */ draw: function () {}, /** * Get converted radial gradient attributes */ getRadialAttr: function (radialReference, gradAttr) { return { cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2], cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2], r: gradAttr.r * radialReference[2] }; }, /** * Parse a simple HTML string into SVG tspans * * @param {Object} textNode The parent text SVG node */ buildText: function (wrapper) { var textNode = wrapper.element, renderer = this, forExport = renderer.forExport, textStr = pick(wrapper.textStr, '').toString(), hasMarkup = textStr.indexOf('<') !== -1, lines, childNodes = textNode.childNodes, styleRegex, hrefRegex, parentX = attr(textNode, 'x'), textStyles = wrapper.styles, width = wrapper.textWidth, textLineHeight = textStyles && textStyles.lineHeight, textShadow = textStyles && textStyles.textShadow, ellipsis = textStyles && textStyles.textOverflow === 'ellipsis', i = childNodes.length, tempParent = width && !wrapper.added && this.box, getLineHeight = function (tspan) { return textLineHeight ? pInt(textLineHeight) : renderer.fontMetrics( /(px|em)$/.test(tspan && tspan.style.fontSize) ? tspan.style.fontSize : ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12), tspan ).h; }, unescapeAngleBrackets = function (inputStr) { return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); }; /// remove old text while (i--) { textNode.removeChild(childNodes[i]); } // Skip tspans, add text directly to text node. The forceTSpan is a hook // used in text outline hack. if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) { textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr))); return; // Complex strings, add more logic } else { styleRegex = /<.*style="([^"]+)".*>/; hrefRegex = /<.*href="(http[^"]+)".*>/; if (tempParent) { tempParent.appendChild(textNode); // attach it to the DOM to read offset width } if (hasMarkup) { lines = textStr .replace(/<(b|strong)>/g, '<span style="font-weight:bold">') .replace(/<(i|em)>/g, '<span style="font-style:italic">') .replace(/<a/g, '<span') .replace(/<\/(b|strong|i|em|a)>/g, '</span>') .split(/<br.*?>/g); } else { lines = [textStr]; } // remove empty line at end if (lines[lines.length - 1] === '') { lines.pop(); } // build the lines each(lines, function (line, lineNo) { var spans, spanNo = 0; line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||'); spans = line.split('|||'); each(spans, function (span) { if (span !== '' || spans.length === 1) { var attributes = {}, tspan = doc.createElementNS(SVG_NS, 'tspan'), spanStyle; // #390 if (styleRegex.test(span)) { spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2'); attr(tspan, 'style', spanStyle); } if (hrefRegex.test(span) && !forExport) { // Not for export - #1529 attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"'); css(tspan, { cursor: 'pointer' }); } span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' '); // Nested tags aren't supported, and cause crash in Safari (#1596) if (span !== ' ') { // add the text node tspan.appendChild(doc.createTextNode(span)); if (!spanNo) { // first span in a line, align it to the left if (lineNo && parentX !== null) { attributes.x = parentX; } } else { attributes.dx = 0; // #16 } // add attributes attr(tspan, attributes); // Append it textNode.appendChild(tspan); // first span on subsequent line, add the line height if (!spanNo && lineNo) { // allow getting the right offset height in exporting in IE if (!hasSVG && forExport) { css(tspan, { display: 'block' }); } // Set the line height based on the font size of either // the text element or the tspan element attr( tspan, 'dy', getLineHeight(tspan) ); } /*if (width) { renderer.breakText(wrapper, width); }*/ // Check width and apply soft breaks or ellipsis if (width) { var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273 hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'), tooLong, wasTooLong, actualWidth, rest = [], dy = getLineHeight(tspan), softLineNo = 1, rotation = wrapper.rotation, wordStr = span, // for ellipsis cursor = wordStr.length, // binary search cursor bBox; while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) { wrapper.rotation = 0; // discard rotation when computing box bBox = wrapper.getBBox(true); actualWidth = bBox.width; // Old IE cannot measure the actualWidth for SVG elements (#2314) if (!hasSVG && renderer.forExport) { actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles); } tooLong = actualWidth > width; // For ellipsis, do a binary search for the correct string length if (wasTooLong === undefined) { wasTooLong = tooLong; // First time } if (ellipsis && wasTooLong) { cursor /= 2; if (wordStr === '' || (!tooLong && cursor < 0.5)) { words = []; // All ok, break out } else { if (tooLong) { wasTooLong = true; } wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor)); words = [wordStr + (width > 3 ? '\u2026' : '')]; tspan.removeChild(tspan.firstChild); } // Looping down, this is the first word sequence that is not too long, // so we can move on to build the next line. } else if (!tooLong || words.length === 1) { words = rest; rest = []; if (words.length) { softLineNo++; tspan = doc.createElementNS(SVG_NS, 'tspan'); attr(tspan, { dy: dy, x: parentX }); if (spanStyle) { // #390 attr(tspan, 'style', spanStyle); } textNode.appendChild(tspan); } if (actualWidth > width) { // a single word is pressing it out width = actualWidth; } } else { // append to existing line tspan tspan.removeChild(tspan.firstChild); rest.unshift(words.pop()); } if (words.length) { tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-'))); } } if (wasTooLong) { wrapper.attr('title', wrapper.textStr); } wrapper.rotation = rotation; } spanNo++; } } }); }); if (tempParent) { tempParent.removeChild(textNode); // attach it to the DOM to read offset width } // Apply the text shadow if (textShadow && wrapper.applyTextShadow) { wrapper.applyTextShadow(textShadow); } } }, /* breakText: function (wrapper, width) { var bBox = wrapper.getBBox(), node = wrapper.element, textLength = node.textContent.length, pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width increment = 0, finalPos; if (bBox.width > width) { while (finalPos === undefined) { textLength = node.getSubStringLength(0, pos); if (textLength <= width) { if (increment === -1) { finalPos = pos; } else { increment = 1; } } else { if (increment === 1) { finalPos = pos - 1; } else { increment = -1; } } pos += increment; } } console.log(finalPos, node.getSubStringLength(0, finalPos)) }, */ /** * Returns white for dark colors and black for bright colors */ getContrast: function (color) { color = Color(color).rgba; return color[0] + color[1] + color[2] > 384 ? '#000000' : '#FFFFFF'; }, /** * Create a button with preset states * @param {String} text * @param {Number} x * @param {Number} y * @param {Function} callback * @param {Object} normalState * @param {Object} hoverState * @param {Object} pressedState */ button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) { var label = this.label(text, x, y, shape, null, null, null, null, 'button'), curState = 0, stateOptions, stateStyle, normalStyle, hoverStyle, pressedStyle, disabledStyle, verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 }; // Normal state - prepare the attributes normalState = merge({ 'stroke-width': 1, stroke: '#CCCCCC', fill: { linearGradient: verticalGradient, stops: [ [0, '#FEFEFE'], [1, '#F6F6F6'] ] }, r: 2, padding: 5, style: { color: 'black' } }, normalState); normalStyle = normalState.style; delete normalState.style; // Hover state hoverState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#FFF'], [1, '#ACF'] ] } }, hoverState); hoverStyle = hoverState.style; delete hoverState.style; // Pressed state pressedState = merge(normalState, { stroke: '#68A', fill: { linearGradient: verticalGradient, stops: [ [0, '#9BD'], [1, '#CDF'] ] } }, pressedState); pressedStyle = pressedState.style; delete pressedState.style; // Disabled state disabledState = merge(normalState, { style: { color: '#CCC' } }, disabledState); disabledStyle = disabledState.style; delete disabledState.style; // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667). addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () { if (curState !== 3) { label.attr(hoverState) .css(hoverStyle); } }); addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () { if (curState !== 3) { stateOptions = [normalState, hoverState, pressedState][curState]; stateStyle = [normalStyle, hoverStyle, pressedStyle][curState]; label.attr(stateOptions) .css(stateStyle); } }); label.setState = function (state) { label.state = curState = state; if (!state) { label.attr(normalState) .css(normalStyle); } else if (state === 2) { label.attr(pressedState) .css(pressedStyle); } else if (state === 3) { label.attr(disabledState) .css(disabledStyle); } }; return label .on('click', function (e) { if (curState !== 3) { callback.call(label, e); } }) .attr(normalState) .css(extend({ cursor: 'default' }, normalStyle)); }, /** * Make a straight line crisper by not spilling out to neighbour pixels * @param {Array} points * @param {Number} width */ crispLine: function (points, width) { // points format: [M, 0, 0, L, 100, 0] // normalize to a crisp line if (points[1] === points[4]) { // Substract due to #1129. Now bottom and left axis gridlines behave the same. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2); } if (points[2] === points[5]) { points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2); } return points; }, /** * Draw a path * @param {Array} path An SVG path in array form */ path: function (path) { var attr = { fill: NONE }; if (isArray(path)) { attr.d = path; } else if (isObject(path)) { // attributes extend(attr, path); } return this.createElement('path').attr(attr); }, /** * Draw and return an SVG circle * @param {Number} x The x position * @param {Number} y The y position * @param {Number} r The radius */ circle: function (x, y, r) { var attr = isObject(x) ? x : { x: x, y: y, r: r }, wrapper = this.createElement('circle'); wrapper.xSetter = function (value) { this.element.setAttribute('cx', value); }; wrapper.ySetter = function (value) { this.element.setAttribute('cy', value); }; return wrapper.attr(attr); }, /** * Draw and return an arc * @param {Number} x X position * @param {Number} y Y position * @param {Number} r Radius * @param {Number} innerR Inner radius like used in donut charts * @param {Number} start Starting angle * @param {Number} end Ending angle */ arc: function (x, y, r, innerR, start, end) { var arc; if (isObject(x)) { y = x.y; r = x.r; innerR = x.innerR; start = x.start; end = x.end; x = x.x; } // Arcs are defined as symbols for the ability to set // attributes in attr and animate arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, { innerR: innerR || 0, start: start || 0, end: end || 0 }); arc.r = r; // #959 return arc; }, /** * Draw and return a rectangle * @param {Number} x Left position * @param {Number} y Top position * @param {Number} width * @param {Number} height * @param {Number} r Border corner radius * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing */ rect: function (x, y, width, height, r, strokeWidth) { r = isObject(x) ? x.r : r; var wrapper = this.createElement('rect'), attribs = isObject(x) ? x : x === UNDEFINED ? {} : { x: x, y: y, width: mathMax(width, 0), height: mathMax(height, 0) }; if (strokeWidth !== UNDEFINED) { attribs.strokeWidth = strokeWidth; attribs = wrapper.crisp(attribs); } if (r) { attribs.r = r; } wrapper.rSetter = function (value) { attr(this.element, { rx: value, ry: value }); }; return wrapper.attr(attribs); }, /** * Resize the box and re-align all aligned elements * @param {Object} width * @param {Object} height * @param {Boolean} animate * */ setSize: function (width, height, animate) { var renderer = this, alignedObjects = renderer.alignedObjects, i = alignedObjects.length; renderer.width = width; renderer.height = height; renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({ width: width, height: height }); while (i--) { alignedObjects[i].align(); } }, /** * Create a group * @param {String} name The group will be given a class name of 'highcharts-{name}'. * This can be used for styling and scripting. */ g: function (name) { var elem = this.createElement('g'); return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem; }, /** * Display an image * @param {String} src * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ image: function (src, x, y, width, height) { var attribs = { preserveAspectRatio: NONE }, elemWrapper; // optional properties if (arguments.length > 1) { extend(attribs, { x: x, y: y, width: width, height: height }); } elemWrapper = this.createElement('image').attr(attribs); // set the href in the xlink namespace if (elemWrapper.element.setAttributeNS) { elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink', 'href', src); } else { // could be exporting in IE // using href throws "not supported" in ie7 and under, requries regex shim to fix later elemWrapper.element.setAttribute('hc-svg-href', src); } return elemWrapper; }, /** * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object. * * @param {Object} symbol * @param {Object} x * @param {Object} y * @param {Object} radius * @param {Object} options */ symbol: function (symbol, x, y, width, height, options) { var 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] || (options && options.width && options.height && [options.width, options.height]); // Ireate the image synchronously, add attribs async obj = this.image(imageSrc) .attr({ x: x, y: y }); obj.isImg = true; if (imageSize) { centerImage(obj, imageSize); } else { // Initialize image to be 0 size so export will still function if there's no cached sizes. obj.attr({ width: 0, height: 0 }); // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8, // the created element must be assigned to a variable in order to load (#292). imageElement = createElement('img', { onload: function () { // Special case for SVGs on IE11, the width is not accessible until the image is // part of the DOM (#2854). if (this.width === 0) { css(this, { position: ABSOLUTE, top: '-999em' }); document.body.appendChild(this); } // Center the image centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]); // Clean up after #2854 workaround. if (this.parentNode) { this.parentNode.removeChild(this); } }, 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 ]; }, /** * Callout shape used for default tooltips, also used for rounded rectangles in VML */ callout: function (x, y, w, h, options) { var arrowLength = 6, halfDistance = 6, r = mathMin((options && options.r) || 0, w, h), safeDistance = r + halfDistance, anchorX = options && options.anchorX, anchorY = options && options.anchorY, path; path = [ 'M', x + r, y, 'L', x + w - r, y, // top side 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner 'L', x + w, y + h - r, // right side 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner 'L', x + r, y + h, // bottom side 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner 'L', x, y + r, // left side 'C', x, y, x, y, x + r, y // top-right corner ]; if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side path.splice(13, 3, 'L', x + w, anchorY - halfDistance, x + w + arrowLength, anchorY, x + w, anchorY + halfDistance, x + w, y + h - r ); } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side path.splice(33, 3, 'L', x, anchorY + halfDistance, x - arrowLength, anchorY, x, anchorY - halfDistance, x, y + r ); } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom path.splice(23, 3, 'L', anchorX + halfDistance, y + h, anchorX, y + h + arrowLength, anchorX - halfDistance, y + h, x + r, y + h ); } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top path.splice(3, 3, 'L', anchorX - halfDistance, y, anchorX, y - arrowLength, anchorX + halfDistance, y, w - r, y ); } return path; } }, /** * Define a clipping rectangle * @param {String} id * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { var wrapper, id = PREFIX + idCounter++, clipPath = this.createElement('clipPath').attr({ id: id }).add(this.defs); wrapper = this.rect(x, y, width, height, 0).add(clipPath); wrapper.id = id; wrapper.clipPath = clipPath; wrapper.count = 0; return wrapper; }, /** * Add text to the SVG object * @param {String} str * @param {Number} x Left position * @param {Number} y Top position * @param {Boolean} useHTML Use HTML to render the text */ text: function (str, x, y, useHTML) { // declare variables var renderer = this, fakeSVG = useCanVG || (!hasSVG && renderer.forExport), wrapper, attr = {}; if (useHTML && (renderer.allowHTML || !renderer.forExport)) { return renderer.html(str, x, y); } attr.x = Math.round(x || 0); // X is always needed for line-wrap logic if (y) { attr.y = Math.round(y); } if (str || str === 0) { attr.text = str; } wrapper = renderer.createElement('text') .attr(attr); // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063) if (fakeSVG) { wrapper.css({ position: ABSOLUTE }); } if (!useHTML) { wrapper.xSetter = function (value, key, element) { var tspans = element.getElementsByTagName('tspan'), tspan, parentVal = element.getAttribute(key), i; for (i = 0; i < tspans.length; i++) { tspan = tspans[i]; // If the x values are equal, the tspan represents a linebreak if (tspan.getAttribute(key) === parentVal) { tspan.setAttribute(key, value); } } element.setAttribute(key, value); }; } return wrapper; }, /** * Utility to return the baseline offset and total line height from the font size */ fontMetrics: function (fontSize, elem) { var lineHeight, baseline, style; fontSize = fontSize || this.style.fontSize; if (!fontSize && elem && win.getComputedStyle) { elem = elem.element || elem; // SVGElement style = win.getComputedStyle(elem, ""); fontSize = style && style.fontSize; // #4309, the style doesn't exist inside a hidden iframe in Firefox } fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12; // Empirical values found by comparing font size and bounding box height. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/ lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2); baseline = mathRound(lineHeight * 0.8); return { h: lineHeight, b: baseline, f: fontSize }; }, /** * Correct X and Y positioning of a label for rotation (#1764) */ rotCorr: function (baseline, rotation, alterY) { var y = baseline; if (rotation && alterY) { y = mathMax(y * mathCos(rotation * deg2rad), 4); } return { x: (-baseline / 3) * mathSin(rotation * deg2rad), y: y }; }, /** * Add a label, a text item that can hold a colored or gradient background * as well as a border and shadow. * @param {string} str * @param {Number} x * @param {Number} y * @param {String} shape * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the * coordinates it should be pinned to * @param {Number} anchorY * @param {Boolean} baseline Whether to position the label relative to the text baseline, * like renderer.text, or to the upper border of the rectangle. * @param {String} className Class name for the group */ label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) { var renderer = this, wrapper = renderer.g(className), text = renderer.text('', 0, 0, useHTML) .attr({ zIndex: 1 }), //.add(wrapper), box, bBox, alignFactor = 0, padding = 3, paddingLeft = 0, width, height, wrapperX, wrapperY, crispAdjust = 0, deferredAttr = {}, baselineOffset, needsBox; /** * 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) && defined(text.textStr) && text.getBBox(); //#3295 && 3514 box failure when string equals 0 wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft; wrapper.height = (height || bBox.height || 0) + 2 * padding; // update the label-scoped y offset baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b; if (needsBox) { // create the border box if it is not already present if (!box) { boxX = mathRound(-alignFactor * padding) + crispAdjust; boxY = (baseline ? -baselineOffset : 0) + crispAdjust; wrapper.box = box = shape ? renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) : renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]); if (!box.isImg) { // #4324, fill "none" causes it to be ignored by mouse events in IE box.attr('fill', NONE); } box.add(wrapper); } // apply the box attributes if (!box.isImg) { // #1630 box.attr(extend({ width: mathRound(wrapper.width), height: mathRound(wrapper.height) }, deferredAttr)); } deferredAttr = null; } } /** * This function runs after setting text or padding, but only if padding is changed */ 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) && bBox && (textAlign === 'center' || textAlign === 'right')) { x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width); } // update if anything changed if (x !== text.x || y !== text.y) { text.attr('x', x); if (y !== UNDEFINED) { text.attr('y', y); } } // record current values text.x = x; text.y = y; } /** * Set a box attribute, or defer it if the box is not yet created * @param {Object} key * @param {Object} value */ function boxAttr(key, value) { if (box) { box.attr(key, value); } else { deferredAttr[key] = value; } } /** * After the text element is added, get the desired size of the border box * and add it before the text in the DOM. */ wrapper.onAdd = function () { text.add(wrapper); wrapper.attr({ text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value x: x, y: y }); if (box && defined(anchorX)) { wrapper.attr({ anchorX: anchorX, anchorY: anchorY }); } }; /* * Add specific attribute setters. */ // only change local variables wrapper.widthSetter = function (value) { width = value; }; wrapper.heightSetter = function (value) { height = value; }; wrapper.paddingSetter = function (value) { if (defined(value) && value !== padding) { padding = wrapper.padding = value; updateTextPadding(); } }; wrapper.paddingLeftSetter = function (value) { if (defined(value) && value !== paddingLeft) { paddingLeft = value; updateTextPadding(); } }; // change local variable and prevent setting attribute on the group wrapper.alignSetter = function (value) { alignFactor = { left: 0, center: 0.5, right: 1 }[value]; }; // apply these to the box and the text alike wrapper.textSetter = function (value) { if (value !== UNDEFINED) { text.textSetter(value); } updateBoxSize(); updateTextPadding(); }; // apply these to the box but not to the text wrapper['stroke-widthSetter'] = function (value, key) { if (value) { needsBox = true; } crispAdjust = value % 2 / 2; boxAttr(key, value); }; wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) { if (key === 'fill' && value) { needsBox = true; } boxAttr(key, value); }; wrapper.anchorXSetter = function (value, key) { anchorX = value; boxAttr(key, mathRound(value) - crispAdjust - wrapperX); }; wrapper.anchorYSetter = function (value, key) { anchorY = value; boxAttr(key, value - wrapperY); }; // rename attributes wrapper.xSetter = function (value) { wrapper.x = value; // for animation getter if (alignFactor) { value -= alignFactor * ((width || bBox.width) + padding); } wrapperX = mathRound(value); wrapper.attr('translateX', wrapperX); }; wrapper.ySetter = function (value) { wrapperY = wrapper.y = mathRound(value); wrapper.attr('translateY', wrapperY); }; // Redirect certain methods to either the box or the text var baseCss = wrapper.css; return extend(wrapper, { /** * Pick up some properties and apply them to the text instead of the wrapper */ css: function (styles) { if (styles) { var textStyles = {}; styles = merge(styles); // create a copy to avoid altering the original object (#537) each(wrapper.textProps, function (prop) { if (styles[prop] !== UNDEFINED) { textStyles[prop] = styles[prop]; delete styles[prop]; } }); text.css(textStyles); } return baseCss.call(wrapper, styles); }, /** * Return the bounding box of the box, not the group */ getBBox: function () { return { width: bBox.width + 2 * padding, height: bBox.height + 2 * padding, x: bBox.x - padding, y: bBox.y - padding }; }, /** * Apply the shadow to the box */ shadow: function (b) { if (box) { box.shadow(b); } return wrapper; }, /** * Destroy and release memory. */ destroy: function () { // Added by button implementation removeEvent(wrapper.element, 'mouseenter'); removeEvent(wrapper.element, 'mouseleave'); if (text) { text = text.destroy(); } if (box) { box = box.destroy(); } // Call base implementation to destroy the rest SVGElement.prototype.destroy.call(wrapper); // Release local pointers (#1298) wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null; } }); } }; // end SVGRenderer // general renderer Renderer = SVGRenderer; // extend SvgElement for useHTML option extend(SVGElement.prototype, { /** * Apply CSS to HTML elements. This is used in text within SVG rendering and * by the VML renderer */ htmlCss: function (styles) { var wrapper = this, element = wrapper.element, textWidth = styles && element.tagName === 'SPAN' && styles.width; if (textWidth) { delete styles.width; wrapper.textWidth = textWidth; wrapper.updateTransform(); } if (styles && styles.textOverflow === 'ellipsis') { styles.whiteSpace = 'nowrap'; styles.overflow = 'hidden'; } wrapper.styles = extend(wrapper.styles, styles); css(wrapper.element, styles); return wrapper; }, /** * VML and useHTML method for calculating the bounding box based on offsets * @param {Boolean} refresh Whether to force a fresh value from the DOM or to * use the cached value * * @return {Object} A hash containing values for x, y, width and height */ htmlGetBBox: function () { var wrapper = this, element = wrapper.element; // faking getBBox in exported SVG in legacy IE // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?) if (element.nodeName === 'text') { element.style.position = ABSOLUTE; } return { x: element.offsetLeft, y: element.offsetTop, width: element.offsetWidth, height: element.offsetHeight }; }, /** * VML override private method to update elements based on internal * properties based on SVG transform */ htmlUpdateTransform: function () { // aligning non added elements is expensive if (!this.added) { this.alignOnAdd = true; return; } var wrapper = this, renderer = wrapper.renderer, elem = wrapper.element, translateX = wrapper.translateX || 0, translateY = wrapper.translateY || 0, x = wrapper.x || 0, y = wrapper.y || 0, align = wrapper.textAlign || 'left', alignCorrection = { left: 0, center: 0.5, right: 1 }[align], shadows = wrapper.shadows, styles = wrapper.styles; // apply translate css(elem, { marginLeft: translateX, marginTop: translateY }); if (shadows) { // used in labels/tooltip each(shadows, function (shadow) { css(shadow, { marginLeft: translateX + 1, marginTop: translateY + 1 }); }); } // apply inversion if (wrapper.inverted) { // wrapper is a group each(elem.childNodes, function (child) { renderer.invertChild(child, elem); }); } if (elem.tagName === 'SPAN') { var width, rotation = wrapper.rotation, baseline, textWidth = pInt(wrapper.textWidth), currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(','); if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed baseline = renderer.fontMetrics(elem.style.fontSize).b; // Renderer specific handling of span rotation if (defined(rotation)) { wrapper.setSpanRotation(rotation, alignCorrection, baseline); } width = pick(wrapper.elemWidth, elem.offsetWidth); // Update textWidth if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254 css(elem, { width: textWidth + PX, display: 'block', whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331 }); width = textWidth; } wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align); } // apply position with correction css(elem, { left: (x + (wrapper.xCorr || 0)) + PX, top: (y + (wrapper.yCorr || 0)) + PX }); // force reflow in webkit to apply the left and top on useHTML element (#1249) if (isWebKit) { baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose } // record current text transform wrapper.cTT = currentTextTransform; } }, /** * Set the rotation of an individual HTML span */ setSpanRotation: function (rotation, alignCorrection, baseline) { var rotationStyle = {}, cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : ''; rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)'; rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px'; css(this.element, rotationStyle); }, /** * Get the correction in X and Y positioning as the element is rotated. */ getSpanCorrection: function (width, baseline, alignCorrection) { this.xCorr = -width * alignCorrection; this.yCorr = -baseline; } }); // Extend SvgRenderer for useHTML option. extend(SVGRenderer.prototype, { /** * Create HTML text node. This is used by the VML renderer as well as the SVG * renderer through the useHTML option. * * @param {String} str * @param {Number} x * @param {Number} y */ html: function (str, x, y) { var wrapper = this.createElement('span'), element = wrapper.element, renderer = wrapper.renderer; // Text setter wrapper.textSetter = function (value) { if (value !== element.innerHTML) { delete this.bBox; } element.innerHTML = this.textStr = value; wrapper.htmlUpdateTransform(); }; // Various setters which rely on update transform wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) { if (key === 'align') { key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML. } wrapper[key] = value; wrapper.htmlUpdateTransform(); }; // Set the default attributes wrapper.attr({ text: str, x: mathRound(x), y: mathRound(y) }) .css({ position: ABSOLUTE, fontFamily: this.style.fontFamily, fontSize: this.style.fontSize }); // Keep the whiteSpace style outside the wrapper.styles collection element.style.whiteSpace = 'nowrap'; // Use the HTML specific .css method wrapper.css = wrapper.htmlCss; // This is specific for HTML within SVG if (renderer.isSVG) { wrapper.add = function (svgGroupWrapper) { var htmlGroup, container = renderer.box.parentNode, parentGroup, parents = []; this.parentGroup = svgGroupWrapper; // Create a mock group to hold the HTML elements if (svgGroupWrapper) { htmlGroup = svgGroupWrapper.div; if (!htmlGroup) { // Read the parent chain into an array and read from top down parentGroup = svgGroupWrapper; while (parentGroup) { parents.push(parentGroup); // Move up to the next parent group parentGroup = parentGroup.parentGroup; } // Ensure dynamically updating position when any parent is translated each(parents.reverse(), function (parentGroup) { var htmlGroupStyle, cls = attr(parentGroup.element, 'class'); if (cls) { cls = { className: cls }; } // else null // Create a HTML div and append it to the parent div to emulate // the SVG group structure htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, cls, { position: ABSOLUTE, left: (parentGroup.translateX || 0) + PX, top: (parentGroup.translateY || 0) + PX }, htmlGroup || container); // the top group is appended to container // Shortcut htmlGroupStyle = htmlGroup.style; // Set listeners to update the HTML div's position whenever the SVG group // position is changed extend(parentGroup, { translateXSetter: function (value, key) { htmlGroupStyle.left = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; }, translateYSetter: function (value, key) { htmlGroupStyle.top = value + PX; parentGroup[key] = value; parentGroup.doTransform = true; } }); // These properties are set as attributes on the SVG group, and as // identical CSS properties on the div. (#3542) each(['opacity', 'visibility'], function (prop) { wrap(parentGroup, prop + 'Setter', function (proceed, value, key, elem) { proceed.call(this, value, key, elem); htmlGroupStyle[key] = value; }); }); }); } } else { htmlGroup = container; } htmlGroup.appendChild(element); // Shared with VML: wrapper.added = true; if (wrapper.alignOnAdd) { wrapper.htmlUpdateTransform(); } return wrapper; }; } return wrapper; } }); /* **************************************************************************** * * * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * * For applications and websites that don't need IE support, like platform * * targeted mobile apps and web apps, this code can be removed. * * * *****************************************************************************/ /** * @constructor */ var VMLRenderer, VMLElement; if (!hasSVG && !useCanVG) { /** * The VML element wrapper. */ VMLElement = { /** * Initialize a new VML element wrapper. It builds the markup as a string * to minimize DOM traffic. * @param {Object} renderer * @param {Object} nodeName */ init: function (renderer, nodeName) { var wrapper = this, markup = ['<', nodeName, ' filled="f" stroked="f"'], style = ['position: ', ABSOLUTE, ';'], isDiv = nodeName === DIV; // divs and shapes need size if (nodeName === 'shape' || isDiv) { style.push('left:0;top:0;width:1px;height:1px;'); } style.push('visibility: ', isDiv ? HIDDEN : VISIBLE); markup.push(' style="', style.join(''), '"/>'); // create element with default attributes and style if (nodeName) { markup = isDiv || nodeName === 'span' || nodeName === 'img' ? markup.join('') : renderer.prepVML(markup); wrapper.element = createElement(markup); } wrapper.renderer = renderer; }, /** * Add the node to the given parent * @param {Object} parent */ add: function (parent) { var wrapper = this, renderer = wrapper.renderer, element = wrapper.element, box = renderer.box, inverted = parent && parent.inverted, // get the parent node parentNode = parent ? parent.element || parent : box; // if the parent group is inverted, apply inversion on all children if (inverted) { // only on groups renderer.invertChild(element, parentNode); } // append it parentNode.appendChild(element); // align text after adding to be able to read offset wrapper.added = true; if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) { wrapper.updateTransform(); } // fire an event for internal hooks if (wrapper.onAdd) { wrapper.onAdd(); } return wrapper; }, /** * VML always uses htmlUpdateTransform */ updateTransform: SVGElement.prototype.htmlUpdateTransform, /** * Set the rotation of a span with oldIE's filter */ setSpanRotation: function () { // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+ // has support for CSS3 transform. The getBBox method also needs to be updated // to compensate for the rotation, like it currently does for SVG. // Test case: http://jsfiddle.net/highcharts/Ybt44/ var rotation = this.rotation, costheta = mathCos(rotation * deg2rad), sintheta = mathSin(rotation * deg2rad); css(this.element, { filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta, ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta, ', sizingMethod=\'auto expand\')'].join('') : NONE }); }, /** * Get the positioning correction for the span after rotating. */ getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) { var costheta = rotation ? mathCos(rotation * deg2rad) : 1, sintheta = rotation ? mathSin(rotation * deg2rad) : 0, height = pick(this.elemHeight, this.element.offsetHeight), quad, nonLeft = align && align !== 'left'; // correct x and y this.xCorr = costheta < 0 && -width; this.yCorr = sintheta < 0 && -height; // correct for baseline and corners spilling out after rotation quad = costheta * sintheta < 0; this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection); this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1); // correct for the length/height of the text if (nonLeft) { this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1); if (rotation) { this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1); } css(this.element, { textAlign: align }); } }, /** * Converts a subset of an SVG path definition to its VML counterpart. Takes an array * as the parameter and returns a string. */ pathToVML: function (value) { // convert paths var i = value.length, path = []; while (i--) { // Multiply by 10 to allow subpixel precision. // Substracting half a pixel seems to make the coordinates // align with SVG, but this hasn't been tested thoroughly if (isNumber(value[i])) { path[i] = mathRound(value[i] * 10) - 5; } else if (value[i] === 'Z') { // close the path path[i] = 'x'; } else { path[i] = value[i]; // When the start X and end X coordinates of an arc are too close, // they are rounded to the same value above. In this case, substract or // add 1 from the end X and Y positions. #186, #760, #1371, #1410. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) { // Start and end X if (path[i + 5] === path[i + 7]) { path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1; } // Start and end Y if (path[i + 6] === path[i + 8]) { path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1; } } } } // Loop up again to handle path shortcuts (#2132) /*while (i++ < path.length) { if (path[i] === 'H') { // horizontal line to path[i] = 'L'; path.splice(i + 2, 0, path[i - 1]); } else if (path[i] === 'V') { // vertical line to path[i] = 'L'; path.splice(i + 1, 0, path[i - 2]); } }*/ return path.join(' ') || 'x'; }, /** * Set the element's clipping to a predefined rectangle * * @param {String} id The id of the clip rectangle */ clip: function (clipRect) { var wrapper = this, clipMembers, cssRet; if (clipRect) { clipMembers = clipRect.members; erase(clipMembers, wrapper); // Ensure unique list of elements (#1258) clipMembers.push(wrapper); wrapper.destroyClip = function () { erase(clipMembers, wrapper); }; cssRet = clipRect.getCSS(wrapper); } else { if (wrapper.destroyClip) { wrapper.destroyClip(); } cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214 } return wrapper.css(cssRet); }, /** * Set styles for the element * @param {Object} styles */ css: SVGElement.prototype.htmlCss, /** * Removes a child either by removeChild or move to garbageBin. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not. */ safeRemoveChild: function (element) { // discardElement will detach the node from its parent before attaching it // to the garbage bin. Therefore it is important that the node is attached and have parent. if (element.parentNode) { discardElement(element); } }, /** * Extend element.destroy by removing it from the clip members array */ destroy: function () { if (this.destroyClip) { this.destroyClip(); } return SVGElement.prototype.destroy.apply(this); }, /** * Add an event listener. VML override for normalizing event parameters. * @param {String} eventType * @param {Function} handler */ on: function (eventType, handler) { // simplest possible event model for internal use this.element['on' + eventType] = function () { var evt = win.event; evt.target = evt.srcElement; handler(evt); }; return this; }, /** * In stacked columns, cut off the shadows so that they don't overlap */ cutOffPath: function (path, length) { var len; path = path.split(/[ ,]/); len = path.length; if (len === 9 || len === 11) { path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length; } return path.join(' '); }, /** * Apply a drop shadow by copying elements and giving them different strokes * @param {Boolean|Object} shadowOptions */ shadow: function (shadowOptions, group, cutOff) { var shadows = [], i, element = this.element, renderer = this.renderer, shadow, elemStyle = element.style, markup, path = element.path, strokeWidth, modifiedPath, shadowWidth, shadowElementOpacity; // some times empty paths are not strings if (path && typeof path.value !== 'string') { path = 'x'; } modifiedPath = path; if (shadowOptions) { shadowWidth = pick(shadowOptions.width, 3); shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth; for (i = 1; i <= 3; i++) { strokeWidth = (shadowWidth * 2) + 1 - (2 * i); // Cut off shadows for stacked column items if (cutOff) { modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5); } markup = ['<shape isShadow="true" strokeweight="', strokeWidth, '" filled="false" path="', modifiedPath, '" coordsize="10 10" style="', element.style.cssText, '" />']; shadow = createElement(renderer.prepVML(markup), null, { left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1), top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1) } ); if (cutOff) { shadow.cutOff = strokeWidth + 1; } // apply the opacity markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>']; createElement(renderer.prepVML(markup), null, null, shadow); // insert it if (group) { group.element.appendChild(shadow); } else { element.parentNode.insertBefore(shadow, element); } // record it shadows.push(shadow); } this.shadows = shadows; } return this; }, updateShadows: noop, // Used in SVG only setAttr: function (key, value) { if (docMode8) { // IE8 setAttribute bug this.element[key] = value; } else { this.element.setAttribute(key, value); } }, classSetter: function (value) { // IE8 Standards mode has problems retrieving the className unless set like this this.element.className = value; }, dashstyleSetter: function (value, key, element) { var strokeElem = element.getElementsByTagName('stroke')[0] || createElement(this.renderer.prepVML(['<stroke/>']), null, null, element); strokeElem[key] = value || 'solid'; this[key] = value; /* because changing stroke-width will change the dash length and cause an epileptic effect */ }, dSetter: function (value, key, element) { var i, shadows = this.shadows; value = value || []; this.d = value.join && value.join(' '); // used in getter for animation element.path = value = this.pathToVML(value); // update shadows if (shadows) { i = shadows.length; while (i--) { shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value; } } this.setAttr(key, value); }, fillSetter: function (value, key, element) { var nodeName = element.nodeName; if (nodeName === 'SPAN') { // text color element.style.color = value; } else if (nodeName !== 'IMG') { // #1336 element.filled = value !== NONE; this.setAttr('fillcolor', this.renderer.color(value, element, key, this)); } }, opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts rotationSetter: function (value, key, element) { var style = element.style; this[key] = style[key] = value; // style is for #1873 // Correction for the 1x1 size of the shape container. Used in gauge needles. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX; style.top = mathRound(mathCos(value * deg2rad)) + PX; }, strokeSetter: function (value, key, element) { this.setAttr('strokecolor', this.renderer.color(value, element, key)); }, 'stroke-widthSetter': function (value, key, element) { element.stroked = !!value; // VML "stroked" attribute this[key] = value; // used in getter, issue #113 if (isNumber(value)) { value += PX; } this.setAttr('strokeweight', value); }, titleSetter: function (value, key) { this.setAttr(key, value); }, visibilitySetter: function (value, key, element) { // Handle inherited visibility if (value === 'inherit') { value = VISIBLE; } // Let the shadow follow the main element if (this.shadows) { each(this.shadows, function (shadow) { shadow.style[key] = value; }); } // Instead of toggling the visibility CSS property, move the div out of the viewport. // This works around #61 and #586 if (element.nodeName === 'DIV') { value = value === HIDDEN ? '-999em' : 0; // In order to redraw, IE7 needs the div to be visible when tucked away // outside the viewport. So the visibility is actually opposite of // the expected value. This applies to the tooltip only. if (!docMode8) { element.style[key] = value ? VISIBLE : HIDDEN; } key = 'top'; } element.style[key] = value; }, xSetter: function (value, key, element) { this[key] = value; // used in getter if (key === 'x') { key = 'left'; } else if (key === 'y') { key = 'top'; }/* else { value = mathMax(0, value); // don't set width or height below zero (#311) }*/ // clipping rectangle special if (this.updateClipping) { this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y' this.updateClipping(); } else { // normal element.style[key] = value; } }, zIndexSetter: function (value, key, element) { element.style[key] = value; } }; Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement); // Some shared setters VMLElement.prototype.ySetter = VMLElement.prototype.widthSetter = VMLElement.prototype.heightSetter = VMLElement.prototype.xSetter; /** * The VML renderer */ var VMLRendererExtension = { // inherit SVGRenderer Element: VMLElement, isIE8: userAgent.indexOf('MSIE 8.0') > -1, /** * Initialize the VMLRenderer * @param {Object} container * @param {Number} width * @param {Number} height */ init: function (container, width, height, style) { var renderer = this, boxWrapper, box, css; renderer.alignedObjects = []; boxWrapper = renderer.createElement(DIV) .css(extend(this.getStyle(style), { position: RELATIVE})); box = boxWrapper.element; container.appendChild(boxWrapper.element); // generate the containing box renderer.isVML = true; renderer.box = box; renderer.boxWrapper = boxWrapper; renderer.cache = {}; renderer.setSize(width, height, false); // The only way to make IE6 and IE7 print is to use a global namespace. However, // with IE8 the only way to make the dynamic shapes visible in screen and print mode // seems to be to add the xmlns attribute and the behaviour style inline. if (!doc.namespaces.hcv) { doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml'); // Setup default CSS (#2153, #2368, #2384) css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' + '{ behavior:url(#default#VML); display: inline-block; } '; try { doc.createStyleSheet().cssText = css; } catch (e) { doc.styleSheets[0].cssText += css; } } }, /** * Detect whether the renderer is hidden. This happens when one of the parent elements * has display: none */ isHidden: function () { return !this.box.offsetWidth; }, /** * Define a clipping rectangle. In VML it is accomplished by storing the values * for setting the CSS style to all associated members. * * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height */ clipRect: function (x, y, width, height) { // create a dummy element var clipRect = this.createElement(), isObj = isObject(x); // mimic a rectangle with its style object for automatic updating in attr return extend(clipRect, { members: [], count: 0, left: (isObj ? x.x : x) + 1, top: (isObj ? x.y : y) + 1, width: (isObj ? x.width : width) - 1, height: (isObj ? x.height : height) - 1, getCSS: function (wrapper) { var element = wrapper.element, nodeName = element.nodeName, isShape = nodeName === 'shape', inverted = wrapper.inverted, rect = this, top = rect.top - (isShape ? element.offsetTop : 0), left = rect.left, right = left + rect.width, bottom = top + rect.height, ret = { clip: 'rect(' + mathRound(inverted ? left : top) + 'px,' + mathRound(inverted ? bottom : right) + 'px,' + mathRound(inverted ? right : bottom) + 'px,' + mathRound(inverted ? top : left) + 'px)' }; // issue 74 workaround if (!inverted && docMode8 && nodeName === 'DIV') { extend(ret, { width: right + PX, height: bottom + PX }); } return ret; }, // used in attr and animation to update the clipping of all members updateClipping: function () { each(clipRect.members, function (member) { if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do. member.css(clipRect.getCSS(member)); } }); } }); }, /** * Take a color and return it if it's a string, make it a gradient if it's a * gradient configuration object, and apply opacity. * * @param {Object} color The color or config object */ color: function (color, elem, prop, wrapper) { var renderer = this, colorObject, regexRgba = /^rgba/, markup, fillType, ret = NONE; // Check for linear or radial gradient if (color && color.linearGradient) { fillType = 'gradient'; } else if (color && color.radialGradient) { fillType = 'pattern'; } if (fillType) { var stopColor, stopOpacity, gradient = color.linearGradient || color.radialGradient, x1, y1, x2, y2, opacity1, opacity2, color1, color2, fillAttr = '', stops = color.stops, firstStop, lastStop, colors = [], addFillNode = function () { // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1, '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />']; createElement(renderer.prepVML(markup), null, null, elem); }; // Extend from 0 to 1 firstStop = stops[0]; lastStop = stops[stops.length - 1]; if (firstStop[0] > 0) { stops.unshift([ 0, firstStop[1] ]); } if (lastStop[0] < 1) { stops.push([ 1, lastStop[1] ]); } // Compute the stops each(stops, function (stop, i) { if (regexRgba.test(stop[1])) { colorObject = Color(stop[1]); stopColor = colorObject.get('rgb'); stopOpacity = colorObject.get('a'); } else { stopColor = stop[1]; stopOpacity = 1; } // Build the color attribute colors.push((stop[0] * 100) + '% ' + stopColor); // Only start and end opacities are allowed, so we use the first and the last if (!i) { opacity1 = stopOpacity; color2 = stopColor; } else { opacity2 = stopOpacity; color1 = stopColor; } }); // Apply the gradient to fills only. if (prop === 'fill') { // Handle linear gradient angle if (fillType === 'gradient') { x1 = gradient.x1 || gradient[0] || 0; y1 = gradient.y1 || gradient[1] || 0; x2 = gradient.x2 || gradient[2] || 0; y2 = gradient.y2 || gradient[3] || 0; fillAttr = 'angle="' + (90 - math.atan( (y2 - y1) / // y vector (x2 - x1) // x vector ) * 180 / mathPI) + '"'; addFillNode(); // Radial (circular) gradient } else { var r = gradient.r, sizex = r * 2, sizey = r * 2, cx = gradient.cx, cy = gradient.cy, radialReference = elem.radialReference, bBox, applyRadialGradient = function () { if (radialReference) { bBox = wrapper.getBBox(); cx += (radialReference[0] - bBox.x) / bBox.width - 0.5; cy += (radialReference[1] - bBox.y) / bBox.height - 0.5; sizex *= radialReference[2] / bBox.width; sizey *= radialReference[2] / bBox.height; } fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' + 'size="' + sizex + ',' + sizey + '" ' + 'origin="0.5,0.5" ' + 'position="' + cx + ',' + cy + '" ' + 'color2="' + color2 + '" '; addFillNode(); }; // Apply radial gradient if (wrapper.added) { applyRadialGradient(); } else { // We need to know the bounding box to get the size and position right wrapper.onAdd = applyRadialGradient; } // The fill element's color attribute is broken in IE8 standards mode, so we // need to set the parent shape's fillcolor attribute instead. ret = color1; } // Gradients are not supported for VML stroke, return the first color. #722. } else { ret = stopColor; } // if the color is an rgba color, split it and add a fill node // to hold the opacity component } else if (regexRgba.test(color) && elem.tagName !== 'IMG') { colorObject = Color(color); 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; }, /** * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems */ createElement: function (nodeName) { return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName); }, /** * In the VML renderer, each child of an inverted div (group) is inverted * @param {Object} element * @param {Object} parentNode */ invertChild: function (element, parentNode) { var ren = this, parentStyle = parentNode.style, imgStyle = element.tagName === 'IMG' && element.style; // #1111 css(element, { flip: 'x', left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1), top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1), rotation: -90 }); // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806. each(element.childNodes, function (child) { ren.invertChild(child, element); }); }, /** * Symbol definitions that override the parent SVG renderer's symbols * */ symbols: { // VML specific arc function arc: function (x, y, w, h, options) { var start = options.start, end = options.end, radius = options.r || w || h, innerRadius = options.innerR, cosStart = mathCos(start), sinStart = mathSin(start), cosEnd = mathCos(end), sinEnd = mathSin(end), ret; if (end - start === 0) { // no angle, don't show it. return ['x']; } ret = [ 'wa', // clockwise arc to x - radius, // left y - radius, // top x + radius, // right y + radius, // bottom x + radius * cosStart, // start x y + radius * sinStart, // start y x + radius * cosEnd, // end x y + radius * sinEnd // end y ]; if (options.open && !innerRadius) { ret.push( 'e', M, x,// - innerRadius, y// - innerRadius ); } ret.push( 'at', // anti clockwise arc to x - innerRadius, // left y - innerRadius, // top x + innerRadius, // right y + innerRadius, // bottom x + innerRadius * cosEnd, // start x y + innerRadius * sinEnd, // start y x + innerRadius * cosStart, // end x y + innerRadius * sinStart, // end y 'x', // finish path 'e' // close ); ret.isArc = true; return ret; }, // Add circle symbol path. This performs significantly faster than v:oval. circle: function (x, y, w, h, wrapper) { if (wrapper) { w = h = 2 * wrapper.r; } // Center correction, #1682 if (wrapper && wrapper.isCircle) { x -= w / 2; y -= h / 2; } // Return the path return [ 'wa', // clockwisearcto x, // left y, // top x + w, // right y + h, // bottom x + w, // start x y + h / 2, // start y x + w, // end x y + h / 2, // end y //'x', // finish path 'e' // close ]; }, /** * Add rectangle symbol path which eases rotation and omits arcsize problems * compared to the built-in VML roundrect shape. When borders are not rounded, * use the simpler square path, else use the callout path without the arrow. */ rect: function (x, y, w, h, options) { return SVGRenderer.prototype.symbols[ !defined(options) || !options.r ? 'square' : 'callout' ].call(0, x, y, w, h, options); } } }; Highcharts.VMLRenderer = VMLRenderer = function () { this.init.apply(this, arguments); }; VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension); // general renderer Renderer = VMLRenderer; } // This method is used with exporting in old IE, when emulating SVG (see #2314) SVGRenderer.prototype.measureSpanWidth = function (text, styles) { var measuringSpan = doc.createElement('span'), offsetWidth, textNode = doc.createTextNode(text); measuringSpan.appendChild(textNode); css(measuringSpan, styles); this.box.appendChild(measuringSpan); offsetWidth = measuringSpan.offsetWidth; discardElement(measuringSpan); // #2463 return offsetWidth; }; /* **************************************************************************** * * * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE * * * *****************************************************************************/ /* **************************************************************************** * * * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT * * TARGETING THAT SYSTEM. * * * *****************************************************************************/ var CanVGRenderer, CanVGController; if (useCanVG) { /** * The CanVGRenderer is empty from start to keep the source footprint small. * When requested, the CanVGController downloads the rest of the source packaged * together with the canvg library. */ Highcharts.CanVGRenderer = CanVGRenderer = function () { // Override the global SVG namespace to fake SVG/HTML that accepts CSS SVG_NS = 'http://www.w3.org/1999/xhtml'; }; /** * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but * the implementation from SvgRenderer will not be merged in until first render. */ CanVGRenderer.prototype.symbols = {}; /** * Handles on demand download of canvg rendering support. */ CanVGController = (function () { // List of renderering calls var deferredRenderCalls = []; /** * When downloaded, we are ready to draw deferred charts. */ function drawDeferred() { var callLength = deferredRenderCalls.length, callIndex; // Draw all pending render calls for (callIndex = 0; callIndex < callLength; callIndex++) { deferredRenderCalls[callIndex](); } // Clear the list deferredRenderCalls = []; } return { push: function (func, scriptLocation) { // Only get the script once if (deferredRenderCalls.length === 0) { getScript(scriptLocation, drawDeferred); } // Register render call deferredRenderCalls.push(func); } }; }()); Renderer = CanVGRenderer; } // end CanVGRenderer /* **************************************************************************** * * * END OF ANDROID < 3 SPECIFIC CODE * * * *****************************************************************************/ /** * The Tick class */ function Tick(axis, pos, type, noLabel) { this.axis = axis; this.pos = pos; this.type = type || ''; this.isNew = true; if (!type && !noLabel) { this.addLabel(); } } Tick.prototype = { /** * Write the tick label */ addLabel: function () { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, categories = axis.categories, names = axis.names, pos = tick.pos, labelOptions = options.labels, str, tickPositions = axis.tickPositions, isFirst = pos === tickPositions[0], isLast = pos === tickPositions[tickPositions.length - 1], value = categories ? pick(categories[pos], names[pos], pos) : pos, label = tick.label, tickPositionInfo = tickPositions.info, dateTimeLabelFormat; // Set the datetime label format. If a higher rank is set for this position, use that. If not, // use the general format. if (axis.isDatetimeAxis && tickPositionInfo) { dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName]; } // set properties for access in render method tick.isFirst = isFirst; tick.isLast = isLast; // get the string str = axis.labelFormatter.call({ axis: axis, chart: chart, isFirst: isFirst, isLast: isLast, dateTimeLabelFormat: dateTimeLabelFormat, value: axis.isLog ? correctFloat(lin2log(value)) : value }); // prepare CSS //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX }; // first call if (!defined(label)) { tick.label = label = defined(str) && labelOptions.enabled ? chart.renderer.text( str, 0, 0, labelOptions.useHTML ) //.attr(attr) // without position absolute, IE export sometimes is wrong .css(merge(labelOptions.style)) .add(axis.labelGroup) : null; tick.labelLength = label && label.getBBox().width; // Un-rotated length tick.rotation = 0; // Base value to detect change for new calls to getBBox // update } else if (label) { label.attr({ text: str }); } }, /** * Get the offset height or width of the label */ getLabelSize: function () { return this.label ? this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] : 0; }, /** * Handle the label overflow by adjusting the labels to the left and right edge, or * hide them if they collide into the neighbour label. */ handleOverflow: function (xy) { var axis = this.axis, pxPos = xy.x, chartWidth = axis.chart.chartWidth, spacing = axis.chart.spacing, leftBound = pick(axis.labelLeft, mathMin(axis.pos, spacing[3])), rightBound = pick(axis.labelRight, mathMax(axis.pos + axis.len, chartWidth - spacing[1])), label = this.label, rotation = this.rotation, factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign], labelWidth = label.getBBox().width, slotWidth = axis.slotWidth, xCorrection = factor, goRight = 1, leftPos, rightPos, textWidth, css = {}; // Check if the label overshoots the chart spacing box. If it does, move it. // If it now overshoots the slotWidth, add ellipsis. if (!rotation) { leftPos = pxPos - factor * labelWidth; rightPos = pxPos + (1 - factor) * labelWidth; if (leftPos < leftBound) { slotWidth = xy.x + slotWidth * (1 - factor) - leftBound; } else if (rightPos > rightBound) { slotWidth = rightBound - xy.x + slotWidth * factor; goRight = -1; } slotWidth = mathMin(axis.slotWidth, slotWidth); // #4177 if (slotWidth < axis.slotWidth && axis.labelAlign === 'center') { xy.x += goRight * (axis.slotWidth - slotWidth - xCorrection * (axis.slotWidth - mathMin(labelWidth, slotWidth))); } // If the label width exceeds the available space, set a text width to be // picked up below. Also, if a width has been set before, we need to set a new // one because the reported labelWidth will be limited by the box (#3938). if (labelWidth > slotWidth || (axis.autoRotation && label.styles.width)) { textWidth = slotWidth; } // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) { textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound); } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) { textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad)); } if (textWidth) { css.width = textWidth; if (!axis.options.labels.style.textOverflow) { css.textOverflow = 'ellipsis'; } label.css(css); } }, /** * Get the x and y position for ticks and labels */ getPosition: function (horiz, pos, tickmarkOffset, old) { var axis = this.axis, chart = axis.chart, cHeight = (old && chart.oldChartHeight) || chart.chartHeight; return { x: horiz ? axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB : axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0), y: horiz ? cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) : cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB }; }, /** * Get the x, y position of the tick label */ getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) { var axis = this.axis, transA = axis.transA, reversed = axis.reversed, staggerLines = axis.staggerLines, rotCorr = axis.tickRotCorr || { x: 0, y: 0 }, yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))), line; x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ? tickmarkOffset * transA * (reversed ? -1 : 1) : 0); y = y + yOffset - (tickmarkOffset && !horiz ? tickmarkOffset * transA * (reversed ? 1 : -1) : 0); // Correct for staggered labels if (staggerLines) { line = (index / (step || 1) % staggerLines); y += line * (axis.labelOffset / staggerLines); } return { x: x, y: mathRound(y) }; }, /** * Extendible method to return the path of the marker */ getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) { return renderer.crispLine([ M, x, y, L, x + (horiz ? 0 : -tickLength), y + (horiz ? tickLength : 0) ], tickWidth); }, /** * Put everything in place * * @param index {Number} * @param old {Boolean} Use old coordinates to prepare an animation into new position */ render: function (index, old, opacity) { var tick = this, axis = tick.axis, options = axis.options, chart = axis.chart, renderer = chart.renderer, horiz = axis.horiz, type = tick.type, label = tick.label, pos = tick.pos, labelOptions = options.labels, gridLine = tick.gridLine, gridPrefix = type ? type + 'Grid' : 'grid', tickPrefix = type ? type + 'Tick' : 'tick', gridLineWidth = options[gridPrefix + 'LineWidth'], gridLineColor = options[gridPrefix + 'LineColor'], dashStyle = options[gridPrefix + 'LineDashStyle'], tickLength = options[tickPrefix + 'Length'], tickWidth = pick(options[tickPrefix + 'Width'], !type && axis.isXAxis ? 1 : 0), // X axis defaults to 1 tickColor = options[tickPrefix + 'Color'], tickPosition = options[tickPrefix + 'Position'], gridLinePath, mark = tick.mark, markPath, step = /*axis.labelStep || */labelOptions.step, attribs, show = true, tickmarkOffset = axis.tickmarkOffset, xy = tick.getPosition(horiz, pos, tickmarkOffset, old), x = xy.x, y = xy.y, reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687 opacity = pick(opacity, 1); this.isActive = true; // create the grid line if (gridLineWidth) { gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true); if (gridLine === UNDEFINED) { attribs = { stroke: gridLineColor, 'stroke-width': gridLineWidth }; if (dashStyle) { attribs.dashstyle = dashStyle; } if (!type) { attribs.zIndex = 1; } if (old) { attribs.opacity = 0; } tick.gridLine = gridLine = gridLineWidth ? renderer.path(gridLinePath) .attr(attribs).add(axis.gridGroup) : null; } // If the parameter 'old' is set, the current call will be followed // by another call, therefore do not do any animations this time if (!old && gridLine && gridLinePath) { gridLine[tick.isNew ? 'attr' : 'animate']({ d: gridLinePath, opacity: opacity }); } } // create the tick mark if (tickWidth && tickLength) { // negate the length if (tickPosition === 'inside') { tickLength = -tickLength; } if (axis.opposite) { tickLength = -tickLength; } markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer); if (mark) { // updating mark.animate({ d: markPath, opacity: opacity }); } else { // first time tick.mark = renderer.path( markPath ).attr({ stroke: tickColor, 'stroke-width': tickWidth, opacity: opacity }).add(axis.axisGroup); } } // the label is created on init - now move it into place if (label && !isNaN(x)) { label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step); // Apply show first and show last. If the tick is both first and last, it is // a single centered tick, in which case we show the label anyway (#2100). if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) || (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) { show = false; // Handle label overflow and show or hide accordingly } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) { tick.handleOverflow(xy); } // apply step if (step && index % step) { // show those indices dividable by step show = false; } // Set the new position, and show or hide if (show && !isNaN(xy.y)) { xy.opacity = opacity; label[tick.isNew ? 'attr' : 'animate'](xy); tick.isNew = false; } else { label.attr('y', -9999); // #1338 } } }, /** * Destructor for the tick prototype */ destroy: function () { destroyObjectProperties(this, this.axis); } }; /** * The object wrapper for plot lines and plot bands * @param {Object} options */ Highcharts.PlotLineOrBand = function (axis, options) { this.axis = axis; if (options) { this.options = options; this.id = options.id; } }; Highcharts.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, 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 path = axis.getPlotBandPath(from, to, options); if (color) { 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(); }; if (label) { plotLine.label = label = label.destroy(); } } } 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) { attribs = { align: optionsLabel.textAlign || optionsLabel.align, rotation: optionsLabel.rotation }; if (defined(zIndex)) { attribs.zIndex = zIndex; } plotLine.label = label = renderer.text( optionsLabel.text, 0, 0, optionsLabel.useHTML ) .attr(attribs) .css(optionsLabel.style) .add(); } // get the bounding box and align the label // #3000 changed to better handle choice between plotband or plotline xs = [path[1], path[4], (isBand ? path[6] : path[1])]; ys = [path[2], path[5], (isBand ? 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); } }; /** * Object with members for extending the Axis prototype */ AxisPlotLineOrBandExtension = { /** * Create the path for a plot band */ getPlotBandPath: function (from, to) { var toPath = this.getPlotLinePath(to, null, null, true), path = this.getPlotLinePath(from, null, null, true); if (path && toPath && path.toString() !== toPath.toString()) { // #3836 path.push( toPath[4], toPath[5], toPath[1], toPath[2] ); } else { // outside the axis area path = null; } return path; }, addPlotBand: function (options) { return this.addPlotBandOrLine(options, 'plotBands'); }, addPlotLine: function (options) { return 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 Highcharts.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; }, /** * 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]); } } }); } }; /** * Create a new axis object * @param {Object} chart * @param {Object} options */ var Axis = Highcharts.Axis = function () { this.init.apply(this, arguments); }; Axis.prototype = { /** * Default options for the X axis - the Y axis has extended defaults */ defaultOptions: { // allowDecimals: null, // alternateGridColor: null, // categories: [], dateTimeLabelFormats: { millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y' }, endOnTick: false, gridLineColor: '#D8D8D8', // gridLineDashStyle: 'solid', // gridLineWidth: 0, // reversed: false, labels: { enabled: true, // rotation: 0, // align: 'center', // step: null, style: { color: '#606060', cursor: 'default', fontSize: '11px' }, x: 0, y: 15 /*formatter: function () { return this.value; },*/ }, lineColor: '#C0D0E0', lineWidth: 1, //linkedTo: null, //max: undefined, //min: undefined, minPadding: 0.01, maxPadding: 0.01, //minRange: null, minorGridLineColor: '#E0E0E0', // minorGridLineDashStyle: null, minorGridLineWidth: 1, minorTickColor: '#A0A0A0', //minorTickInterval: null, minorTickLength: 2, minorTickPosition: 'outside', // inside or outside //minorTickWidth: 0, //opposite: false, //offset: 0, //plotBands: [{ // events: {}, // zIndex: 1, // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //plotLines: [{ // events: {} // dashStyle: {} // zIndex: // labels: { align, x, verticalAlign, y, style, rotation, textAlign } //}], //reversed: false, // showFirstLabel: true, // showLastLabel: true, startOfWeek: 1, startOnTick: false, tickColor: '#C0D0E0', //tickInterval: null, tickLength: 10, tickmarkPlacement: 'between', // on or between tickPixelInterval: 100, tickPosition: 'outside', //tickWidth: 1, title: { //text: null, align: 'middle', // low, middle or high //margin: 0 for horizontal, 10 for vertical axes, //rotation: 0, //side: 'outside', style: { color: '#707070' } //x: 0, //y: 0 }, type: 'linear' // linear, logarithmic or datetime //visible: true }, /** * This options set extends the defaultOptions for Y axes */ defaultYAxisOptions: { endOnTick: true, gridLineWidth: 1, tickPixelInterval: 72, showLastLabel: true, labels: { x: -8, y: 3 }, lineWidth: 0, maxPadding: 0.05, minPadding: 0.05, startOnTick: true, //tickWidth: 0, title: { rotation: 270, text: 'Values' }, stackLabels: { enabled: false, //align: dynamic, //y: dynamic, //x: dynamic, //verticalAlign: dynamic, //textAlign: dynamic, //rotation: 0, formatter: function () { return Highcharts.numberFormat(this.total, -1); }, style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' }) } }, /** * These options extend the defaultOptions for left axes */ defaultLeftAxisOptions: { labels: { x: -15, y: null }, title: { rotation: 270 } }, /** * These options extend the defaultOptions for right axes */ defaultRightAxisOptions: { labels: { x: 15, y: null }, title: { rotation: 90 } }, /** * These options extend the defaultOptions for bottom axes */ defaultBottomAxisOptions: { labels: { autoRotation: [-45], x: 0, y: null // based on font size // overflow: undefined, // staggerLines: null }, title: { rotation: 0 } }, /** * These options extend the defaultOptions for top axes */ defaultTopAxisOptions: { labels: { autoRotation: [-45], x: 0, y: -15 // overflow: undefined // staggerLines: null }, title: { rotation: 0 } }, /** * Initialize the axis */ init: function (chart, userOptions) { var isXAxis = userOptions.isX, axis = this; axis.chart = chart; // Flag, is the axis horizontal axis.horiz = chart.inverted ? !isXAxis : isXAxis; // Flag, isXAxis axis.isXAxis = isXAxis; axis.coll = isXAxis ? 'xAxis' : 'yAxis'; axis.opposite = userOptions.opposite; // needed in setOptions axis.side = userOptions.side || (axis.horiz ? (axis.opposite ? 0 : 2) : // top : bottom (axis.opposite ? 1 : 3)); // right : left axis.setOptions(userOptions); var options = this.options, type = options.type, isDatetimeAxis = type === 'datetime'; axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format // Flag, stagger lines or not axis.userOptions = userOptions; //axis.axisTitleMargin = UNDEFINED,// = options.title.margin, axis.minPixelPadding = 0; axis.reversed = options.reversed; axis.visible = options.visible !== false; axis.zoomEnabled = options.zoomEnabled !== false; // Initial categories axis.categories = options.categories || type === 'category'; axis.names = axis.names || []; // Preserve on update (#3830) // Elements //axis.axisGroup = UNDEFINED; //axis.gridGroup = UNDEFINED; //axis.axisTitle = UNDEFINED; //axis.axisLine = UNDEFINED; // Shorthand types axis.isLog = type === 'logarithmic'; axis.isDatetimeAxis = isDatetimeAxis; // Flag, if axis is linked to another axis axis.isLinked = defined(options.linkedTo); // Linked axis. //axis.linkedParent = UNDEFINED; // Tick positions //axis.tickPositions = UNDEFINED; // array containing predefined positions // Tick intervals //axis.tickInterval = UNDEFINED; //axis.minorTickInterval = UNDEFINED; // Major ticks axis.ticks = {}; axis.labelEdge = []; // Minor ticks axis.minorTicks = {}; // List of plotLines/Bands axis.plotLinesAndBands = []; // Alternate bands axis.alternateBands = {}; // Axis metrics //axis.left = UNDEFINED; //axis.top = UNDEFINED; //axis.width = UNDEFINED; //axis.height = UNDEFINED; //axis.bottom = UNDEFINED; //axis.right = UNDEFINED; //axis.transA = UNDEFINED; //axis.transB = UNDEFINED; //axis.oldTransA = UNDEFINED; axis.len = 0; //axis.oldMin = UNDEFINED; //axis.oldMax = UNDEFINED; //axis.oldUserMin = UNDEFINED; //axis.oldUserMax = UNDEFINED; //axis.oldAxisLength = UNDEFINED; axis.minRange = axis.userMinRange = options.minRange || options.maxZoom; axis.range = options.range; axis.offset = options.offset || 0; // Dictionary for stacks axis.stacks = {}; axis.oldStacks = {}; axis.stacksTouched = 0; // Min and max in the data //axis.dataMin = UNDEFINED, //axis.dataMax = UNDEFINED, // The axis range axis.max = null; axis.min = null; // User set min and max //axis.userMin = UNDEFINED, //axis.userMax = UNDEFINED, // Crosshair options axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false); // Run Axis var eventType, events = axis.options.events; // Register if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update() if (isXAxis && !this.isColorAxis) { // #2713 chart.axes.splice(chart.xAxis.length, 0, axis); } else { chart.axes.push(axis); } chart[axis.coll].push(axis); } axis.series = axis.series || []; // populated by Series // inverted charts have reversed xAxes as default if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) { axis.reversed = true; } axis.removePlotBand = axis.removePlotBandOrLine; axis.removePlotLine = axis.removePlotBandOrLine; // register event listeners for (eventType in events) { addEvent(axis, eventType, events[eventType]); } // extend logarithmic axis if (axis.isLog) { axis.val2lin = log2lin; axis.lin2val = lin2log; } }, /** * Merge and set options */ setOptions: function (userOptions) { this.options = merge( this.defaultOptions, this.isXAxis ? {} : this.defaultYAxisOptions, [this.defaultTopAxisOptions, this.defaultRightAxisOptions, this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side], merge( defaultOptions[this.coll], // if set in setOptions (#1053) userOptions ) ); }, /** * The default label formatter. The context is a special config object for the label. */ defaultLabelFormatter: function () { var axis = this.axis, value = this.value, categories = axis.categories, dateTimeLabelFormat = this.dateTimeLabelFormat, numericSymbols = defaultOptions.lang.numericSymbols, i = numericSymbols && numericSymbols.length, multi, ret, formatOption = axis.options.labels.format, // make sure the same symbol is added for all labels on a linear axis numericSymbolDetector = axis.isLog ? value : axis.tickInterval; if (formatOption) { ret = format(formatOption, this); } else if (categories) { ret = value; } else if (dateTimeLabelFormat) { // datetime axis ret = dateFormat(dateTimeLabelFormat, value); } else if (i && numericSymbolDetector >= 1000) { // Decide whether we should add a numeric symbol like k (thousands) or M (millions). // If we are to enable this in tooltip or other places as well, we can move this // logic to the numberFormatter and enable it by a parameter. while (i-- && ret === UNDEFINED) { multi = Math.pow(1000, i + 1); if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null) { ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i]; } } } if (ret === UNDEFINED) { if (mathAbs(value) >= 10000) { // add thousands separators ret = Highcharts.numberFormat(value, -1); } else { // small numbers ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466 } } return ret; }, /** * Get the minimum and maximum for the series of each axis */ getSeriesExtremes: function () { var axis = this, chart = axis.chart; axis.hasVisibleSeries = false; // Reset properties in case we're redrawing (#3353) axis.dataMin = axis.dataMax = axis.threshold = null; axis.softThreshold = !axis.isXAxis; if (axis.buildStacks) { axis.buildStacks(); } // loop through this axis' series each(axis.series, function (series) { if (series.visible || !chart.options.chart.ignoreHiddenSeries) { var seriesOptions = series.options, xData, threshold = seriesOptions.threshold, seriesDataMin, seriesDataMax; axis.hasVisibleSeries = true; // Validate threshold in logarithmic axes if (axis.isLog && threshold <= 0) { threshold = null; } // Get dataMin and dataMax for X axes if (axis.isXAxis) { xData = series.xData; if (xData.length) { axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData)); axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData)); } // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data } else { // Get this particular series extremes series.getExtremes(); seriesDataMax = series.dataMax; seriesDataMin = series.dataMin; // Get the dataMin and dataMax so far. If percentage is used, the min and max are // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series // doesn't have active y data, we continue with nulls if (defined(seriesDataMin) && defined(seriesDataMax)) { axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin); axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax); } // Adjust to threshold if (defined(threshold)) { axis.threshold = threshold; } // If any series has a hard threshold, it takes precedence if (!seriesOptions.softThreshold || axis.isLog) { axis.softThreshold = false; } } } }); }, /** * Translate from axis value to pixel position on the chart, or back * */ translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) { var axis = this.linkedParent || this, // #1417 sign = 1, cvsOffset = 0, localA = old ? axis.oldTransA : axis.transA, localMin = old ? axis.oldMin : axis.min, returnValue, minPixelPadding = axis.minPixelPadding, doPostTranslate = (axis.doPostTranslate || (axis.isLog && handleLog)) && axis.lin2val; if (!localA) { localA = axis.transA; } // In vertical axes, the canvas coordinates start from 0 at the top like in // SVG. if (cvsCoord) { sign *= -1; // canvas coordinates inverts the value cvsOffset = axis.len; } // Handle reversed axis if (axis.reversed) { sign *= -1; cvsOffset -= sign * (axis.sector || axis.len); } // From pixels to value if (backwards) { // reverse translation val = val * sign + cvsOffset; val -= minPixelPadding; returnValue = val / localA + localMin; // from chart pixel to value if (doPostTranslate) { // log and ordinal axes returnValue = axis.lin2val(returnValue); } // From value to pixels } else { if (doPostTranslate) { // log and ordinal axes val = axis.val2lin(val); } if (pointPlacement === 'between') { pointPlacement = 0.5; } returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) + (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0); } return returnValue; }, /** * Utility method to translate an axis value to pixel position. * @param {Number} value A value in terms of axis units * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart * or just the axis/pane itself. */ toPixels: function (value, paneCoordinates) { return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos); }, /* * Utility method to translate a pixel position in to an axis value * @param {Number} pixel The pixel value coordinate * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the * axis/pane itself. */ toValue: function (pixel, paneCoordinates) { return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true); }, /** * Create the path for a plot line that goes from the given value on * this axis, across the plot to the opposite side * @param {Number} value * @param {Number} lineWidth Used for calculation crisp line * @param {Number] old Use old coordinates (for resizing and rescaling) */ getPlotLinePath: function (value, lineWidth, old, force, translatedValue) { var axis = this, chart = axis.chart, axisLeft = axis.left, axisTop = axis.top, x1, y1, x2, y2, cHeight = (old && chart.oldChartHeight) || chart.chartHeight, cWidth = (old && chart.oldChartWidth) || chart.chartWidth, skip, transB = axis.transB, /** * Check if x is between a and b. If not, either move to a/b or skip, * depending on the force parameter. */ between = function (x, a, b) { if (x < a || x > b) { if (force) { x = mathMin(mathMax(a, x), b); } else { skip = true; } } return x; }; translatedValue = pick(translatedValue, axis.translate(value, null, null, old)); x1 = x2 = mathRound(translatedValue + transB); y1 = y2 = mathRound(cHeight - translatedValue - transB); if (isNaN(translatedValue)) { // no min or max skip = true; } else if (axis.horiz) { y1 = axisTop; y2 = cHeight - axis.bottom; x1 = x2 = between(x1, axisLeft, axisLeft + axis.width); } else { x1 = axisLeft; x2 = cWidth - axis.right; y1 = y2 = between(y1, axisTop, axisTop + axis.height); } return skip && !force ? null : chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1); }, /** * Set the tick positions of a linear axis to round values like whole tens or every five. */ getLinearTickPositions: function (tickInterval, min, max) { var pos, lastPos, roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval), roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval), tickPositions = []; // For single points, add a tick regardless of the relative position (#2662) if (min === max && isNumber(min)) { return [min]; } // Populate the intermediate values pos = roundedMin; while (pos <= roundedMax) { // Place the tick on the rounded value tickPositions.push(pos); // Always add the raw tickInterval, not the corrected one. pos = correctFloat(pos + tickInterval); // If the interval is not big enough in the current min - max range to actually increase // the loop variable, we need to break out to prevent endless loop. Issue #619 if (pos === lastPos) { break; } // Record the last value lastPos = pos; } return tickPositions; }, /** * Return the minor tick positions. For logarithmic axes, reuse the same logic * as for major ticks. */ getMinorTickPositions: function () { var axis = this, options = axis.options, tickPositions = axis.tickPositions, minorTickInterval = axis.minorTickInterval, minorTickPositions = [], pos, i, pointRangePadding = axis.pointRangePadding || 0, min = axis.min - pointRangePadding, // #1498 max = axis.max + pointRangePadding, // #1498 range = max - min, len; // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them. if (range && range / minorTickInterval < axis.len / 3) { // #3875 if (axis.isLog) { len = tickPositions.length; for (i = 1; i < len; i++) { minorTickPositions = minorTickPositions.concat( axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true) ); } } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314 minorTickPositions = minorTickPositions.concat( axis.getTimeTicks( axis.normalizeTimeTickInterval(minorTickInterval), min, max, options.startOfWeek ) ); } else { for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) { minorTickPositions.push(pos); } } } if(minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498 } return minorTickPositions; }, /** * Adjust the min and max for the minimum range. Keep in mind that the series data is * not yet processed, so we don't have information on data cropping and grouping, or * updated axis.pointRange or series.pointRange. The data can't be processed until * we have finally established min and max. */ adjustForMinRange: function () { var axis = this, options = axis.options, min = axis.min, max = axis.max, zoomOffset, spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange, closestDataRange, i, distance, xData, loopLength, minArgs, maxArgs, minRange; // Set the automatic minimum range based on the closest point distance if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) { if (defined(options.min) || defined(options.max)) { axis.minRange = null; // don't do this again } else { // Find the closest distance between raw data points, as opposed to // closestPointRange that applies to processed points (cropped and grouped) each(axis.series, function (series) { xData = series.xData; loopLength = series.xIncrement ? 1 : xData.length - 1; for (i = loopLength; i > 0; i--) { distance = xData[i] - xData[i - 1]; if (closestDataRange === UNDEFINED || distance < closestDataRange) { closestDataRange = distance; } } }); axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin); } } // if minRange is exceeded, adjust if (max - min < axis.minRange) { minRange = axis.minRange; zoomOffset = (minRange - max + min) / 2; // if min and max options have been set, don't go beyond it minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)]; if (spaceAvailable) { // if space is available, stay within the data range minArgs[2] = axis.dataMin; } min = arrayMax(minArgs); maxArgs = [min + minRange, pick(options.max, min + minRange)]; if (spaceAvailable) { // if space is availabe, stay within the data range maxArgs[2] = axis.dataMax; } max = arrayMin(maxArgs); // now if the max is adjusted, adjust the min back if (max - min < minRange) { minArgs[0] = max - minRange; minArgs[1] = pick(options.min, max - minRange); min = arrayMax(minArgs); } } // Record modified extremes axis.min = min; axis.max = max; }, /** * Update translation information */ setAxisTranslation: function (saveOld) { var axis = this, range = axis.max - axis.min, pointRange = axis.axisPointRange || 0, closestPointRange, minPointOffset = 0, pointRangePadding = 0, linkedParent = axis.linkedParent, ordinalCorrection, hasCategories = !!axis.categories, transA = axis.transA, isXAxis = axis.isXAxis; // Adjust translation for padding. Y axis with categories need to go through the same (#1784). if (isXAxis || hasCategories || pointRange) { if (linkedParent) { minPointOffset = linkedParent.minPointOffset; pointRangePadding = linkedParent.pointRangePadding; } else { each(axis.series, function (series) { var seriesPointRange = hasCategories ? 1 : (isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806 pointPlacement = series.options.pointPlacement, seriesClosestPointRange = series.closestPointRange; pointRange = mathMax(pointRange, seriesPointRange); if (!axis.single) { // minPointOffset is the value padding to the left of the axis in order to make // room for points with a pointRange, typically columns. When the pointPlacement option // is 'between' or 'on', this padding does not apply. minPointOffset = mathMax( minPointOffset, isString(pointPlacement) ? 0 : seriesPointRange / 2 ); // Determine the total padding needed to the length of the axis to make room for the // pointRange. If the series' pointPlacement is 'on', no padding is added. pointRangePadding = mathMax( pointRangePadding, pointPlacement === 'on' ? 0 : seriesPointRange ); } // 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 if (isXAxis) { axis.closestPointRange = closestPointRange; } } // Secondary values if (saveOld) { axis.oldTransA = transA; } axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1); axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend axis.minPixelPadding = transA * minPointOffset; }, minFromRange: function () { return this.max - this.range; }, /** * Set the tick positions to round values and optionally extend the extremes * to the nearest tick */ setTickInterval: function (secondPass) { var axis = this, chart = axis.chart, options = axis.options, isLog = axis.isLog, isDatetimeAxis = axis.isDatetimeAxis, isXAxis = axis.isXAxis, isLinked = axis.isLinked, maxPadding = options.maxPadding, minPadding = options.minPadding, length, linkedParentExtremes, tickIntervalOption = options.tickInterval, minTickInterval, tickPixelIntervalOption = options.tickPixelInterval, categories = axis.categories, threshold = axis.threshold, softThreshold = axis.softThreshold, thresholdMin, thresholdMax, hardMin, hardMax; if (!isDatetimeAxis && !categories && !isLinked) { this.getTickAmount(); } // Min or max set either by zooming/setExtremes or initial options hardMin = pick(axis.userMin, options.min); hardMax = pick(axis.userMax, options.max); // Linked axis gets the extremes from the parent axis if (isLinked) { axis.linkedParent = chart[axis.coll][options.linkedTo]; linkedParentExtremes = axis.linkedParent.getExtremes(); axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin); axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax); if (options.type !== axis.linkedParent.options.type) { error(11, 1); // Can't link axes of different type } // Initial min and max from the extreme data values } else { // Adjust to hard threshold if (!softThreshold && defined(threshold)) { if (axis.dataMin >= threshold) { thresholdMin = threshold; minPadding = 0; } else if (axis.dataMax <= threshold) { thresholdMax = threshold; maxPadding = 0; } } axis.min = pick(hardMin, thresholdMin, axis.dataMin); axis.max = pick(hardMax, thresholdMax, axis.dataMax); } if (isLog) { if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978 error(10, 1); // Can't plot negative values on log axis } // The correctFloat cures #934, float errors on full tens. But it // was too aggressive for #4360 because of conversion back to lin, // therefore use precision 15. axis.min = correctFloat(log2lin(axis.min), 15); axis.max = correctFloat(log2lin(axis.max), 15); } // handle zoomed range if (axis.range && defined(axis.max)) { axis.userMin = axis.min = hardMin = mathMax(axis.min, axis.minFromRange()); // #618 axis.userMax = hardMax = axis.max; axis.range = null; // don't use it when running setExtremes } // Hook for adjusting this.min and this.max. Used by bubble series. if (axis.beforePadding) { axis.beforePadding(); } // adjust min and max for the minimum range axis.adjustForMinRange(); // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding // into account, we do this after computing tick interval (#1337). if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) { length = axis.max - axis.min; if (length) { if (!defined(hardMin) && minPadding) { axis.min -= length * minPadding; } if (!defined(hardMax) && maxPadding) { axis.max += length * maxPadding; } } } // Stay within floor and ceiling if (isNumber(options.floor)) { axis.min = mathMax(axis.min, options.floor); } if (isNumber(options.ceiling)) { axis.max = mathMin(axis.max, options.ceiling); } // When the threshold is soft, adjust the extreme value only if // the data extreme and the padded extreme land on either side of the threshold. For example, // a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the // default minPadding and startOnTick options. This is prevented by the softThreshold // option. if (softThreshold && defined(axis.dataMin)) { threshold = threshold || 0; if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) { axis.min = threshold; } else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) { axis.max = threshold; } } // get tickInterval if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) { axis.tickInterval = 1; } else if (isLinked && !tickIntervalOption && tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) { axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval; } else { axis.tickInterval = pick( tickIntervalOption, this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined, categories ? // for categoried axis, 1 is default, for linear axis use tickPix 1 : // don't let it be more than the data range (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption) ); } // Now we're finished detecting min and max, crop and group series data. This // is in turn needed in order to find tick positions in ordinal axes. if (isXAxis && !secondPass) { each(axis.series, function (series) { series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax); }); } // set the translation factor used in translate function axis.setAxisTranslation(true); // hook for ordinal axes and radial axes if (axis.beforeSetTickPositions) { axis.beforeSetTickPositions(); } // hook for extensions, used in Highstock ordinal axes if (axis.postProcessTickInterval) { axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval); } // In column-like charts, don't cramp in more ticks than there are points (#1943) 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. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange); if (!tickIntervalOption && axis.tickInterval < minTickInterval) { axis.tickInterval = minTickInterval; } // for linear axes, get magnitude and normalize the interval if (!isDatetimeAxis && !isLog && !tickIntervalOption) { axis.tickInterval = normalizeTickInterval( axis.tickInterval, null, getMagnitude(axis.tickInterval), // If the tick interval is between 0.5 and 5 and the axis max is in the order of // thousands, chances are we are dealing with years. Don't allow decimals. #3363. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)), !!this.tickAmount ); } // Prevent ticks from getting so close that we can't draw the labels if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length axis.tickInterval = axis.unsquish(); } this.setTickPositions(); }, /** * Now we have computed the normalized tickInterval, get the tick positions */ setTickPositions: function () { var options = this.options, tickPositions, tickPositionsOption = options.tickPositions, tickPositioner = options.tickPositioner, startOnTick = options.startOnTick, endOnTick = options.endOnTick, single; // Set the tickmarkOffset this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' && this.tickInterval === 1) ? 0.5 : 0; // #3202 // get minorTickInterval this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ? this.tickInterval / 5 : options.minorTickInterval; // Find the tick positions this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565) if (!tickPositions) { if (this.isDatetimeAxis) { tickPositions = this.getTimeTicks( this.normalizeTimeTickInterval(this.tickInterval, options.units), this.min, this.max, options.startOfWeek, this.ordinalPositions, this.closestPointRange, true ); } else if (this.isLog) { tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max); } else { tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max); } // Too dense ticks, keep only the first and last (#4477) if (tickPositions.length > this.len) { tickPositions = [tickPositions[0], tickPositions.pop()]; } this.tickPositions = tickPositions; // Run the tick positioner callback, that allows modifying auto tick positions. if (tickPositioner) { tickPositioner = tickPositioner.apply(this, [this.min, this.max]); if (tickPositioner) { this.tickPositions = tickPositions = tickPositioner; } } } if (!this.isLinked) { // reset min/max or remove extremes based on start/end on tick this.trimTicks(tickPositions, startOnTick, endOnTick); // When there is only one point, or all points have the same value on this axis, then min // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding // in order to center the point, but leave it with one tick. #1337. if (this.min === this.max && defined(this.min) && !this.tickAmount) { // Substract half a unit (#2619, #2846, #2515, #3390) single = true; this.min -= 0.5; this.max += 0.5; } this.single = single; if (!tickPositionsOption && !tickPositioner) { this.adjustTickAmount(); } } }, /** * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max */ trimTicks: function (tickPositions, startOnTick, endOnTick) { var roundedMin = tickPositions[0], roundedMax = tickPositions[tickPositions.length - 1], minPointOffset = this.minPointOffset || 0; if (startOnTick) { this.min = roundedMin; } else if (this.min - minPointOffset > roundedMin) { tickPositions.shift(); } if (endOnTick) { this.max = roundedMax; } else if (this.max + minPointOffset < roundedMax) { tickPositions.pop(); } // If no tick are left, set one tick in the middle (#3195) if (tickPositions.length === 0 && defined(roundedMin)) { tickPositions.push((roundedMax + roundedMin) / 2); } }, /** * Set the max ticks of either the x and y axis collection */ getTickAmount: function () { var others = {}, // Whether there is another axis to pair with this one hasOther, options = this.options, tickAmount = options.tickAmount, tickPixelInterval = options.tickPixelInterval; if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial && !this.isLog && options.startOnTick && options.endOnTick) { tickAmount = 2; } if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) { // Check if there are multiple axes in the same pane each(this.chart[this.coll], function (axis) { var options = axis.options, horiz = axis.horiz, key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(','); if (axis.series.length) { // #4442 if (others[key]) { hasOther = true; // #4201 } else { others[key] = 1; } } }); if (hasOther) { // Add 1 because 4 tick intervals require 5 ticks (including first and last) tickAmount = mathCeil(this.len / tickPixelInterval) + 1; } } // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This // prevents the axis from adding ticks that are too far away from the data extremes. if (tickAmount < 4) { this.finalTickAmt = tickAmount; tickAmount = 5; } this.tickAmount = tickAmount; }, /** * When using multiple axes, adjust the number of ticks to match the highest * number of ticks in that group */ adjustTickAmount: function () { var tickInterval = this.tickInterval, tickPositions = this.tickPositions, tickAmount = this.tickAmount, finalTickAmt = this.finalTickAmt, currentTickAmount = tickPositions && tickPositions.length, i, len; if (currentTickAmount < tickAmount) { // TODO: Check #3411 while (tickPositions.length < tickAmount) { tickPositions.push(correctFloat( tickPositions[tickPositions.length - 1] + tickInterval )); } this.transA *= (currentTickAmount - 1) / (tickAmount - 1); this.max = tickPositions[tickPositions.length - 1]; // We have too many ticks, run second pass to try to reduce ticks } else if (currentTickAmount > tickAmount) { this.tickInterval *= 2; this.setTickPositions(); } // The finalTickAmt property is set in getTickAmount if (defined(finalTickAmt)) { i = len = tickPositions.length; while (i--) { if ( (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last ) { tickPositions.splice(i, 1); } } this.finalTickAmt = UNDEFINED; } }, /** * Set the scale based on data min and max, user set min and max or options * */ setScale: function () { var axis = this, isDirtyData, isDirtyAxisLength; axis.oldMin = axis.min; axis.oldMax = axis.max; axis.oldAxisLength = axis.len; // set the new axisLength axis.setAxisSize(); //axisLength = horiz ? axisWidth : axisHeight; isDirtyAxisLength = axis.len !== axis.oldAxisLength; // is there new data? each(axis.series, function (series) { if (series.isDirtyData || series.isDirty || series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well isDirtyData = true; } }); // do we really need to go through all this? if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw || axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) { if (axis.resetStacks) { axis.resetStacks(); } axis.forceRedraw = false; // get data extremes if needed axis.getSeriesExtremes(); // get fixed positions based on tickInterval axis.setTickInterval(); // record old values to decide whether a rescale is necessary later on (#540) axis.oldUserMin = axis.userMin; axis.oldUserMax = axis.userMax; // Mark as dirty if it is not already set to dirty and extremes have changed. #595. if (!axis.isDirty) { axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax; } } else if (axis.cleanStacks) { axis.cleanStacks(); } }, /** * Set the extremes and optionally redraw * @param {Number} newMin * @param {Number} newMax * @param {Boolean} redraw * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * @param {Object} eventArguments * */ setExtremes: function (newMin, newMax, redraw, animation, eventArguments) { var axis = this, chart = axis.chart; redraw = pick(redraw, true); // defaults to true each(axis.series, function (serie) { delete serie.kdTree; }); // Extend the arguments with min and max eventArguments = extend(eventArguments, { min: newMin, max: newMax }); // Fire the event fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler axis.userMin = newMin; axis.userMax = newMax; axis.eventArgs = eventArguments; if (redraw) { chart.redraw(animation); } }); }, /** * Overridable method for zooming chart. Pulled out in a separate method to allow overriding * in stock charts. */ zoom: function (newMin, newMax) { var dataMin = this.dataMin, dataMax = this.dataMax, options = this.options, min = mathMin(dataMin, pick(options.min, dataMin)), max = mathMax(dataMax, pick(options.max, dataMax)); // Prevent pinch zooming out of range. Check for defined is for #1946. #1734. if (!this.allowZoomOutside) { if (defined(dataMin) && newMin <= min) { newMin = min; } if (defined(dataMax) && newMax >= max) { newMax = max; } } // In full view, displaying the reset zoom button is not required this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED; // Do it this.setExtremes( newMin, newMax, false, UNDEFINED, { trigger: 'zoom' } ); return true; }, /** * Update the axis metrics */ setAxisSize: function () { var chart = this.chart, options = this.options, offsetLeft = options.offsetLeft || 0, offsetRight = options.offsetRight || 0, horiz = this.horiz, width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight), height = pick(options.height, chart.plotHeight), top = pick(options.top, chart.plotTop), left = pick(options.left, chart.plotLeft + offsetLeft), percentRegex = /%$/; // Check for percentage based input values if (percentRegex.test(height)) { height = parseFloat(height) / 100 * chart.plotHeight; } if (percentRegex.test(top)) { top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop; } // Expose basic values to use in Series object and navigator this.left = left; this.top = top; this.width = width; this.height = height; this.bottom = chart.chartHeight - height - top; this.right = chart.chartWidth - width - left; // Direction agnostic properties this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905 this.pos = horiz ? left : top; // distance from SVG origin }, /** * Get the actual axis extremes */ getExtremes: function () { var axis = this, isLog = axis.isLog; return { min: isLog ? correctFloat(lin2log(axis.min)) : axis.min, max: isLog ? correctFloat(lin2log(axis.max)) : axis.max, dataMin: axis.dataMin, dataMax: axis.dataMax, userMin: axis.userMin, userMax: axis.userMax }; }, /** * Get the zero plane either based on zero or on the min or max value. * Used in bar and area plots */ getThreshold: function (threshold) { var axis = this, isLog = axis.isLog, realMin = isLog ? lin2log(axis.min) : axis.min, realMax = isLog ? lin2log(axis.max) : axis.max; // With a threshold of null, make the columns/areas rise from the top or bottom // depending on the value, assuming an actual threshold of 0 (#4233). if (threshold === null) { threshold = realMax < 0 ? realMax : realMin; } else if (realMin > threshold) { threshold = realMin; } else if (realMax < threshold) { threshold = realMax; } return axis.translate(threshold, 0, 1, 0, 1); }, /** * Compute auto alignment for the axis label based on which side the axis is on * and the given rotation for the label */ autoLabelAlign: function (rotation) { var ret, angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360; if (angle > 15 && angle < 165) { ret = 'right'; } else if (angle > 195 && angle < 345) { ret = 'left'; } else { ret = 'center'; } return ret; }, /** * Prevent the ticks from getting so close we can't draw the labels. On a horizontal * axis, this is handled by rotating the labels, removing ticks and adding ellipsis. * On a vertical axis remove ticks and add ellipsis. */ unsquish: function () { var chart = this.chart, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, tickInterval = this.tickInterval, newTickInterval = tickInterval, slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval), rotation, rotationOption = labelOptions.rotation, labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), step, bestScore = Number.MAX_VALUE, autoRotation, // Return the multiple of tickInterval that is needed to avoid collision getStep = function (spaceNeeded) { var step = spaceNeeded / (slotSize || 1); step = step > 1 ? mathCeil(step) : 1; return step * tickInterval; }; if (horiz) { autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971 defined(rotationOption) ? [rotationOption] : slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation ); if (autoRotation) { // Loop over the given autoRotation options, and determine which gives the best score. The // best score is that with the lowest number of steps and a rotation closest to horizontal. each(autoRotation, function (rot) { var score; if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891 step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot))); score = step + mathAbs(rot / 360); if (score < bestScore) { bestScore = score; rotation = rot; newTickInterval = step; } } }); } } else if (!labelOptions.step) { // #4411 newTickInterval = getStep(labelMetrics.h); } this.autoRotation = autoRotation; this.labelRotation = pick(rotation, rotationOption); return newTickInterval; }, renderUnsquish: function () { var chart = this.chart, renderer = chart.renderer, tickPositions = this.tickPositions, ticks = this.ticks, labelOptions = this.options.labels, horiz = this.horiz, margin = chart.margin, slotCount = this.categories ? tickPositions.length : tickPositions.length - 1, slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation && ((this.staggerLines || 1) * chart.plotWidth) / slotCount) || (!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931, innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))), attr = {}, labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label), textOverflowOption = labelOptions.style.textOverflow, css, labelLength = 0, label, i, pos; // Set rotation option unless it is "auto", like in gauges if (!isString(labelOptions.rotation)) { attr.rotation = labelOptions.rotation || 0; // #4443 } // Handle auto rotation on horizontal axis if (this.autoRotation) { // Get the longest label length each(tickPositions, function (tick) { tick = ticks[tick]; if (tick && tick.labelLength > labelLength) { labelLength = tick.labelLength; } }); // Apply rotation only if the label is too wide for the slot, and // the label is wider than its height. if (labelLength > innerWidth && labelLength > labelMetrics.h) { attr.rotation = this.labelRotation; } else { this.labelRotation = 0; } // Handle word-wrap or ellipsis on vertical axis } else if (slotWidth) { // For word-wrap or ellipsis css = { width: innerWidth + PX }; if (!textOverflowOption) { css.textOverflow = 'clip'; // On vertical axis, only allow word wrap if there is room for more lines. i = tickPositions.length; while (!horiz && i--) { pos = tickPositions[i]; label = ticks[pos].label; if (label) { // Reset ellipsis in order to get the correct bounding box (#4070) if (label.styles.textOverflow === 'ellipsis') { label.css({ textOverflow: 'clip' }); } if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) { label.specCss = { textOverflow: 'ellipsis' }; } } } } } // Add ellipsis if the label length is significantly longer than ideal if (attr.rotation) { css = { width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX }; if (!textOverflowOption) { css.textOverflow = 'ellipsis'; } } // Set the explicit or automatic label alignment this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation); // Apply general and specific CSS each(tickPositions, function (pos) { var tick = ticks[pos], label = tick && tick.label; if (label) { label.attr(attr); // This needs to go before the CSS in old IE (#4502) if (css) { label.css(merge(css, label.specCss)); } delete label.specCss; tick.rotation = attr.rotation; } }); // TODO: Why not part of getLabelPosition? this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2); }, /** * Return true if the axis has associated data */ hasData: function () { return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions); }, /** * Render the tick labels to a preliminary position to get their sizes */ getOffset: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, tickPositions = axis.tickPositions, ticks = axis.ticks, horiz = axis.horiz, side = axis.side, invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side, hasData, showAxis, titleOffset = 0, titleOffsetOption, titleMargin = 0, axisTitleOptions = options.title, labelOptions = options.labels, labelOffset = 0, // reset labelOffsetPadded, axisOffset = chart.axisOffset, clipOffset = chart.clipOffset, clip, directionFactor = [-1, 1, 1, -1][side], n, axisParent = axis.axisParent, // Used in color axis lineHeightCorrection; // For reuse in Axis.render hasData = axis.hasData(); axis.showAxis = showAxis = hasData || pick(options.showEmpty, true); // Set/reset staggerLines axis.staggerLines = axis.horiz && labelOptions.staggerLines; // Create the axisGroup and gridGroup elements on first iteration if (!axis.axisGroup) { axis.gridGroup = renderer.g('grid') .attr({ zIndex: options.gridZIndex || 1 }) .add(axisParent); axis.axisGroup = renderer.g('axis') .attr({ zIndex: options.zIndex || 2 }) .add(axisParent); axis.labelGroup = renderer.g('axis-labels') .attr({ zIndex: labelOptions.zIndex || 7 }) .addClass(PREFIX + axis.coll.toLowerCase() + '-labels') .add(axisParent); } if (hasData || axis.isLinked) { // Generate ticks each(tickPositions, function (pos) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } else { ticks[pos].addLabel(); // update labels depending on tick interval } }); axis.renderUnsquish(); 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] }) .addClass(PREFIX + this.coll.toLowerCase() + '-title') .css(axisTitleOptions.style) .add(axis.axisGroup); axis.axisTitle.isNew = true; } if (showAxis) { titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width']; titleOffsetOption = axisTitleOptions.offset; titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10); } // hide or show the title depending on whether showEmpty is set axis.axisTitle[showAxis ? 'show' : 'hide'](); } // handle automatic or user set offset axis.offset = directionFactor * pick(options.offset, axisOffset[side]); axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0; labelOffsetPadded = labelOffset + titleMargin + (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection)); axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded); axisOffset[side] = mathMax( axisOffset[side], axis.axisTitleMargin + titleOffset + directionFactor * axis.offset, labelOffsetPadded // #3027 ); // Decide the clipping needed to keep the graph inside the plot area and axis lines clip = options.offset ? 0 : mathFloor(options.lineWidth / 2) * 2; // #4308, #4371 clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], clip); }, /** * Get the path for the axis line */ getLinePath: function (lineWidth) { var chart = this.chart, opposite = this.opposite, offset = this.offset, horiz = this.horiz, lineLeft = this.left + (opposite ? this.width : 0) + offset, lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset; if (opposite) { lineWidth *= -1; // crispify the other way - #1480, #1687 } return chart.renderer.crispLine([ M, horiz ? this.left : lineLeft, horiz ? lineTop : this.top, L, horiz ? chart.chartWidth - this.right : lineLeft, horiz ? lineTop : chart.chartHeight - this.bottom ], lineWidth); }, /** * Position the title */ getTitlePosition: function () { // compute anchor points for each of the title align options var horiz = this.horiz, axisLeft = this.left, axisTop = this.top, axisLength = this.len, axisTitleOptions = this.options.title, margin = horiz ? axisLeft : axisTop, opposite = this.opposite, offset = this.offset, xOption = axisTitleOptions.x || 0, yOption = axisTitleOptions.y || 0, fontSize = pInt(axisTitleOptions.style.fontSize || 12), // the position in the length direction of the axis alongAxis = { low: margin + (horiz ? 0 : axisLength), middle: margin + axisLength / 2, high: margin + (horiz ? axisLength : 0) }[axisTitleOptions.align], // the position in the perpendicular direction of the axis offAxis = (horiz ? axisTop + this.height : axisLeft) + (horiz ? 1 : -1) * // horizontal axis reverses the margin (opposite ? -1 : 1) * // so does opposite axes this.axisTitleMargin + (this.side === 2 ? fontSize : 0); return { x: horiz ? alongAxis + xOption : offAxis + (opposite ? this.width : 0) + offset + xOption, y: horiz ? offAxis + yOption - (opposite ? this.height : 0) + offset : alongAxis + yOption }; }, /** * Render the axis */ render: function () { var axis = this, chart = axis.chart, renderer = chart.renderer, options = axis.options, isLog = axis.isLog, isLinked = axis.isLinked, tickPositions = axis.tickPositions, axisTitle = axis.axisTitle, ticks = axis.ticks, minorTicks = axis.minorTicks, alternateBands = axis.alternateBands, stackLabelOptions = options.stackLabels, alternateGridColor = options.alternateGridColor, tickmarkOffset = axis.tickmarkOffset, lineWidth = options.lineWidth, linePath, hasRendered = chart.hasRendered, slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin), showAxis = axis.showAxis, globalAnimation = renderer.globalAnimation, from, to; // Reset axis.labelEdge.length = 0; //axis.justifyToPlot = overflow === 'justify'; axis.overlap = false; // Mark all elements inActive before we go over and mark the active ones each([ticks, minorTicks, alternateBands], function (coll) { var pos; for (pos in coll) { coll[pos].isActive = false; } }); // If the series has data draw the ticks. Else only the line and title if (axis.hasData() || isLinked) { // minor ticks if (axis.minorTickInterval && !axis.categories) { each(axis.getMinorTickPositions(), function (pos) { if (!minorTicks[pos]) { minorTicks[pos] = new Tick(axis, pos, 'minor'); } // render new ticks in old position if (slideInTicks && minorTicks[pos].isNew) { minorTicks[pos].render(null, true); } minorTicks[pos].render(null, false, 1); }); } // Major ticks. Pull out the first item and render it last so that // we can get the position of the neighbour label. #808. if (tickPositions.length) { // #1300 each(tickPositions, function (pos, i) { // linked axes need an extra check to find out if if (!isLinked || (pos >= axis.min && pos <= axis.max)) { if (!ticks[pos]) { ticks[pos] = new Tick(axis, pos); } // render new ticks in old position if (slideInTicks && ticks[pos].isNew) { ticks[pos].render(i, true, 0.1); } ticks[pos].render(i); } }); // In a categorized axis, the tick marks are displayed between labels. So // we need to add a tick mark and grid line at the left edge of the X axis. if (tickmarkOffset && (axis.min === 0 || axis.single)) { if (!ticks[-1]) { ticks[-1] = new Tick(axis, -1, null, true); } ticks[-1].render(-1); } } // alternate grid color if (alternateGridColor) { each(tickPositions, function (pos, i) { to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset; if (i % 2 === 0 && pos < axis.max && to <= axis.max - tickmarkOffset) { // #2248 if (!alternateBands[pos]) { alternateBands[pos] = new Highcharts.PlotLineOrBand(axis); } from = pos + tickmarkOffset; // #949 alternateBands[pos].options = { from: isLog ? lin2log(from) : from, to: isLog ? lin2log(to) : to, color: alternateGridColor }; alternateBands[pos].render(); alternateBands[pos].isActive = true; } }); } // custom plot lines and bands if (!axis._addedPlotLB) { // only first time each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) { axis.addPlotBandOrLine(plotLineOptions); }); axis._addedPlotLB = true; } } // end if hasData // Remove inactive ticks each([ticks, minorTicks, alternateBands], function (coll) { var pos, i, forDestruction = [], delay = globalAnimation ? globalAnimation.duration || 500 : 0, destroyInactiveItems = function () { i = forDestruction.length; while (i--) { // When resizing rapidly, the same items may be destroyed in different timeouts, // or the may be reactivated if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) { coll[forDestruction[i]].destroy(); delete coll[forDestruction[i]]; } } }; for (pos in coll) { if (!coll[pos].isActive) { // Render to zero opacity coll[pos].render(pos, false, 0); coll[pos].isActive = false; forDestruction.push(pos); } } // When the objects are finished fading out, destroy them 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) { axis.renderStackTotals(); } // End stacked totals axis.isDirty = false; }, /** * Redraw the axis to reflect changes in the data or axis extremes */ redraw: function () { if (this.visible) { // render the axis this.render(); // move plot lines and bands each(this.plotLinesAndBands, function (plotLine) { plotLine.render(); }); } // mark associated series as dirty and ready for redraw each(this.series, function (series) { series.isDirty = true; }); }, /** * Destroys an Axis instance. */ destroy: function (keepEvents) { var axis = this, stacks = axis.stacks, stackKey, plotLinesAndBands = axis.plotLinesAndBands, i; // Remove the events if (!keepEvents) { removeEvent(axis); } // Destroy each stack total for (stackKey in stacks) { destroyObjectProperties(stacks[stackKey]); stacks[stackKey] = null; } // Destroy collections each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) { destroyObjectProperties(coll); }); i = plotLinesAndBands.length; while (i--) { // #1975 plotLinesAndBands[i].destroy(); } // Destroy local variables each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) { if (axis[prop]) { axis[prop] = axis[prop].destroy(); } }); // Destroy crosshair if (this.cross) { this.cross.destroy(); } }, /** * Draw the crosshair */ drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties. var path, options = this.crosshair, animation = options.animation, pos, attribs, categorized; if ( // Disabled in options !this.crosshair || // Snap ((defined(point) || !pick(this.crosshair.snap, true)) === false) || // Not on this axis (#4095, #2888) (point && point.series && point.series[this.coll] !== this) ) { this.hideCrosshair(); } else { // Get the path if (!pick(options.snap, true)) { pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos); } else if (defined(point)) { /*jslint eqeq: true*/ pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834 /*jslint eqeq: false*/ } if (this.isRadial) { path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189 } else { path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189 } if (path === null) { this.hideCrosshair(); return; } // Draw the cross if (this.cross) { this.cross .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation); } else { categorized = this.categories && !this.isRadial; attribs = { 'stroke-width': options.width || (categorized ? this.transA : 1), stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'), zIndex: options.zIndex || 2 }; if (options.dashStyle) { attribs.dashstyle = options.dashStyle; } this.cross = this.chart.renderer.path(path).attr(attribs).add(); } } }, /** * Hide the crosshair. */ hideCrosshair: function () { if (this.cross) { this.cross.hide(); } } }; // end Axis extend(Axis.prototype, AxisPlotLineOrBandExtension); /** * 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 */ Axis.prototype.getTimeTicks = function (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 - getTZOffset(min)), interval = normalizedInterval.unitRange, count = normalizedInterval.count; if (defined(min)) { // #1300 minDate[setMilliseconds](interval >= timeUnits.second ? 0 : // #3935 count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654 if (interval >= timeUnits.second) { // second minDate[setSeconds](interval >= timeUnits.minute ? 0 : // #3935 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; if (timezoneOffset || getTimezoneOffset) { minDate = minDate.getTime(); minDate = new Date(minDate + getTZOffset(minDate)); } minYear = minDate[getFullYear](); var time = minDate.getTime(), minMonth = minDate[getMonth](), minDateDate = minDate[getDate](), localTimezoneOffset = (timeUnits.day + (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000) ) % timeUnits.day; // #950, #3359 // 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 === localTimezoneOffset; }), 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; }; /** * 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. */ Axis.prototype.normalizeTimeTickInterval = function (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' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360 ); return { unitRange: interval, count: count, unitName: unit[0] }; };/** * Methods defined on the Axis prototype */ /** * Set the tick positions of a logarithmic axis */ Axis.prototype.getLogTickPositions = function (interval, min, max, minor) { var axis = this, options = axis.options, axisLength = axis.len, // Since we use this method for both major and minor ticks, // use a local variable and return the result positions = []; // Reset if (!minor) { axis._minorAutoInterval = null; } // First case: All ticks fall on whole logarithms: 1, 10, 100 etc. if (interval >= 0.5) { interval = mathRound(interval); positions = axis.getLinearTickPositions(interval, min, max); // Second case: We need intermediary ticks. For example // 1, 2, 4, 6, 8, 10, 20, 40 etc. } else if (interval >= 0.08) { var roundedMin = mathFloor(min), intermediate, i, j, len, pos, lastPos, break2; if (interval > 0.3) { intermediate = [1, 2, 4]; } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc intermediate = [1, 2, 4, 6, 8]; } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9]; } for (i = roundedMin; i < max + 1 && !break2; i++) { len = intermediate.length; for (j = 0; j < len && !break2; j++) { pos = log2lin(lin2log(i) * intermediate[j]); if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113 positions.push(lastPos); } if (lastPos > max) { break2 = true; } lastPos = pos; } } // Third case: We are so deep in between whole logarithmic values that // we might as well handle the tick positions like a linear axis. For // example 1.01, 1.02, 1.03, 1.04. } else { var realMin = lin2log(min), realMax = lin2log(max), tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'], filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption, tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1), totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength; interval = pick( filteredTickIntervalOption, axis._minorAutoInterval, (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1) ); interval = normalizeTickInterval( interval, null, getMagnitude(interval) ); positions = map(axis.getLinearTickPositions( interval, realMin, realMax ), log2lin); if (!minor) { axis._minorAutoInterval = interval / 5; } } // Set the axis-level tickInterval variable if (!minor) { axis.tickInterval = interval; } return positions; };/** * The tooltip object * @param {Object} chart The chart instance * @param {Object} options Tooltip options */ var Tooltip = Highcharts.Tooltip = function () { this.init.apply(this, arguments); }; Tooltip.prototype = { init: function (chart, options) { var borderWidth = options.borderWidth, style = options.style, padding = pInt(style.padding); // Save the chart and options this.chart = chart; this.options = options; // Keep track of the current series //this.currentSeries = UNDEFINED; // List of crosshairs this.crosshairs = []; // Current values of x and y when animating this.now = { x: 0, y: 0 }; // The tooltip is initially hidden this.isHidden = true; // create the label this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip') .attr({ padding: padding, fill: options.backgroundColor, 'stroke-width': borderWidth, r: options.borderRadius, zIndex: 8 }) .css(style) .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117) .add() .attr({ y: -9999 }); // #2301, #2657 // When using canVG the shadow shows up as a gray circle // even if the tooltip is hidden. if (!useCanVG) { this.label.shadow(options.shadow); } // Public property for getting the shared state. this.shared = options.shared; }, /** * Destroy the tooltip and its elements. */ destroy: function () { // Destroy and clear local variables if (this.label) { this.label = this.label.destroy(); } clearTimeout(this.hideTimer); clearTimeout(this.tooltipTimeout); }, /** * Provide a soft movement for the tooltip * * @param {Number} x * @param {Number} y * @private */ move: function (x, y, anchorX, anchorY) { var tooltip = this, now = tooltip.now, animate = tooltip.options.animation !== false && !tooltip.isHidden && // When we get close to the target position, abort animation and land on the right place (#3056) (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1), skipAnchor = tooltip.followPointer || tooltip.len > 1; // Get intermediate values for animation extend(now, { x: animate ? (2 * now.x + x) / 3 : x, y: animate ? (now.y + y) / 2 : y, anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX, anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY }); // Move to the intermediate value tooltip.label.attr(now); // Run on next tick of the mouse tracker if (animate) { // Never allow two timeouts clearTimeout(this.tooltipTimeout); // Set the fixed interval ticking for the smooth tooltip this.tooltipTimeout = setTimeout(function () { // The interval function may still be running during destroy, so check that the chart is really there before calling. if (tooltip) { tooltip.move(x, y, anchorX, anchorY); } }, 32); } }, /** * Hide the tooltip */ hide: function (delay) { var tooltip = this, 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(delay, this.options.hideDelay, 500)); } }, /** * Extendable method to get the anchor position of the tooltip * from a point or set of points */ getAnchor: function (points, mouseEvent) { var ret, chart = this.chart, inverted = chart.inverted, plotTop = chart.plotTop, plotLeft = chart.plotLeft, plotX = 0, plotY = 0, yAxis, xAxis; points = splat(points); // Pie uses a special tooltipPos ret = points[0].tooltipPos; // When tooltip follows mouse, relate the position to the mouse if (this.followPointer && mouseEvent) { if (mouseEvent.chartX === UNDEFINED) { mouseEvent = chart.pointer.normalize(mouseEvent); } ret = [ mouseEvent.chartX - chart.plotLeft, mouseEvent.chartY - plotTop ]; } // When shared, use the average position if (!ret) { each(points, function (point) { yAxis = point.series.yAxis; xAxis = point.series.xAxis; plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0); plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) + (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151 }); plotX /= points.length; plotY /= points.length; ret = [ inverted ? chart.plotWidth - plotY : plotX, this.shared && !inverted && points.length > 1 && mouseEvent ? mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424) inverted ? chart.plotHeight - plotX : plotY ]; } return map(ret, mathRound); }, /** * Place the tooltip in a chart without spilling over * and not covering the point it self. */ getPosition: function (boxWidth, boxHeight, point) { var chart = this.chart, distance = this.distance, ret = {}, h = point.h || 0, // #4117 swapped, first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop, chart.plotTop, chart.plotTop + chart.plotHeight], second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft, chart.plotLeft, chart.plotLeft + chart.plotWidth], // The far side is right or bottom preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)), /** * Handle the preferred dimension. When the preferred dimension is tooltip * on top or bottom of the point, it will look for space there. */ firstDimension = function (dim, outerSize, innerSize, point, min, max) { var roomLeft = innerSize < point - distance, roomRight = point + distance + innerSize < outerSize, alignedLeft = point - distance - innerSize, alignedRight = point + distance; if (preferFarSide && roomRight) { ret[dim] = alignedRight; } else if (!preferFarSide && roomLeft) { ret[dim] = alignedLeft; } else if (roomLeft) { ret[dim] = mathMin(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h); } else if (roomRight) { ret[dim] = mathMax(min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h); } else { return false; } }, /** * Handle the secondary dimension. If the preferred dimension is tooltip * on top or bottom of the point, the second dimension is to align the tooltip * above the point, trying to align center but allowing left or right * align within the chart box. */ secondDimension = function (dim, outerSize, innerSize, point) { // Too close to the edge, return false and swap dimensions if (point < distance || point > outerSize - distance) { return false; // Align left/top } else if (point < innerSize / 2) { ret[dim] = 1; // Align right/bottom } else if (point > outerSize - innerSize / 2) { ret[dim] = outerSize - innerSize - 2; // Align center } else { ret[dim] = point - innerSize / 2; } }, /** * Swap the dimensions */ swap = function (count) { var temp = first; first = second; second = temp; swapped = count; }, run = function () { if (firstDimension.apply(0, first) !== false) { if (secondDimension.apply(0, second) === false && !swapped) { swap(true); run(); } } else if (!swapped) { swap(true); run(); } else { ret.x = ret.y = 0; } }; // Under these conditions, prefer the tooltip on the side of the point if (chart.inverted || this.len > 1) { swap(); } run(); return ret; }, /** * In case no user defined formatter is given, this will be used. Note that the context * here is an object holding point, series, x, y etc. */ defaultFormatter: function (tooltip) { var items = this.points || splat(this), s; // build the header s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header // build the values s = s.concat(tooltip.bodyFormatter(items)); // footer s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header return s.join(''); }, /** * Refresh the tooltip's text and position. * @param {Object} point */ refresh: function (point, mouseEvent) { var tooltip = this, chart = tooltip.chart, label = tooltip.label, options = tooltip.options, x, y, anchor, textConfig = {}, text, pointConfig = [], formatter = options.formatter || tooltip.defaultFormatter, hoverPoints = chart.hoverPoints, borderColor, shared = tooltip.shared, currentSeries; clearTimeout(this.hideTimer); // get the reference point coordinates (pie charts use tooltipPos) tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer; anchor = tooltip.getAnchor(point, mouseEvent); x = anchor[0]; y = anchor[1]; // shared tooltip, array is sent over if (shared && !(point.series && point.series.noSharedTooltip)) { // hide previous hoverPoints and set new chart.hoverPoints = point; if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } each(point, function (item) { item.setState(HOVER_STATE); pointConfig.push(item.getLabelConfig()); }); textConfig = { x: point[0].category, y: point[0].y }; textConfig.points = pointConfig; this.len = pointConfig.length; point = point[0]; // single point tooltip } else { textConfig = point.getLabelConfig(); } text = formatter.call(textConfig, tooltip); // register the current series currentSeries = point.series; this.distance = pick(currentSeries.tooltipOptions.distance, 16); // update the inner HTML if (text === false) { this.hide(); } else { // show it if (tooltip.isHidden) { stop(label); label.attr('opacity', 1).show(); } // update text label.attr({ text: text }); // set the stroke color of the box borderColor = options.borderColor || point.color || currentSeries.color || '#606060'; label.attr({ stroke: borderColor }); tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow, h: anchor[2] || 0 }); this.isHidden = false; } fireEvent(chart, 'tooltipRefresh', { text: text, x: x + chart.plotLeft, y: y + chart.plotTop, borderColor: borderColor }); }, /** * Find the new position and perform the move */ updatePosition: function (point) { var chart = this.chart, label = this.label, pos = (this.options.positioner || this.getPosition).call( this, label.width, label.height, point ); // do the move this.move( mathRound(pos.x), mathRound(pos.y || 0), // can be undefined (#3977) point.plotX + chart.plotLeft, point.plotY + chart.plotTop ); }, /** * Get the best X date format based on the closest point range on the axis. */ getXDateFormat: function (point, options, xAxis) { var xDateFormat, dateTimeLabelFormats = options.dateTimeLabelFormats, closestPointRange = xAxis && xAxis.closestPointRange, n, blank = '01-01 00:00:00.000', strpos = { millisecond: 15, second: 12, minute: 9, hour: 6, day: 3 }, date, lastN = 'millisecond'; // for sub-millisecond data, #4223 if (closestPointRange) { date = dateFormat('%m-%d %H:%M:%S.%L', point.x); for (n in timeUnits) { // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek && date.substr(6) === blank.substr(6)) { n = 'week'; break; // The first format that is too great for the range } else if (timeUnits[n] > closestPointRange) { n = lastN; break; // If the point is placed every day at 23:59, we need to show // the minutes as well. #2637. } else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) { break; } // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition if (n !== 'week') { lastN = n; } } if (n) { xDateFormat = dateTimeLabelFormats[n]; } } else { xDateFormat = dateTimeLabelFormats.day; } return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581 }, /** * Format the footer/header of the tooltip * #3397: abstraction to enable formatting of footer and header */ tooltipFooterHeaderFormatter: function (point, isFooter) { var footOrHead = isFooter ? 'footer' : 'header', series = point.series, tooltipOptions = series.tooltipOptions, xDateFormat = tooltipOptions.xDateFormat, xAxis = series.xAxis, isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key), formatString = tooltipOptions[footOrHead+'Format']; // Guess the best date format based on the closest point distance (#568, #3418) if (isDateTime && !xDateFormat) { xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis); } // Insert the footer date format if any if (isDateTime && xDateFormat) { formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}'); } return format(formatString, { point: point, series: series }); }, /** * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item, * abstracting this functionality allows to easily overwrite and extend it. */ bodyFormatter: function (items) { return map(items, function (item) { var tooltipOptions = item.series.tooltipOptions; return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat); }); } }; var hoverChartIndex; // Global flag for touch support hasTouch = doc.documentElement.ontouchstart !== UNDEFINED; /** * The mouse tracker object. All methods starting with "on" are primary DOM event handlers. * Subsequent methods should be named differently from what they are doing. * @param {Object} chart The Chart instance * @param {Object} options The root options object */ var Pointer = Highcharts.Pointer = function (chart, options) { this.init(chart, options); }; Pointer.prototype = { /** * Initialize Pointer */ init: function (chart, options) { var chartOptions = options.chart, chartEvents = chartOptions.events, zoomType = useCanVG ? '' : chartOptions.zoomType, inverted = chart.inverted, zoomX, zoomY; // Store references this.options = options; this.chart = chart; // Zoom status this.zoomX = zoomX = /x/.test(zoomType); this.zoomY = zoomY = /y/.test(zoomType); this.zoomHor = (zoomX && !inverted) || (zoomY && inverted); this.zoomVert = (zoomY && !inverted) || (zoomX && inverted); this.hasZoom = zoomX || zoomY; // Do we need to handle click on a touch device? this.runChartClick = chartEvents && !!chartEvents.click; this.pinchDown = []; this.lastValidTouch = {}; if (Highcharts.Tooltip && options.tooltip.enabled) { chart.tooltip = new Tooltip(chart, options.tooltip); this.followTouchMove = pick(options.tooltip.followTouchMove, true); } this.setDOMEvents(); }, /** * Add crossbrowser support for chartX and chartY * @param {Object} e The event object in standard browsers */ normalize: function (e, chartPosition) { var chartX, chartY, ePos; // common IE normalizing e = e || window.event; // Framework specific normalizing (#1165) e = washMouseEvent(e); // More IE normalizing, needs to go after washMouseEvent if (!e.target) { e.target = e.srcElement; } // iOS (#2757) ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e; // Get mouse position if (!chartPosition) { this.chartPosition = chartPosition = offset(this.chart.container); } // chartX and chartY if (ePos.pageX === UNDEFINED) { // IE < 9. #886. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is // for IE10 quirks mode within framesets chartY = e.y; } else { chartX = ePos.pageX - chartPosition.left; chartY = ePos.pageY - chartPosition.top; } return extend(e, { chartX: mathRound(chartX), chartY: mathRound(chartY) }); }, /** * Get the click position in terms of axis values. * * @param {Object} e A pointer event */ getCoordinates: function (e) { var coordinates = { xAxis: [], yAxis: [] }; each(this.chart.axes, function (axis) { coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({ axis: axis, value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY']) }); }); return coordinates; }, /** * With line type charts with a single tracker, get the point closest to the mouse. * Run Point.onMouseOver and display tooltip for the point or points. */ runPointActions: function (e) { var pointer = this, chart = pointer.chart, series = chart.series, tooltip = chart.tooltip, shared = tooltip ? tooltip.shared : false, followPointer, hoverPoint = chart.hoverPoint, hoverSeries = chart.hoverSeries, i, distance = Number.MAX_VALUE, // #4511 anchor, noSharedTooltip, stickToHoverSeries, directTouch, kdpoints = [], kdpoint, kdpointT; // For hovering over the empty parts of the plot area (hoverSeries is undefined). // If there is one series with point tracking (combo chart), don't go to nearest neighbour. if (!shared && !hoverSeries) { for (i = 0; i < series.length; i++) { if (series[i].directTouch || !series[i].options.stickyTracking) { series = []; } } } // If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on // a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise, // search the k-d tree. stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch); if (stickToHoverSeries && hoverPoint) { kdpoint = hoverPoint; // Handle shared tooltip or cases where a series is not yet hovered } else { // Find nearest points on all series each(series, function (s) { // Skip hidden series noSharedTooltip = s.noSharedTooltip && shared; directTouch = !shared && s.directTouch; if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821 kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828 if (kdpointT) { kdpoints.push(kdpointT); } } }); // Find absolute nearest point each(kdpoints, function (p) { if (p && typeof p.dist === 'number' && p.dist < distance) { distance = p.dist; kdpoint = p; } }); } // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200 if (kdpoint && (kdpoint !== this.prevKDPoint || (tooltip && tooltip.isHidden))) { // Draw tooltip if necessary if (shared && !kdpoint.series.noSharedTooltip) { i = kdpoints.length; while (i--) { if (kdpoints[i].clientX !== kdpoint.clientX || kdpoints[i].series.noSharedTooltip) { kdpoints.splice(i, 1); } } if (kdpoints.length && tooltip) { tooltip.refresh(kdpoints, e); } // Do mouseover on all points (#3919, #3985, #4410) each(kdpoints, function (point) { point.onMouseOver(e, point !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoint)); }); } else { if (tooltip) { tooltip.refresh(kdpoint, e); } if(!hoverSeries || !hoverSeries.directTouch) { // #4448 kdpoint.onMouseOver(e); } } this.prevKDPoint = kdpoint; // Update positions (regardless of kdpoint or hoverPoint) } else { followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer; if (tooltip && followPointer && !tooltip.isHidden) { anchor = tooltip.getAnchor([{}], e); tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] }); } } // Start the event listener to pick up the tooltip if (tooltip && !pointer._onDocumentMouseMove) { pointer._onDocumentMouseMove = function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.onDocumentMouseMove(e); } }; addEvent(doc, 'mousemove', pointer._onDocumentMouseMove); } // Crosshair each(chart.axes, function (axis) { axis.drawCrosshair(e, pick(kdpoint, hoverPoint)); }); }, /** * Reset the tracking by hiding the tooltip, the hover series state and the hover point * * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible */ reset: function (allowMove, delay) { var pointer = this, chart = pointer.chart, hoverSeries = chart.hoverSeries, hoverPoint = chart.hoverPoint, hoverPoints = chart.hoverPoints, tooltip = chart.tooltip, tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint; // Narrow in allowMove allowMove = allowMove && tooltip && tooltipPoints; // Check if the points have moved outside the plot area, #1003 if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) { allowMove = false; } // Just move the tooltip, #349 if (allowMove) { tooltip.refresh(tooltipPoints); if (hoverPoint) { // #2500 hoverPoint.setState(hoverPoint.state, true); each(chart.axes, function (axis) { if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) { axis.drawCrosshair(null, hoverPoint); } else { axis.hideCrosshair(); } }); } // Full reset } else { if (hoverPoint) { hoverPoint.onMouseOut(); } if (hoverPoints) { each(hoverPoints, function (point) { point.setState(); }); } if (hoverSeries) { hoverSeries.onMouseOut(); } if (tooltip) { tooltip.hide(delay); } if (pointer._onDocumentMouseMove) { removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove); pointer._onDocumentMouseMove = null; } // Remove crosshairs each(chart.axes, function (axis) { axis.hideCrosshair(); }); pointer.hoverX = chart.hoverPoints = chart.hoverPoint = null; } }, /** * Scale series groups to a certain scale and translation */ scaleGroups: function (attribs, clip) { var chart = this.chart, seriesAttribs; // Scale each series each(chart.series, function (series) { seriesAttribs = attribs || series.getPlotBox(); // #1701 if (series.xAxis && series.xAxis.zoomEnabled) { series.group.attr(seriesAttribs); if (series.markerGroup) { series.markerGroup.attr(seriesAttribs); series.markerGroup.clip(clip ? chart.clipRect : null); } if (series.dataLabelsGroup) { series.dataLabelsGroup.attr(seriesAttribs); } } }); // Clip chart.clipRect.attr(clip || chart.clipBox); }, /** * Start a drag operation */ dragStart: function (e) { var chart = this.chart; // Record the start position chart.mouseIsDown = e.type; chart.cancelClick = false; chart.mouseDownX = this.mouseDownX = e.chartX; chart.mouseDownY = this.mouseDownY = e.chartY; }, /** * Perform a drag operation in response to a mousemove event while the mouse is down */ drag: function (e) { var chart = this.chart, chartOptions = chart.options.chart, chartX = e.chartX, chartY = e.chartY, zoomHor = this.zoomHor, zoomVert = this.zoomVert, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, clickedInside, size, selectionMarker = this.selectionMarker, mouseDownX = this.mouseDownX, mouseDownY = this.mouseDownY, panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key']; // If the device supports both touch and mouse (like IE11), and we are touch-dragging // inside the plot area, don't handle the mouse event. #4339. if (selectionMarker && selectionMarker.touch) { return; } // If the mouse is outside the plot area, adjust to cooordinates // inside to prevent the selection marker from going outside if (chartX < plotLeft) { chartX = plotLeft; } else if (chartX > plotLeft + plotWidth) { chartX = plotLeft + plotWidth; } if (chartY < plotTop) { chartY = plotTop; } else if (chartY > plotTop + plotHeight) { chartY = plotTop + plotHeight; } // determine if the mouse has moved more than 10px this.hasDragged = Math.sqrt( Math.pow(mouseDownX - chartX, 2) + Math.pow(mouseDownY - chartY, 2) ); if (this.hasDragged > 10) { clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop); // make a selection if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) { if (!selectionMarker) { this.selectionMarker = selectionMarker = chart.renderer.rect( plotLeft, plotTop, zoomHor ? 1 : plotWidth, zoomVert ? 1 : plotHeight, 0 ) .attr({ fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)', zIndex: 7 }) .add(); } } // adjust the width of the selection marker if (selectionMarker && zoomHor) { size = chartX - mouseDownX; selectionMarker.attr({ width: mathAbs(size), x: (size > 0 ? 0 : size) + mouseDownX }); } // adjust the height of the selection marker if (selectionMarker && zoomVert) { size = chartY - mouseDownY; selectionMarker.attr({ height: mathAbs(size), y: (size > 0 ? 0 : size) + mouseDownY }); } // panning if (clickedInside && !selectionMarker && chartOptions.panning) { chart.pan(e, chartOptions.panning); } } }, /** * On mouse up or touch end across the entire document, drop the selection. */ drop: function (e) { var pointer = this, chart = this.chart, hasPinched = this.hasPinched; if (this.selectionMarker) { var selectionData = { xAxis: [], yAxis: [], originalEvent: e.originalEvent || e }, selectionBox = this.selectionMarker, selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x, selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y, selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width, selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height, runZoom; // a selection has been made if (this.hasDragged || hasPinched) { // record each axis' min and max each(chart.axes, function (axis) { if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569 var horiz = axis.horiz, minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075 selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding), selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding); selectionData[axis.coll].push({ axis: axis, min: mathMin(selectionMin, selectionMax), // for reversed axes max: mathMax(selectionMin, selectionMax) }); runZoom = true; } }); if (runZoom) { fireEvent(chart, 'selection', selectionData, function (args) { chart.zoom(extend(args, hasPinched ? { animation: false } : null)); }); } } this.selectionMarker = this.selectionMarker.destroy(); // Reset scaling preview if (hasPinched) { this.scaleGroups(); } } // Reset all if (chart) { // it may be destroyed on mouse up - #877 css(chart.container, { cursor: chart._cursor }); chart.cancelClick = this.hasDragged > 10; // #370 chart.mouseIsDown = this.hasDragged = this.hasPinched = false; this.pinchDown = []; } }, onContainerMouseDown: function (e) { e = this.normalize(e); // issue #295, dragging not always working in Firefox if (e.preventDefault) { e.preventDefault(); } this.dragStart(e); }, onDocumentMouseUp: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } }, /** * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea. * Issue #149 workaround. The mouseleave event does not always fire. */ onDocumentMouseMove: function (e) { var chart = this.chart, chartPosition = this.chartPosition; e = this.normalize(e, chartPosition); // If we're outside, hide the tooltip if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') && !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) { this.reset(); } }, /** * When mouse leaves the container, hide the tooltip. */ onContainerMouseLeave: function () { var chart = charts[hoverChartIndex]; if (chart) { chart.pointer.reset(); chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix } }, // The mousemove, touchmove and touchstart event handler onContainerMouseMove: function (e) { var chart = this.chart; hoverChartIndex = chart.index; e = this.normalize(e); e.returnValue = false; // #2251, #3224 if (chart.mouseIsDown === 'mousedown') { this.drag(e); } // Show the tooltip and run mouse over events (#977) if ((this.inClass(e.target, 'highcharts-tracker') || chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) { this.runPointActions(e); } }, /** * Utility to detect whether an element has, or has a parent with, a specific * class name. Used on detection of tracker objects and on deciding whether * hovering the tooltip should cause the active series to mouse out. */ inClass: function (element, className) { var elemClassName; while (element) { elemClassName = attr(element, 'class'); if (elemClassName) { if (elemClassName.indexOf(className) !== -1) { return true; } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) { return false; } } element = element.parentNode; } }, onTrackerMouseOut: function (e) { var series = this.chart.hoverSeries, relatedTarget = e.relatedTarget || e.toElement; if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') && !this.inClass(relatedTarget, PREFIX + 'series-' + series.index)) { // #2499, #4465 series.onMouseOut(); } }, onContainerClick: function (e) { var chart = this.chart, hoverPoint = chart.hoverPoint, plotLeft = chart.plotLeft, plotTop = chart.plotTop; e = this.normalize(e); e.originalEvent = e; // #3913 if (!chart.cancelClick) { // On tracker click, fire the series and point events. #783, #1583 if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) { // the series click event fireEvent(hoverPoint.series, 'click', extend(e, { point: hoverPoint })); // the point click event if (chart.hoverPoint) { // it may be destroyed (#1844) hoverPoint.firePointEvent('click', e); } // When clicking outside a tracker, fire a chart event } else { extend(e, this.getCoordinates(e)); // fire a click event in the chart if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) { fireEvent(chart, 'click', e); } } } }, /** * Set the JS DOM events on the container and document. This method should contain * a one-to-one assignment between methods and their handlers. Any advanced logic should * be moved to the handler reflecting the event's name. */ setDOMEvents: function () { var pointer = this, container = pointer.chart.container; container.onmousedown = function (e) { pointer.onContainerMouseDown(e); }; container.onmousemove = function (e) { pointer.onContainerMouseMove(e); }; container.onclick = function (e) { pointer.onContainerClick(e); }; addEvent(container, 'mouseleave', pointer.onContainerMouseLeave); if (chartCount === 1) { addEvent(doc, 'mouseup', pointer.onDocumentMouseUp); } if (hasTouch) { container.ontouchstart = function (e) { pointer.onContainerTouchStart(e); }; container.ontouchmove = function (e) { pointer.onContainerTouchMove(e); }; if (chartCount === 1) { addEvent(doc, 'touchend', pointer.onDocumentTouchEnd); } } }, /** * Destroys the Pointer object and disconnects DOM events. */ destroy: function () { var prop; removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave); if (!chartCount) { removeEvent(doc, 'mouseup', this.onDocumentMouseUp); removeEvent(doc, 'touchend', this.onDocumentTouchEnd); } // memory and CPU leak clearInterval(this.tooltipTimeout); for (prop in this) { this[prop] = null; } } }; /* Support for touch devices */ extend(Highcharts.Pointer.prototype, { /** * Run translation operations */ pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) { if (this.zoomHor || this.pinchHor) { this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } if (this.zoomVert || this.pinchVert) { this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); } }, /** * Run translation operations for each direction (horizontal and vertical) independently */ pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) { var chart = this.chart, xy = horiz ? 'x' : 'y', XY = horiz ? 'X' : 'Y', sChartXY = 'chart' + XY, wh = horiz ? 'width' : 'height', plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')], selectionWH, selectionXY, clipXY, scale = forcedScale || 1, inverted = chart.inverted, bounds = chart.bounds[horiz ? 'h' : 'v'], singleTouch = pinchDown.length === 1, touch0Start = pinchDown[0][sChartXY], touch0Now = touches[0][sChartXY], touch1Start = !singleTouch && pinchDown[1][sChartXY], touch1Now = !singleTouch && touches[1][sChartXY], outOfBounds, transformScale, scaleKey, setScale = function () { if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start); } clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start; selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale; }; // Set the scale, first pass setScale(); selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not // Out of bounds if (selectionXY < bounds.min) { selectionXY = bounds.min; outOfBounds = true; } else if (selectionXY + selectionWH > bounds.max) { selectionXY = bounds.max - selectionWH; outOfBounds = true; } // Is the chart dragged off its bounds, determined by dataMin and dataMax? if (outOfBounds) { // Modify the touchNow position in order to create an elastic drag movement. This indicates // to the user that the chart is responsive but can't be dragged further. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]); if (!singleTouch) { touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]); } // Set the scale, second pass to adapt to the modified touchNow positions setScale(); } else { lastValidTouch[xy] = [touch0Now, touch1Now]; } // Set geometry for clipping, selection and transformation if (!inverted) { // 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, touches = e.touches, touchesLength = touches.length, lastValidTouch = self.lastValidTouch, hasZoom = self.hasZoom, selectionMarker = self.selectionMarker, transform = {}, fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') && chart.runTrackerClick) || self.runChartClick), clip = {}; // Don't initiate panning until the user has pinched. This prevents us from // blocking page scrolling as users scroll down a long page (#4210). if (touchesLength > 1) { self.initiated = true; } // On touch devices, only proceed to trigger click if a handler is defined if (hasZoom && self.initiated && !fireClickEvent) { e.preventDefault(); } // Normalize each touch map(touches, function (e) { return self.normalize(e); }); // Register the touch start position if (e.type === 'touchstart') { each(touches, function (e, i) { pinchDown[i] = { chartX: e.chartX, chartY: e.chartY }; }); lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX]; lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY]; // Identify the data bounds in pixels each(chart.axes, function (axis) { if (axis.zoomEnabled) { var bounds = chart.bounds[axis.horiz ? 'h' : 'v'], minPixelPadding = axis.minPixelPadding, min = axis.toPixels(pick(axis.options.min, axis.dataMin)), max = axis.toPixels(pick(axis.options.max, axis.dataMax)), absMin = mathMin(min, max), absMax = mathMax(min, max); // Store the bounds for use in the touchmove handler bounds.min = mathMin(axis.pos, absMin - minPixelPadding); bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding); } }); self.res = true; // reset on next move // Event type is touchmove, handle panning and pinching } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first // Set the marker if (!selectionMarker) { self.selectionMarker = selectionMarker = extend({ destroy: noop, touch: true }, chart.plotBox); } self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch); self.hasPinched = hasZoom; // Scale and translate the groups to provide visual feedback during pinching self.scaleGroups(transform, clip); // Optionally move the tooltip on touchmove if (!hasZoom && self.followTouchMove && touchesLength === 1) { this.runPointActions(self.normalize(e)); } else if (self.res) { self.res = false; this.reset(false, 0); } } }, /** * General touch handler shared by touchstart and touchmove. */ touch: function (e, start) { var chart = this.chart; hoverChartIndex = chart.index; if (e.touches.length === 1) { e = this.normalize(e); if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) { // Run mouse events and display tooltip etc if (start) { this.runPointActions(e); } this.pinch(e); } else if (start) { // Hide the tooltip on touching outside the plot area (#1203) this.reset(); } } else if (e.touches.length === 2) { this.pinch(e); } }, onContainerTouchStart: function (e) { this.touch(e, true); }, onContainerTouchMove: function (e) { this.touch(e); }, onDocumentTouchEnd: function (e) { if (charts[hoverChartIndex]) { charts[hoverChartIndex].pointer.drop(e); } } }); if (win.PointerEvent || win.MSPointerEvent) { // The touches object keeps track of the points being touched at all times var touches = {}, hasPointerEvent = !!win.PointerEvent, getWebkitTouches = function () { var key, fake = []; fake.item = function (i) { return this[i]; }; for (key in touches) { if (touches.hasOwnProperty(key)) { fake.push({ pageX: touches[key].pageX, pageY: touches[key].pageY, target: touches[key].target }); } } return fake; }, translateMSPointer = function (e, method, wktype, callback) { var p; e = e.originalEvent || e; if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) { callback(e); p = charts[hoverChartIndex].pointer; p[method]({ type: wktype, target: e.currentTarget, preventDefault: noop, touches: getWebkitTouches() }); } }; /** * Extend the Pointer prototype with methods for each event handler and more */ extend(Pointer.prototype, { onContainerPointerDown: function (e) { translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget }; }); }, onContainerPointerMove: function (e) { translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) { touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY }; if (!touches[e.pointerId].target) { touches[e.pointerId].target = e.currentTarget; } }); }, onDocumentPointerUp: function (e) { translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) { delete touches[e.pointerId]; }); }, /** * Add or remove the MS Pointer specific events */ batchMSEvents: function (fn) { fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown); fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove); fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp); } }); // Disable default IE actions for pinch and such on chart element wrap(Pointer.prototype, 'init', function (proceed, chart, options) { proceed.call(this, chart, options); if (this.hasZoom) { // #4014 css(chart.container, { '-ms-touch-action': NONE, 'touch-action': NONE }); } }); // Add IE specific touch events to chart wrap(Pointer.prototype, 'setDOMEvents', function (proceed) { proceed.apply(this); if (this.hasZoom || this.followTouchMove) { this.batchMSEvents(addEvent); } }); // Destroy MS events also wrap(Pointer.prototype, 'destroy', function (proceed) { this.batchMSEvents(removeEvent); proceed.call(this); }); } /** * The overview of the chart's series */ var Legend = Highcharts.Legend = function (chart, options) { this.init(chart, options); }; Legend.prototype = { /** * Initialize the legend */ init: function (chart, options) { var legend = this, itemStyle = options.itemStyle, padding, itemMarginTop = options.itemMarginTop || 0; this.options = options; if (!options.enabled) { return; } legend.itemStyle = itemStyle; legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle); legend.itemMarginTop = itemMarginTop; legend.padding = padding = pick(options.padding, 8); legend.initialItemX = padding; legend.initialItemY = padding - 5; // 5 is the number of pixels above the text legend.maxItemWidth = 0; legend.chart = chart; legend.itemHeight = 0; legend.symbolWidth = pick(options.symbolWidth, 16); legend.pages = []; // Render it legend.render(); // move checkboxes addEvent(legend.chart, 'endResize', function () { legend.positionCheckboxes(); }); }, /** * Set the colors for the legend item * @param {Object} item A Series or Point instance * @param {Object} visible Dimmed or colored */ colorizeItem: function (item, visible) { var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ? options.itemStyle.color : hiddenColor, symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor }, key, val; if (legendItem) { legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE } if (legendLine) { legendLine.attr({ stroke: symbolColor }); } if (legendSymbol) { // Apply marker options if (markerOptions && legendSymbol.isMarker) { // #585 symbolAttr.stroke = symbolColor; markerOptions = item.convertAttribs(markerOptions); for (key in markerOptions) { val = markerOptions[key]; if (val !== UNDEFINED) { symbolAttr[key] = val; } } } legendSymbol.attr(symbolAttr); } }, /** * Position the legend item * @param {Object} item A Series or Point instance */ positionItem: function (item) { var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup; if (legendGroup && legendGroup.element) { legendGroup.translate( ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4, itemY ); } if (checkbox) { checkbox.x = itemX; checkbox.y = itemY; } }, /** * Destroy a single legend item * @param {Object} item The series or point */ destroyItem: function (item) { var checkbox = item.checkbox; // destroy SVG elements each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) { if (item[key]) { item[key] = item[key].destroy(); } }); if (checkbox) { discardElement(item.checkbox); } }, /** * Destroys the legend. */ destroy: function () { var legend = this, legendGroup = legend.group, box = legend.box; if (box) { legend.box = box.destroy(); } if (legendGroup) { legend.group = legendGroup.destroy(); } }, /** * Position the checkboxes after the width is determined */ positionCheckboxes: function (scrollOffset) { var alignAttr = this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight; 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.checkboxOffset + checkbox.x - 20) + PX, top: top + PX, display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE }); } }); } }, /** * Render the legend title on top of the legend */ renderTitle: function () { var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox; if (titleOptions.text) { if (!this.title) { this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title') .attr({ zIndex: 1 }) .css(titleOptions.style) .add(this.group); } bBox = this.title.getBBox(); titleHeight = bBox.height; this.offsetWidth = bBox.width; // #1717 this.contentGroup.attr({ translateY: titleHeight }); } this.titleHeight = titleHeight; }, /** * Set the legend item text */ setText: function (item) { var options = this.options; item.legendItem.attr({ text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item) }); }, /** * Render a single specific legend item * @param {Object} item A series or point */ renderItem: function (item) { var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, padding = legend.padding, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, itemHeight, widthOption = options.width, itemMarginBottom = options.itemMarginBottom || 0, itemMarginTop = legend.itemMarginTop, initialItemX = legend.initialItemX, bBox, itemWidth, li = item.legendItem, series = item.series && item.series.drawLegendSymbol ? item.series : item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox, useHTML = options.useHTML; if (!li) { // generate it once, later move it // Generate the group box // A group to hold the symbol and text. Text is to be appended in Legend class. item.legendGroup = renderer.g('legend-item') .attr({ zIndex: 1 }) .add(legend.scrollGroup); // Generate the list item text and add it to the group item.legendItem = li = renderer.text( '', ltr ? symbolWidth + symbolPadding : -symbolPadding, legend.baseline || 0, useHTML ) .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021) .attr({ align: ltr ? 'left' : 'right', zIndex: 2 }) .add(item.legendGroup); // Get the baseline for the first item - the font size is equal for all if (!legend.baseline) { legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li); legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop; li.attr('y', legend.baseline); } // Draw the legend symbol inside the group box series.drawLegendSymbol(legend, item); if (legend.setItemEvents) { legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle); } // Colorize the items legend.colorizeItem(item, item.visible); // add the HTML checkbox on top if (showCheckbox) { legend.createCheckboxForItem(item); } } // Always update the text legend.setText(item); // calculate the positions for the next line bBox = li.getBBox(); itemWidth = item.checkboxOffset = options.itemWidth || item.legendItemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0); legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height); // if the item exceeds the width, start a new line if (horizontal && legend.itemX - initialItemX + itemWidth > (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) { legend.itemX = initialItemX; legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom; legend.lastLineHeight = 0; // reset for next line (#915, #3976) } // If the item exceeds the height, start a new column /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) { legend.itemY = legend.initialItemY; legend.itemX += legend.maxItemWidth; legend.maxItemWidth = 0; }*/ // Set the edge positions legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth); legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom; legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915 // cache the position of the newly generated or reordered items item._legendItemPos = [legend.itemX, legend.itemY]; // advance if (horizontal) { legend.itemX += itemWidth; } else { legend.itemY += itemMarginTop + itemHeight + itemMarginBottom; legend.lastLineHeight = itemHeight; } // the width of the widest item legend.offsetWidth = widthOption || mathMax( (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding, legend.offsetWidth ); }, /** * Get all items, which is one item per series for normal series and one item per point * for pie series. */ getAllItems: function () { var allItems = []; each(this.chart.series, function (series) { var seriesOptions = series.options; // Handle showInLegend. If the series is linked to another series, defaults to false. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) { return; } // use points or series for the legend item depending on legendType allItems = allItems.concat( series.legendItems || (seriesOptions.legendType === 'point' ? series.data : series) ); }); return allItems; }, /** * Adjust the chart margins by reserving space for the legend on only one side * of the chart. If the position is set to a corner, top or bottom is reserved * for horizontal legends and left or right for vertical ones. */ adjustMargins: function (margin, spacing) { var chart = this.chart, options = this.options, // Use the first letter of each alignment option in order to detect the side alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7 if (this.display && !options.floating) { each([ /(lth|ct|rth)/, /(rtv|rm|rbv)/, /(rbh|cb|lbh)/, /(lbv|lm|ltv)/ ], function (alignments, side) { if (alignments.test(alignment) && !defined(margin[side])) { // Now we have detected on which side of the chart we should reserve space for the legend chart[marginNames[side]] = mathMax( chart[marginNames[side]], chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] + [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] + pick(options.margin, 12) + spacing[side] ); } }); } }, /** * Render the legend. This method can be called both before and after * chart.render. If called after, it will only rearrange items instead * of creating new ones. */ render: function () { var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, legendBorderWidth = options.borderWidth, legendBackgroundColor = options.backgroundColor; legend.itemX = legend.initialItemX; legend.itemY = legend.initialItemY; legend.offsetWidth = 0; legend.lastItemY = 0; if (!legendGroup) { legend.group = legendGroup = renderer.g('legend') .attr({ zIndex: 7 }) .add(); legend.contentGroup = renderer.g() .attr({ zIndex: 1 }) // above background .add(legendGroup); legend.scrollGroup = renderer.g() .add(legend.contentGroup); } legend.renderTitle(); // add each series or point allItems = legend.getAllItems(); // sort by legendIndex stableSort(allItems, function (a, b) { return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0); }); // reversed legend if (options.reversed) { allItems.reverse(); } legend.allItems = allItems; legend.display = display = !!allItems.length; // render the items legend.lastLineHeight = 0; each(allItems, function (item) { legend.renderItem(item); }); // Get the box legendWidth = (options.width || legend.offsetWidth) + padding; legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight; legendHeight = legend.handleOverflow(legendHeight); legendHeight += padding; // Draw the border and/or background if (legendBorderWidth || legendBackgroundColor) { if (!box) { legend.box = box = renderer.rect( 0, 0, legendWidth, legendHeight, options.borderRadius, legendBorderWidth || 0 ).attr({ stroke: options.borderColor, 'stroke-width': legendBorderWidth || 0, fill: legendBackgroundColor || NONE }) .add(legendGroup) .shadow(options.shadow); box.isNew = true; } else if (legendWidth > 0 && legendHeight > 0) { box[box.isNew ? 'attr' : 'animate']( box.crisp({ width: legendWidth, height: legendHeight }) ); box.isNew = false; } // hide the border if no items box[display ? 'show' : 'hide'](); } legend.legendWidth = legendWidth; legend.legendHeight = legendHeight; // Now that the legend width and height are established, put the items in the // final position each(allItems, function (item) { legend.positionItem(item); }); // 1.x compatibility: positioning based on style /*var props = ['left', 'right', 'top', 'bottom'], prop, i = 4; while (i--) { prop = props[i]; if (options.style[prop] && options.style[prop] !== 'auto') { options[i < 2 ? 'align' : 'verticalAlign'] = prop; options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1); } }*/ if (display) { legendGroup.align(extend({ width: legendWidth, height: legendHeight }, options), true, 'spacingBox'); } if (!chart.isResizing) { this.positionCheckboxes(); } }, /** * Set up the overflow handling by adding navigation with up and down arrows below the * legend. */ handleOverflow: function (legendHeight) { var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding, maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, padding = this.padding, lastY, allItems = this.allItems, clipToHeight = function (height) { clipRect.attr({ height: height }); // useHTML if (legend.contentGroup.div) { legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)'; } }; // Adjust the height if (options.layout === 'horizontal') { spaceHeight /= 2; } if (maxHeight) { spaceHeight = mathMin(spaceHeight, maxHeight); } // Reset the legend height and adjust the clipping rectangle pages.length = 0; if (legendHeight > spaceHeight) { this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - padding, 0); this.currentPage = pick(this.currentPage, 1); this.fullHeight = legendHeight; // Fill pages with Y positions so that the top of each a legend item defines // the scroll top for each page (#2098) each(allItems, function (item, i) { var y = item._legendItemPos[1], h = mathRound(item.legendItem.getBBox().height), len = pages.length; if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) { pages.push(lastY || y); len++; } if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) { pages.push(y); } if (y !== lastY) { lastY = y; } }); // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787) if (!clipRect) { clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0); legend.contentGroup.clip(clipRect); } clipToHeight(clipHeight); // Add navigation elements if (!nav) { this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group); this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(-1, animation); }) .add(nav); this.pager = renderer.text('', 15, 10) .css(navOptions.style) .add(nav); this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize) .on('click', function () { legend.scroll(1, animation); }) .add(nav); } // Set initial position legend.scroll(0); legendHeight = spaceHeight; } else if (nav) { clipToHeight(chart.chartHeight); nav.hide(); this.scrollGroup.attr({ translateY: 1 }); this.clipHeight = 0; // #1379 } return legendHeight; }, /** * Scroll the legend by a number of pages * @param {Object} scrollBy * @param {Object} animation */ scroll: function (scrollBy, animation) { var pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, activeColor = navOptions.activeColor, inactiveColor = navOptions.inactiveColor, pager = this.pager, padding = this.padding, scrollOffset; // When resizing while looking at the last page if (currentPage > pageCount) { currentPage = pageCount; } if (currentPage > 0) { if (animation !== UNDEFINED) { setAnimation(animation, this.chart); } this.nav.attr({ translateX: padding, translateY: clipHeight + this.padding + 7 + this.titleHeight, visibility: VISIBLE }); this.up.attr({ fill: currentPage === 1 ? inactiveColor : activeColor }) .css({ cursor: currentPage === 1 ? 'default' : 'pointer' }); pager.attr({ text: currentPage + '/' + pageCount }); this.down.attr({ x: 18 + this.pager.getBBox().width, // adjust to text width fill: currentPage === pageCount ? inactiveColor : activeColor }) .css({ cursor: currentPage === pageCount ? 'default' : 'pointer' }); scrollOffset = -pages[currentPage - 1] + this.initialItemY; this.scrollGroup.animate({ translateY: scrollOffset }); this.currentPage = currentPage; this.positionCheckboxes(scrollOffset); } } }; /* * LegendSymbolMixin */ var LegendSymbolMixin = Highcharts.LegendSymbolMixin = { /** * Get the series' symbol in the legend * * @param {Object} legend The legend object * @param {Object} item The series (this) or point */ drawRectangle: function (legend, item) { var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f; item.legendSymbol = this.chart.renderer.rect( 0, legend.baseline - symbolHeight + 1, // #3988 legend.symbolWidth, symbolHeight, legend.options.symbolRadius || 0 ).attr({ zIndex: 3 }).add(item.legendGroup); }, /** * Get the series' symbol in the legend. This method should be overridable to create custom * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols. * * @param {Object} legend The legend object */ drawLineMarker: function (legend) { var options = this.options, markerOptions = options.marker, radius, legendSymbol, symbolWidth = legend.symbolWidth, renderer = this.chart.renderer, legendItemGroup = this.legendGroup, verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3), attr; // Draw the line if (options.lineWidth) { attr = { 'stroke-width': options.lineWidth }; if (options.dashStyle) { attr.dashstyle = options.dashStyle; } this.legendLine = renderer.path([ M, 0, verticalCenter, L, symbolWidth, verticalCenter ]) .attr(attr) .add(legendItemGroup); } // Draw the marker if (markerOptions && markerOptions.enabled !== false) { radius = markerOptions.radius; this.legendSymbol = legendSymbol = renderer.symbol( this.symbol, (symbolWidth / 2) - radius, verticalCenter - radius, 2 * radius, 2 * radius ) .add(legendItemGroup); legendSymbol.isMarker = true; } } }; // Workaround for #2030, horizontal legend items not displaying in IE11 Preview, // and for #2580, a similar drawing flaw in Firefox 26. // TODO: Explore if there's a general cause for this. The problem may be related // to nested group elements, as the legend item texts are within 4 group elements. if (/Trident\/7\.0/.test(userAgent) || isFirefox) { wrap(Legend.prototype, 'positionItem', function (proceed, item) { var legend = this, runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030) if (item._legendItemPos) { proceed.call(legend, item); } }; // Do it now, for export and to get checkbox placement runPositionItem(); // Do it after to work around the core issue setTimeout(runPositionItem); }); } /** * The chart class * @param {Object} options * @param {Function} callback Function to run when the chart has loaded */ var Chart = Highcharts.Chart = function () { this.init.apply(this, arguments); }; Chart.prototype = { /** * Hook for modules */ callbacks: [], /** * Initialize the chart */ init: function (userOptions, callback) { // Handle regular options var options, seriesOptions = userOptions.series; // skip merging data points to increase performance userOptions.series = null; options = merge(defaultOptions, userOptions); // do the merge options.series = userOptions.series = seriesOptions; // set back the series data this.userOptions = userOptions; var optionsChart = options.chart; // Create margin & spacing array this.margin = this.splashArray('margin', optionsChart); this.spacing = this.splashArray('spacing', optionsChart); var chartEvents = optionsChart.events; //this.runChartClick = chartEvents && !!chartEvents.click; this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom this.callback = callback; this.isResizing = 0; this.options = options; //chartTitleOptions = UNDEFINED; //chartSubtitleOptions = UNDEFINED; this.axes = []; this.series = []; this.hasCartesianSeries = optionsChart.showAxes; //this.axisOffset = UNDEFINED; //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes //this.inverted = UNDEFINED; //this.loadingShown = UNDEFINED; //this.container = UNDEFINED; //this.chartWidth = UNDEFINED; //this.chartHeight = UNDEFINED; //this.marginRight = UNDEFINED; //this.marginBottom = UNDEFINED; //this.containerWidth = UNDEFINED; //this.containerHeight = UNDEFINED; //this.oldChartWidth = UNDEFINED; //this.oldChartHeight = UNDEFINED; //this.renderTo = UNDEFINED; //this.renderToClone = UNDEFINED; //this.spacingBox = UNDEFINED //this.legend = UNDEFINED; // Elements //this.chartBackground = UNDEFINED; //this.plotBackground = UNDEFINED; //this.plotBGImage = UNDEFINED; //this.plotBorder = UNDEFINED; //this.loadingDiv = UNDEFINED; //this.loadingSpan = UNDEFINED; var chart = this, eventType; // Add the chart to the global lookup chart.index = charts.length; charts.push(chart); chartCount++; // Set up auto resize if (optionsChart.reflow !== false) { addEvent(chart, 'load', function () { chart.initReflow(); }); } // Chart event handlers if (chartEvents) { for (eventType in chartEvents) { addEvent(chart, eventType, chartEvents[eventType]); } } chart.xAxis = []; chart.yAxis = []; // Expose methods and variables chart.animation = useCanVG ? false : pick(optionsChart.animation, true); chart.pointCount = chart.colorCounter = chart.symbolCounter = 0; chart.firstRender(); }, /** * Initialize an individual series, called internally before render time */ initSeries: function (options) { var chart = this, optionsChart = chart.options.chart, type = options.type || optionsChart.type || optionsChart.defaultSeriesType, series, constr = seriesTypes[type]; // No such series type if (!constr) { error(17, true); } series = new constr(); series.init(this, options); return series; }, /** * Check whether a given point is within the plot area * * @param {Number} plotX Pixel x relative to the plot area * @param {Number} plotY Pixel y relative to the plot area * @param {Boolean} inverted Whether the chart is inverted */ isInsidePlot: function (plotX, plotY, inverted) { var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY; return x >= 0 && x <= this.plotWidth && y >= 0 && y <= this.plotHeight; }, /** * Redraw legend, axes or series based on updated data * * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ redraw: function (animation) { var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, // 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) { if (serie.options.legendType === 'point') { if (serie.updateTotals) { serie.updateTotals(); } redrawLegend = true; } } }); // handle added or removed series if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed // draw legend graphics legend.render(); chart.isDirtyLegend = false; } // reset stacks if (hasStackedSeries) { chart.getStacks(); } if (hasCartesianSeries) { if (!chart.isResizing) { // reset maxTicks chart.maxTicks = null; // set axes scales each(axes, function (axis) { axis.setScale(); }); } } chart.getMargins(); // #3098 if (hasCartesianSeries) { // If one axis is dirty, all axes must be redrawn (#792, #2169) each(axes, function (axis) { if (axis.isDirty) { isDirtyBox = true; } }); // redraw axes each(axes, function (axis) { // Fire 'afterSetExtremes' only if extremes are set var key = axis.min + ',' + axis.max; if (axis.extKey !== key) { // #821, #4452 axis.extKey = key; afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119) fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751 delete axis.eventArgs; }); } if (isDirtyBox || hasStackedSeries) { axis.redraw(); } }); } // the plot areas size has changed if (isDirtyBox) { chart.drawChartBox(); } // redraw affected series each(series, function (serie) { if (serie.isDirty && serie.visible && (!serie.isCartesian || serie.xAxis)) { // issue #153 serie.redraw(); } }); // move tooltip or reset if (pointer) { pointer.reset(true); } // redraw if canvas renderer.draw(); // fire the event fireEvent(chart, 'redraw'); // 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(); }); }, /** * 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); }); }, /** * Get the currently selected points from all series */ getSelectedPoints: function () { var points = []; each(this.series, function (serie) { points = points.concat(grep(serie.points || [], function (point) { return point.selected; })); }); return points; }, /** * Get the currently selected series */ getSelectedSeries: function () { return grep(this.series, function (serie) { return serie.selected; }); }, /** * Show the title and subtitle of the chart * * @param titleOptions {Object} New title options * @param subtitleOptions {Object} New subtitle options * */ setTitle: function (titleOptions, subtitleOptions, redraw) { var chart = this, options = chart.options, chartTitleOptions, chartSubtitleOptions; chartTitleOptions = options.title = merge(options.title, titleOptions); chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions); // add title and subtitle each([ ['title', titleOptions, chartTitleOptions], ['subtitle', subtitleOptions, chartSubtitleOptions] ], function (arr) { var name = arr[0], title = chart[name], titleOptions = arr[1], chartTitleOptions = arr[2]; if (title && titleOptions) { chart[name] = title = title.destroy(); // remove old } if (chartTitleOptions && chartTitleOptions.text && !title) { chart[name] = chart.renderer.text( chartTitleOptions.text, 0, 0, chartTitleOptions.useHTML ) .attr({ align: chartTitleOptions.align, 'class': PREFIX + name, zIndex: chartTitleOptions.zIndex || 4 }) .css(chartTitleOptions.style) .add(); } }); chart.layOutTitles(redraw); }, /** * Lay out the chart titles and cache the full offset height for use in getMargins */ layOutTitles: function (redraw) { var titleOffset = 0, title = this.title, subtitle = this.subtitle, options = this.options, titleOptions = options.title, subtitleOptions = options.subtitle, requiresDirtyBox, renderer = this.renderer, autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button if (title) { title .css({ width: (titleOptions.width || autoWidth) + PX }) .align(extend({ y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3 }, titleOptions), false, 'spacingBox'); if (!titleOptions.floating && !titleOptions.verticalAlign) { titleOffset = title.getBBox().height; } } if (subtitle) { subtitle .css({ width: (subtitleOptions.width || autoWidth) + PX }) .align(extend({ y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(subtitleOptions.style.fontSize, title).b }, subtitleOptions), false, 'spacingBox'); if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) { titleOffset = mathCeil(titleOffset + subtitle.getBBox().height); } } requiresDirtyBox = this.titleOffset !== titleOffset; this.titleOffset = titleOffset; // used in getMargins if (!this.isDirtyBox && requiresDirtyBox) { this.isDirtyBox = requiresDirtyBox; // Redraw if necessary (#2719, #2744) if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) { this.redraw(); } } }, /** * Get chart width and height according to options and container size */ getChartSize: function () { var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderToClone || chart.renderTo; // get inner width and height from jQuery (#824) if (!defined(widthOption)) { chart.containerWidth = adapterRun(renderTo, 'width'); } if (!defined(heightOption)) { chart.containerHeight = adapterRun(renderTo, 'height'); } chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460 chart.chartHeight = mathMax(0, pick(heightOption, // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7: chart.containerHeight > 19 ? chart.containerHeight : 400)); }, /** * Create a clone of the chart's renderTo div and place it outside the viewport to allow * size computation on chart.render and chart.redraw */ cloneRenderTo: function (revert) { var clone = this.renderToClone, container = this.container; // Destroy the clone and bring the container back to the real renderTo div if (revert) { if (clone) { this.renderTo.appendChild(container); discardElement(clone); delete this.renderToClone; } // Set up the clone } else { if (container && container.parentNode === this.renderTo) { this.renderTo.removeChild(container); // do not clone this } this.renderToClone = clone = this.renderTo.cloneNode(0); css(clone, { position: ABSOLUTE, top: '-9999px', display: 'block' // #833 }); if (clone.style.setProperty) { // #2631 clone.style.setProperty('display', 'block', 'important'); } doc.body.appendChild(clone); if (container) { clone.appendChild(container); } } }, /** * Get the containing element, determine the size and create the inner container * div to hold the chart */ getContainer: function () { var chart = this, container, options = chart.options, optionsChart = options.chart, chartWidth, chartHeight, renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, Ren, 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. The check for hasRendered is there // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart // attribute and the SVG contents, but not an interactive chart. So in this case, // charts[oldChartIndex] will point to the wrong chart if any (#2609). oldChartIndex = pInt(attr(renderTo, indexAttrName)); if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) { charts[oldChartIndex].destroy(); } // Make a reference to the chart from the div attr(renderTo, indexAttrName, chart.index); // remove previous chart renderTo.innerHTML = ''; // If the container doesn't have an offsetWidth, it has or is a child of a node // that has display:none. We need to temporarily move it out to a visible // state to determine the size, else the legend and tooltips won't render // properly. The allowClone option is used in sparklines as a micro optimization, // saving about 1-2 ms each chart. if (!optionsChart.skipClone && !renderTo.offsetWidth) { chart.cloneRenderTo(); } // get the width and height chart.getChartSize(); chartWidth = chart.chartWidth; chartHeight = chart.chartHeight; // create the inner container chart.container = container = createElement(DIV, { className: PREFIX + 'container' + (optionsChart.className ? ' ' + optionsChart.className : ''), id: containerId }, extend({ position: RELATIVE, overflow: HIDDEN, // needed for context menu (avoid scrollbars) and // content overflow in IE width: chartWidth + PX, height: chartHeight + PX, textAlign: 'left', lineHeight: 'normal', // #427 zIndex: 0, // #1072 '-webkit-tap-highlight-color': 'rgba(0,0,0,0)' }, optionsChart.style), chart.renderToClone || renderTo ); // cache the cursor (#1650) chart._cursor = container.style.cursor; // Initialize the renderer Ren = Highcharts[optionsChart.renderer] || Renderer; chart.renderer = new Ren( container, chartWidth, chartHeight, optionsChart.style, optionsChart.forExport, options.exporting && options.exporting.allowHTML ); if (useCanVG) { // If we need canvg library, extend and configure the renderer // to get the tracker for translating mouse events chart.renderer.create(chart, container, chartWidth, chartHeight); } // Add a reference to the charts index chart.renderer.chartIndex = chart.index; }, /** * Calculate margins by rendering axis labels in a preliminary position. Title, * subtitle and legend have already been rendered at this stage, but will be * moved into their final positions */ getMargins: function (skipAxes) { var chart = this, spacing = chart.spacing, margin = chart.margin, titleOffset = chart.titleOffset; chart.resetMargins(); // Adjust for title and subtitle if (titleOffset && !defined(margin[0])) { chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]); } // Adjust for legend chart.legend.adjustMargins(margin, spacing); // adjust for scroller if (chart.extraBottomMargin) { chart.marginBottom += chart.extraBottomMargin; } if (chart.extraTopMargin) { chart.plotTop += chart.extraTopMargin; } if (!skipAxes) { this.getAxisMargins(); } }, getAxisMargins: function () { var chart = this, axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left margin = chart.margin; // pre-render axes to get labels offset width if (chart.hasCartesianSeries) { each(chart.axes, function (axis) { if (axis.visible) { axis.getOffset(); } }); } // Add the axis offsets each(marginNames, function (m, side) { if (!defined(margin[side])) { chart[m] += axisOffset[side]; } }); chart.setChartSize(); }, /** * Resize the chart to its container if size is not explicitly set */ reflow: function (e) { var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, width = optionsChart.width || adapterRun(renderTo, 'width'), height = optionsChart.height || adapterRun(renderTo, 'height'), target = e ? e.target : win, // #805 - MooTools doesn't supply e doReflow = function () { if (chart.container) { // It may have been destroyed in the meantime (#1257) chart.setSize(width, height, false); chart.hasUserSize = null; } }; // Width and height checks for display:none. Target is doc in IE8 and Opera, // win in Firefox, Chrome and IE9. if (!chart.hasUserSize && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093 if (width !== chart.containerWidth || height !== chart.containerHeight) { clearTimeout(chart.reflowTimeout); if (e) { // Called from window.resize chart.reflowTimeout = setTimeout(doReflow, 100); } else { // Called directly (#2224) doReflow(); } } chart.containerWidth = width; chart.containerHeight = height; } }, /** * Add the event handlers necessary for auto resizing */ initReflow: function () { var chart = this, reflow = function (e) { chart.reflow(e); }; addEvent(win, 'resize', reflow); addEvent(chart, 'destroy', function () { removeEvent(win, 'resize', reflow); }); }, /** * Resize the chart to a given width and height * @param {Number} width * @param {Number} height * @param {Object|Boolean} animation */ setSize: function (width, height, animation) { var chart = this, chartWidth, chartHeight, fireEndResize, renderer = chart.renderer, globalAnimation; // 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)); } // Resize the container with the global animation applied if enabled (#2503) globalAnimation = renderer.globalAnimation; (globalAnimation ? animate : css)(chart.container, { width: chartWidth + PX, height: chartHeight + PX }, globalAnimation); chart.setChartSize(true); renderer.setSize(chartWidth, chartHeight, animation); // handle axes chart.maxTicks = null; each(chart.axes, function (axis) { axis.isDirty = true; axis.setScale(); }); // make sure non-cartesian series are also handled each(chart.series, function (serie) { serie.isDirty = true; }); chart.isDirtyLegend = true; // force legend redraw chart.isDirtyBox = true; // force redraw of plot and chart border chart.layOutTitles(); // #2857 chart.getMargins(); chart.redraw(animation); chart.oldChartHeight = null; fireEvent(chart, 'resize'); // Fire endResize and set isResizing back. If animation is disabled, fire without delay globalAnimation = renderer.globalAnimation; // Reassign it before using it, it may have changed since the top of this function. 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: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)) }; if (!skipAxes) { each(chart.axes, function (axis) { axis.setAxisSize(); axis.setAxisTranslation(); }); } }, /** * Initial margins before auto size margins are applied */ resetMargins: function () { var chart = this; each(marginNames, function (m, side) { chart[m] = pick(chart.margin[side], chart.spacing[side]); }); chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left chart.clipOffset = [0, 0, 0, 0]; }, /** * Draw the borders and backgrounds for chart and plot area */ drawChartBox: function () { var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, plotBGImage = chart.plotBGImage, chartBorderWidth = optionsChart.borderWidth || 0, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, plotBorderWidth = optionsChart.plotBorderWidth || 0, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox; // Chart area mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0); if (chartBorderWidth || chartBackgroundColor) { if (!chartBackground) { bgAttr = { fill: chartBackgroundColor || NONE }; if (chartBorderWidth) { // #980 bgAttr.stroke = optionsChart.borderColor; bgAttr['stroke-width'] = chartBorderWidth; } chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn, optionsChart.borderRadius, chartBorderWidth) .attr(bgAttr) .addClass(PREFIX + 'background') .add() .shadow(optionsChart.shadow); } else { // resize chartBackground.animate( chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn }) ); } } // Plot background if (plotBackgroundColor) { if (!plotBackground) { chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0) .attr({ fill: plotBackgroundColor }) .add() .shadow(optionsChart.plotShadow); } else { plotBackground.animate(plotBox); } } if (plotBackgroundImage) { if (!plotBGImage) { chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight) .add(); } else { plotBGImage.animate(plotBox); } } // Plot clip if (!clipRect) { chart.clipRect = renderer.clipRect(clipBox); } else { clipRect.animate({ width: clipBox.width, height: clipBox.height }); } // Plot area border if (plotBorderWidth) { if (!plotBorder) { chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth) .attr({ stroke: optionsChart.plotBorderColor, 'stroke-width': plotBorderWidth, fill: NONE, zIndex: 1 }) .add(); } else { plotBorder.animate( plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative ); } } // reset chart.isDirtyBox = false; }, /** * Detect whether a certain chart property is needed based on inspecting its options * and series. This mainly applies to the chart.invert property, and in extensions to * the chart.angular and chart.polar properties. */ propFromSeries: function () { var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value; each(['inverted', 'angular', 'polar'], function (key) { // The default series type's class klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType]; // Get the value from available chart-wide properties value = ( chart[key] || // 1. it is set before optionsChart[key] || // 2. it is set in the options (klass && klass.prototype[key]) // 3. it's default series class requires it ); // 4. Check if any the chart's series require it i = seriesOptions && seriesOptions.length; while (!value && i--) { klass = seriesTypes[seriesOptions[i].type]; if (klass && klass.prototype[key]) { value = true; } } // Set the chart property chart[key] = value; }); }, /** * Link two or more series together. This is done initially from Chart.render, * and after Chart.addSeries and Series.remove. */ linkSeries: function () { var chart = this, chartSeries = chart.series; // Reset links each(chartSeries, function (series) { series.linkedSeries.length = 0; }); // Apply new links each(chartSeries, function (series) { var linkedTo = series.options.linkedTo; if (isString(linkedTo)) { if (linkedTo === ':previous') { linkedTo = chart.series[series.index - 1]; } else { linkedTo = chart.get(linkedTo); } if (linkedTo) { linkedTo.linkedSeries.push(series); series.linkedParent = linkedTo; series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879 } } }); }, /** * Render series for the chart */ renderSeries: function () { each(this.series, function (serie) { serie.translate(); serie.render(); }); }, /** * Render labels for the chart */ renderLabels: function () { var chart = this, labels = chart.options.labels; if (labels.items) { each(labels.items, function (label) { var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12; // delete to prevent rewriting in IE delete style.left; delete style.top; chart.renderer.text( label.html, x, y ) .attr({ zIndex: 2 }) .css(style) .add(); }); } }, /** * Render all graphics for the chart */ render: function () { var chart = this, axes = chart.axes, renderer = chart.renderer, options = chart.options, tempWidth, tempHeight, redoHorizontal, redoVertical; // Title chart.setTitle(); // Legend chart.legend = new Legend(chart, options.legend); // Get stacks if (chart.getStacks) { chart.getStacks(); } // Get chart margins chart.getMargins(true); chart.setChartSize(); // Record preliminary dimensions for later comparison tempWidth = chart.plotWidth; tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels // Get margins by pre-rendering axes each(axes, function (axis) { axis.setScale(); }); chart.getAxisMargins(); // If the plot area size has changed significantly, calculate tick positions again redoHorizontal = tempWidth / chart.plotWidth > 1.1; redoVertical = tempHeight / chart.plotHeight > 1.1; if (redoHorizontal || redoVertical) { chart.maxTicks = null; // reset for second pass each(axes, function (axis) { if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) { axis.setTickInterval(true); // update to reflect the new margins } }); chart.getMargins(); // second pass to check for new labels } // Draw the borders and backgrounds chart.drawChartBox(); // Axes if (chart.hasCartesianSeries) { each(axes, function (axis) { if (axis.visible) { axis.render(); } }); } // The series if (!chart.seriesGroup) { chart.seriesGroup = renderer.g('series-group') .attr({ zIndex: 3 }) .add(); } chart.renderSeries(); // Labels chart.renderLabels(); // Credits chart.showCredits(options.credits); // Set flag chart.hasRendered = true; }, /** * Show chart credits based on config options */ showCredits: function (credits) { if (credits.enabled && !this.credits) { this.credits = this.renderer.text( credits.text, 0, 0 ) .on('click', function () { if (credits.href) { location.href = credits.href; } }) .attr({ align: credits.position.align, zIndex: 8 }) .css(credits.style) .add() .align(credits.position); } }, /** * Clean up memory usage */ destroy: function () { var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode; // fire the chart.destoy event fireEvent(chart, 'destroy'); // Delete the chart from charts lookup array charts[chart.index] = UNDEFINED; chartCount--; chart.renderTo.removeAttribute('data-highcharts-chart'); // remove events removeEvent(chart); // ==== Destroy collections: // Destroy axes i = axes.length; while (i--) { axes[i] = axes[i].destroy(); } // Destroy each series i = series.length; while (i--) { series[i] = series[i].destroy(); } // ==== Destroy chart properties: each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) { var prop = chart[name]; if (prop && prop.destroy) { chart[name] = prop.destroy(); } }); // remove container and all SVG if (container) { // can break in IE when destroyed before finished loading container.innerHTML = ''; removeEvent(container); if (parentNode) { discardElement(container); } } // clean it all up for (i in chart) { delete chart[i]; } }, /** * VML namespaces can't be added until after complete. Listening * for Perini's doScroll hack is not enough. */ isReadyToRender: function () { var chart = this; // Note: 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 if (Highcharts.Pointer) { 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) { if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600) fn.apply(chart, [chart]); } }); // Fire the load event fireEvent(chart, 'load'); // If the chart was rendered outside the top container, put it back in (#3679) chart.cloneRenderTo(true); }, /** * 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 var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = { /** * 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), i, value; for (i = 0; i < 4; ++i) { value = positions[i]; handleSlicingRoom = i < 2 || (i === 2 && /%$/.test(value)); // i == 0: centerX, relative to width // i == 1: centerY, relative to height // i == 2: size, relative to smallestSize // i == 3: innerSize, relative to size positions[i] = relativeLength(value, [plotWidth, plotHeight, smallestSize, positions[2]][i]) + (handleSlicingRoom ? slicingRoom : 0); } // innerSize cannot be larger than size (#3632) if (positions[3] > positions[2]) { positions[3] = positions[2]; } return positions; } }; /** * The Point object and prototype. Inheritable and used as base for PiePoint */ var Point = function () {}; Point.prototype = { /** * Initialize the point * @param {Object} series The series object containing this point * @param {Object} options The data in either number, array or object format */ init: function (series, options, x) { var point = this, colors; point.series = series; point.color = series.color; // #3445 point.applyOptions(options, x); point.pointAttr = {}; if (series.options.colorByPoint) { colors = series.options.colors || series.chart.options.colors; point.color = point.color || colors[series.colorCounter++]; // loop back to zero if (series.colorCounter === colors.length) { series.colorCounter = 0; } } series.chart.pointCount++; return point; }, /** * Apply the options containing the x and y data and possible some extra properties. * This is called on point init or from point.update. * * @param {Object} options */ applyOptions: function (options, x) { var point = this, series = point.series, pointValKey = series.options.pointValKey || series.pointValKey; options = Point.prototype.optionsToObject.call(this, options); // copy options directly to point extend(point, options); point.options = point.options ? extend(point.options, options) : options; // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low. if (pointValKey) { point.y = point[pointValKey]; } // 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, keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, firstItemType, i = 0, j = 0; if (typeof options === 'number' || options === null) { ret[pointArrayMap[0]] = options; } else if (isArray(options)) { // with leading x value if (!keys && options.length > valueCount) { firstItemType = typeof options[0]; if (firstItemType === 'string') { ret.name = options[0]; } else if (firstItemType === 'number') { ret.x = options[0]; } i++; } while (j < valueCount) { if (!keys || options[i] !== undefined) { // Skip undefined positions for keys ret[pointArrayMap[j]] = options[i]; } i++; j++; } } else if (typeof options === 'object') { ret = options; // This is the fastest way to detect if there are individual point dataLabels that need // to be considered in drawDataLabels. These can only occur in object configs. if (options.dataLabels) { series._hasPointLabels = true; } // Same approach as above for markers if (options.marker) { series._hasPointMarkers = true; } } return ret; }, /** * Destroy a point to clear memory. Its reference still stays in series.data. */ destroy: function () { var point = this, series = point.series, chart = series.chart, hoverPoints = chart.hoverPoints, prop; chart.pointCount--; if (hoverPoints) { point.setState(); erase(hoverPoints, point); if (!hoverPoints.length) { chart.hoverPoints = null; } } if (point === chart.hoverPoint) { point.onMouseOut(); } // remove all events if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive removeEvent(point); point.destroyElements(); } if (point.legendItem) { // pies have legend items chart.legend.destroyItem(point); } for (prop in point) { point[prop] = null; } }, /** * Destroy SVG elements associated with the point */ destroyElements: function () { var point = this, props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'], prop, i = 6; while (i--) { prop = props[i]; if (point[prop]) { point[prop] = point[prop].destroy(); } } }, /** * Return the configuration hash needed for the data label and tooltip formatters */ getLabelConfig: function () { return { x: this.category, y: this.y, color: this.color, key: this.name || this.category, series: this.series, point: this, percentage: this.percentage, total: this.total || this.stackTotal }; }, /** * Extendable method for formatting each point's tooltip line * * @return {String} A string to be concatenated in to the common tooltip text */ tooltipFormatter: function (pointFormat) { // Insert options for valueDecimals, valuePrefix, and valueSuffix var series = this.series, seriesTooltipOptions = series.tooltipOptions, valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''), valuePrefix = seriesTooltipOptions.valuePrefix || '', valueSuffix = seriesTooltipOptions.valueSuffix || ''; // Loop over the point array map and replace unformatted values with sprintf formatting markup each(series.pointArrayMap || ['y'], function (key) { key = '{point.' + key; // without the closing bracket if (valuePrefix || valueSuffix) { pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix); } pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}'); }); return format(pointFormat, { point: this, series: this.series }); }, /** * Fire an event on the Point object. 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 if (point.select) { // Could be destroyed by prior event handlers (#2911) point.select(null, event.ctrlKey || event.metaKey || event.shiftKey); } }; } fireEvent(this, eventType, eventArgs, defaultFunction); }, visible: true };/** * @classDescription The base function which all other series types inherit from. The data in the series is stored * in various arrays. * * - First, series.options.data contains all the original config options for * each point whether added by options or methods like series.addPoint. * - Next, series.data contains those values converted to points, but in case the series data length * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It * only contains the points that have been created on demand. * - Then there's series.points that contains all currently visible point objects. In case of cropping, * the cropped-away points are not part of this array. The series.points array starts at series.cropStart * compared to series.data and series.options.data. If however the series data is grouped, these can't * be correlated one to one. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points. * * @param {Object} chart * @param {Object} options */ var Series = Highcharts.Series = function () {}; Series.prototype = { isCartesian: true, type: 'line', pointClass: Point, sorted: true, // requires the data to be sorted requireSorting: true, pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'lineColor', 'stroke-width': 'lineWidth', fill: 'fillColor', r: 'radius' }, directTouch: false, axisTypes: ['xAxis', 'yAxis'], colorCounter: 0, parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData init: function (chart, options) { var series = this, eventType, events, chartSeries = chart.series, sortByIndex = function (a, b) { return pick(a.options.index, a._i) - pick(b.options.index, b._i); }; series.chart = chart; series.options = options = series.setOptions(options); // merge with plotOptions series.linkedSeries = []; // bind the axes series.bindAxes(); // set some variables extend(series, { name: options.name, state: NORMAL_STATE, pointAttr: {}, visible: options.visible !== false, // true by default selected: options.selected === true // false by default }); // special if (useCanVG) { options.animation = false; } // register event listeners events = options.events; for (eventType in events) { addEvent(series, eventType, events[eventType]); } if ( (events && events.click) || (options.point && options.point.events && options.point.events.click) || options.allowPointSelect ) { chart.runTrackerClick = true; } series.getColor(); series.getSymbol(); // Set the data each(series.parallelArrays, function (key) { series[key + 'Data'] = []; }); series.setData(options.data, false); // Mark cartesian if (series.isCartesian) { chart.hasCartesianSeries = true; } // Register it in the chart chartSeries.push(series); series._i = chartSeries.length - 1; // Sort series according to index option (#248, #1123, #2456) stableSort(chartSeries, sortByIndex); if (this.yAxis) { stableSort(this.yAxis.series, sortByIndex); } each(chartSeries, function (series, i) { series.index = i; series.name = series.name || 'Series ' + (i + 1); }); }, /** * Set the xAxis and yAxis properties of cartesian series, and register the series * in the axis.series array */ bindAxes: function () { var series = this, seriesOptions = series.options, chart = series.chart, axisOptions; each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis each(chart[AXIS], function (axis) { // loop through the chart's axis objects axisOptions = axis.options; // apply if the series xAxis or yAxis option mathches the number of the // axis, or if undefined, use the first axis if ((seriesOptions[AXIS] === axisOptions.index) || (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) || (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) { // register this series in the axis.series lookup axis.series.push(series); // set this series.xAxis or series.yAxis reference series[AXIS] = axis; // mark dirty for redraw axis.isDirty = true; } }); // The series needs an X and an Y axis if (!series[AXIS] && series.optionalAxis !== AXIS) { error(18, true); } }); }, /** * For simple series types like line and column, the data values are held in arrays like * xData and yData for quick lookup to find extremes and more. For multidimensional series * like bubble and map, this can be extended with arrays like zData and valueData by * adding to the series.parallelArrays array. */ updateParallelArrays: function (point, i) { var series = point.series, args = arguments, fn = typeof i === 'number' ? // Insert the value in the given position function (key) { var val = key === 'y' && series.toYData ? series.toYData(point) : point[key]; series[key + 'Data'][i] = val; } : // Apply the method specified in i with the following arguments as arguments function (key) { Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2)); }; each(series.parallelArrays, fn); }, /** * Return an auto incremented x value based on the pointStart and pointInterval options. * This is only used if an x value is not given for the point that calls autoIncrement. */ autoIncrement: function () { var options = this.options, xIncrement = this.xIncrement, date, pointInterval, pointIntervalUnit = options.pointIntervalUnit; xIncrement = pick(xIncrement, options.pointStart, 0); this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1); // Added code for pointInterval strings if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') { date = new Date(xIncrement); date = (pointIntervalUnit === 'month') ? +date[setMonth](date[getMonth]() + pointInterval) : +date[setFullYear](date[getFullYear]() + pointInterval); pointInterval = date - xIncrement; } this.xIncrement = xIncrement + pointInterval; return xIncrement; }, /** * 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, userOptions = chart.userOptions || {}, userPlotOptions = userOptions.plotOptions || {}, typeOptions = plotOptions[this.type], options, zones; this.userOptions = itemOptions; // General series options take precedence over type options because otherwise, default // type options like column.animation would be overwritten by the general option. // But issues have been raised here (#3881), and the solution may be to distinguish // between default option and userOptions like in the tooltip below. options = merge( typeOptions, plotOptions.series, itemOptions ); // The tooltip options are merged between global and series specific options this.tooltipOptions = merge( defaultOptions.tooltip, defaultOptions.plotOptions[this.type].tooltip, userOptions.tooltip, userPlotOptions.series && userPlotOptions.series.tooltip, userPlotOptions[this.type] && userPlotOptions[this.type].tooltip, itemOptions.tooltip ); // Delete marker object if not allowed (#1125) if (typeOptions.marker === null) { delete options.marker; } // Handle color zones this.zoneAxis = options.zoneAxis; zones = this.zones = (options.zones || []).slice(); if ((options.negativeColor || options.negativeFillColor) && !options.zones) { zones.push({ value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0, color: options.negativeColor, fillColor: options.negativeFillColor }); } if (zones.length) { // Push one extra zone for the rest if (defined(zones[zones.length - 1].value)) { zones.push({ color: this.color, fillColor: this.fillColor }); } } return options; }, getCyclic: function (prop, value, defaults) { var i, userOptions = this.userOptions, indexName = '_' + prop + 'Index', counterName = prop + 'Counter'; if (!value) { if (defined(userOptions[indexName])) { // after Series.update() i = userOptions[indexName]; } else { userOptions[indexName] = i = this.chart[counterName] % defaults.length; this.chart[counterName] += 1; } value = defaults[i]; } this[prop] = value; }, /** * Get the series' color */ getColor: function () { if (this.options.colorByPoint) { this.options.color = null; // #4359, selected slice got series.color even when colorByPoint was set. } else { this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors); } }, /** * Get the series' symbol */ getSymbol: function () { var seriesMarkerOption = this.options.marker; this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols); // don't substract radius in image symbols (#604) if (/^url/.test(this.symbol)) { seriesMarkerOption.radius = 0; } }, drawLegendSymbol: LegendSymbolMixin.drawLineMarker, /** * Replace the series data with a new set of data * @param {Object} data * @param {Object} redraw */ setData: function (data, redraw, animation, updatePoints) { var series = this, oldData = series.points, oldDataLength = (oldData && oldData.length) || 0, dataLength, options = series.options, chart = series.chart, firstPoint = null, xAxis = series.xAxis, hasCategories = xAxis && !!xAxis.categories, i, turboThreshold = options.turboThreshold, pt, xData = this.xData, yData = this.yData, pointArrayMap = series.pointArrayMap, valueCount = pointArrayMap && pointArrayMap.length; data = data || []; dataLength = data.length; redraw = pick(redraw, true); // If the point count is the same as is was, just run Point.update which is // cheaper, allows animation, and keeps references to points. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) { each(data, function (point, i) { if (oldData[i].update) { // Linked, previously hidden series (#3709) oldData[i].update(point, false, null, false); } }); } else { // Reset properties series.xIncrement = null; series.pointRange = hasCategories ? 1 : options.pointRange; series.colorCounter = 0; // for series with colorByPoint (#1547) // Update parallel arrays each(this.parallelArrays, function (key) { series[key + 'Data'].length = 0; }); // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The // first value is tested, and we assume that all the rest are defined the same // way. Although the 'for' loops are similar, they are repeated inside each // if-else conditional for max performance. if (turboThreshold && dataLength > turboThreshold) { // find the first non-null point i = 0; while (firstPoint === null && i < dataLength) { firstPoint = data[i]; i++; } if (isNumber(firstPoint)) { // assume all points are numbers var x = pick(options.pointStart, 0), pointInterval = pick(options.pointInterval, 1); for (i = 0; i < dataLength; i++) { xData[i] = x; yData[i] = data[i]; x += pointInterval; } series.xIncrement = x; } else if (isArray(firstPoint)) { // assume all points are arrays if (valueCount) { // [x, low, high] or [x, o, h, l, c] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt.slice(1, valueCount + 1); } } else { // [x, y] for (i = 0; i < dataLength; i++) { pt = data[i]; xData[i] = pt[0]; yData[i] = pt[1]; } } } else { error(12); // Highcharts expects configs to be numbers or arrays in turbo mode } } else { for (i = 0; i < dataLength; i++) { if (data[i] !== UNDEFINED) { // stray commas in oldIE pt = { series: series }; series.pointClass.prototype.applyOptions.apply(pt, [data[i]]); series.updateParallelArrays(pt, i); if (hasCategories && defined(pt.name)) { // #4401 xAxis.names[pt.x] = pt.name; // #2046 } } } } // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON if (isString(yData[0])) { error(14, true); } series.data = []; series.options.data = data; //series.zData = zData; // destroy old points i = oldDataLength; while (i--) { if (oldData[i] && oldData[i].destroy) { oldData[i].destroy(); } } // reset minRange (#878) if (xAxis) { xAxis.minRange = xAxis.userMinRange; } // redraw series.isDirty = series.isDirtyData = chart.isDirtyBox = true; animation = false; } // Typically for pie series, points need to be processed and generated // prior to rendering the legend if (options.legendType === 'point') { // docs: legendType now supported on more series types (at least column and pie) this.processData(); this.generatePoints(); } if (redraw) { chart.redraw(animation); } }, /** * Process the data by cropping away unused data points if the series is longer * than the crop threshold. This saves computing time for lage series. */ processData: function (force) { var series = this, processedXData = series.xData, // copied during slice operation below processedYData = series.yData, dataLength = processedXData.length, croppedData, cropStart = 0, cropped, distance, closestPointRange, xAxis = series.xAxis, i, // loop variable options = series.options, cropThreshold = options.cropThreshold, getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599 isCartesian = series.isCartesian, xExtremes, min, max; // If the series data or axes haven't changed, don't go through this. Return false to pass // the message on to override methods like in data grouping. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) { return false; } if (xAxis) { xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053) min = xExtremes.min; max = xExtremes.max; } // optionally filter out points outside the plot area if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) { // it's outside current extremes if (processedXData[dataLength - 1] < min || processedXData[0] > max) { processedXData = []; processedYData = []; // only crop if it's actually spilling out } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) { croppedData = this.cropData(series.xData, series.yData, min, max); processedXData = croppedData.xData; processedYData = croppedData.yData; cropStart = croppedData.start; cropped = true; } } // Find the closest distance between processed points 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]))); } points[i].index = cursor; // For faster access in Point.update } // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when // swithching view from non-grouped data to grouped data (#637) if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) { for (i = 0; i < dataLength; i++) { if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points i += processedDataLength; } if (data[i]) { data[i].destroyElements(); data[i].plotX = UNDEFINED; // #1003 } } } series.data = data; series.points = points; }, /** * Calculate Y extremes for visible data */ getExtremes: function (yData) { var xAxis = this.xAxis, yAxis = this.yAxis, xData = this.processedXData, yDataLength, activeYData = [], activeCounter = 0, xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis xMin = xExtremes.min, xMax = xExtremes.max, validValue, withinRange, x, y, i, j; yData = yData || this.stackedYData || this.processedYData; yDataLength = yData.length; for (i = 0; i < yDataLength; i++) { x = xData[i]; y = yData[i]; // For points within the visible range, including the first point outside the // visible range, consider y extremes validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0)); withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax); if (validValue && withinRange) { j = y.length; if (j) { // array, like ohlc or range data while (j--) { if (y[j] !== null) { activeYData[activeCounter++] = y[j]; } } } else { activeYData[activeCounter++] = y; } } } this.dataMin = arrayMin(activeYData); this.dataMax = arrayMax(activeYData); }, /** * Translate data points from raw data values to chart specific positioning data * needed later in drawPoints, drawGraph and drawTracker. */ translate: function () { if (!this.processedXData) { // hidden series this.processData(); } this.generatePoints(); var series = this, options = series.options, stacking = options.stacking, xAxis = series.xAxis, categories = xAxis.categories, yAxis = series.yAxis, points = series.points, dataLength = points.length, hasModifyValue = !!series.modifyValue, i, pointPlacement = options.pointPlacement, dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement), threshold = options.threshold, stackThreshold = options.startFromThreshold ? threshold : 0, plotX, plotY, lastPlotX, stackIndicator, closestPointRangePx = Number.MAX_VALUE; // Translate each point for (i = 0; i < dataLength; i++) { var point = points[i], xValue = point.x, yValue = point.y, yBottom = point.low, stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey], pointStack, stackValues; // Discard disallowed y values for log axes (#3434) if (yAxis.isLog && yValue !== null && yValue <= 0) { point.y = yValue = null; error(10); } // Get the plotX translation point.plotX = plotX = mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5); // #3923 // Calculate the bottom y value for stacked series if (stacking && series.visible && stack && stack[xValue]) { stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index); pointStack = stack[xValue]; stackValues = pointStack.points[stackIndicator.key]; yBottom = stackValues[0]; yValue = stackValues[1]; if (yBottom === stackThreshold) { yBottom = pick(threshold, yAxis.min); } if (yAxis.isLog && yBottom <= 0) { // #1200, #1232 yBottom = null; } point.total = point.stackTotal = pointStack.total; point.percentage = pointStack.total && (point.y / pointStack.total * 100); point.stackY = yValue; // Place the stack label pointStack.setOffset(series.pointXOffset || 0, series.barW || 0); } // Set translated yBottom or remove it point.yBottom = defined(yBottom) ? yAxis.translate(yBottom, 0, 1, 0, 1) : null; // general hook, used for Highstock compare mode if (hasModifyValue) { yValue = series.modifyValue(yValue, point); } // Set the the plotY value, reset it for redraws point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ? mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201 UNDEFINED; point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519 plotX >= 0 && plotX <= xAxis.len; // Set client related positions for mouse tracking point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514 point.negative = point.y < (threshold || 0); // some API data point.category = categories && categories[point.x] !== UNDEFINED ? categories[point.x] : point.x; // Determine auto enabling of markers (#3635) if (i) { closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX)); } lastPlotX = plotX; } series.closestPointRangePx = closestPointRangePx; // now that we have the cropped data, build the segments series.getSegments(); }, /** * Set the clipping for the series. For animated series it is called twice, first to initiate * animating the clip then the second time without the animation to set the final clip. */ setClip: function (animation) { var chart = this.chart, options = this.options, renderer = chart.renderer, inverted = chart.inverted, seriesClipBox = this.clipBox, clipBox = seriesClipBox || chart.clipBox, sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526 clipRect = chart[sharedClipKey], markerClipRect = chart[sharedClipKey + 'm']; // If a clipping rectangle with the same properties is currently present in the chart, use that. if (!clipRect) { // When animation is set, prepare the initial positions if (animation) { clipBox.width = 0; chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect( -99, // include the width of the first marker inverted ? -chart.plotLeft : -chart.plotTop, 99, inverted ? chart.chartWidth : chart.chartHeight ); } chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox); } if (animation) { clipRect.count += 1; } if (options.clip !== false) { this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect); this.markerGroup.clip(markerClipRect); this.sharedClipKey = sharedClipKey; } // Remove the shared clipping rectangle when all series are shown if (!animation) { clipRect.count -= 1; if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) { if (!seriesClipBox) { chart[sharedClipKey] = chart[sharedClipKey].destroy(); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy(); } } } }, /** * Animate in the series */ animate: function (init) { var series = this, chart = series.chart, clipRect, animation = series.options.animation, sharedClipKey; // Animation option is set to true if (animation && !isObject(animation)) { animation = defaultPlotOptions[series.type].animation; } // Initialize the animation. Set up the clipping rectangle. if (init) { series.setClip(animation); // Run the animation } else { sharedClipKey = this.sharedClipKey; clipRect = chart[sharedClipKey]; if (clipRect) { clipRect.animate({ width: chart.plotSizeX }, animation); } if (chart[sharedClipKey + 'm']) { chart[sharedClipKey + 'm'].animate({ width: chart.plotSizeX + 99 }, animation); } // Delete this function to allow it only once series.animate = null; } }, /** * This runs after animation to land on the final plot clipping */ afterAnimate: function () { this.setClip(); fireEvent(this, 'afterAnimate'); }, /** * Draw the markers */ drawPoints: function () { var series = this, pointAttr, points = series.points, chart = series.chart, plotX, plotY, i, point, radius, symbol, isImage, graphic, options = series.options, seriesMarkerOptions = options.marker, seriesPointAttr = series.pointAttr[''], pointMarkerOptions, hasPointMarker, enabled, isInside, markerGroup = series.markerGroup, xAxis = series.xAxis, globallyEnabled = pick( seriesMarkerOptions.enabled, xAxis.isRadial, series.closestPointRangePx > 2 * seriesMarkerOptions.radius ); if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) { i = points.length; while (i--) { point = points[i]; plotX = mathFloor(point.plotX); // #1843 plotY = point.plotY; graphic = point.graphic; pointMarkerOptions = point.marker || {}; hasPointMarker = !!point.marker; enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled; isInside = point.isInside; // only draw the point if y is defined if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { // shortcuts pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr; radius = pointAttr.r; symbol = pick(pointMarkerOptions.symbol, series.symbol); isImage = symbol.indexOf('url') === 0; if (graphic) { // update graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled .animate(extend({ x: plotX - radius, y: plotY - radius }, graphic.symbolName ? { // don't apply to image symbols #507 width: 2 * radius, height: 2 * radius } : {})); } else if (isInside && (radius > 0 || isImage)) { point.graphic = graphic = chart.renderer.symbol( symbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius, hasPointMarker ? pointMarkerOptions : seriesMarkerOptions ) .attr(pointAttr) .add(markerGroup); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } } } }, /** * Convert state properties from API naming conventions to SVG attributes * * @param {Object} options API options object * @param {Object} base1 SVG attribute object to inherit from * @param {Object} base2 Second level SVG attribute object to inherit from */ convertAttribs: function (options, base1, base2, base3) { var conversion = this.pointAttrToOptions, attr, option, obj = {}; options = options || {}; base1 = base1 || {}; base2 = base2 || {}; base3 = base3 || {}; for (attr in conversion) { option = conversion[attr]; obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]); } return obj; }, /** * Get the state attributes. Each series type has its own set of attributes * that are allowed to change on a point's state change. Series wide attributes are stored for * all series, and additionally point specific attributes are stored for all * points with individual marker options. If such options are not defined for the point, * a reference to the series wide attributes is stored in point.pointAttr. */ getAttribs: function () { var series = this, seriesOptions = series.options, normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions, stateOptions = normalOptions.states, stateOptionsHover = stateOptions[HOVER_STATE], pointStateOptionsHover, seriesColor = series.color, seriesNegativeColor = series.options.negativeColor, normalDefaults = { stroke: seriesColor, fill: seriesColor }, points = series.points || [], // #927 i, j, threshold, point, seriesPointAttr = [], pointAttr, pointAttrToOptions = series.pointAttrToOptions, hasPointSpecificOptions = series.hasPointSpecificOptions, defaultLineColor = normalOptions.lineColor, defaultFillColor = normalOptions.fillColor, turboThreshold = seriesOptions.turboThreshold, zones = series.zones, zoneAxis = series.zoneAxis || 'y', attr, key; // series type specific modifications if (seriesOptions.marker) { // line, spline, area, areaspline, scatter // if no hover radius is given, default to normal radius + 2 stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus; stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus; } else { // column, bar, pie // if no hover color is given, brighten the normal color stateOptionsHover.color = stateOptionsHover.color || Color(stateOptionsHover.color || seriesColor) .brighten(stateOptionsHover.brightness).get(); // if no hover negativeColor is given, brighten the normal negativeColor stateOptionsHover.negativeColor = stateOptionsHover.negativeColor || Color(stateOptionsHover.negativeColor || seriesNegativeColor) .brighten(stateOptionsHover.brightness).get(); } // general point attributes for the series normal state seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults); // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius each([HOVER_STATE, SELECT_STATE], function (state) { seriesPointAttr[state] = series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]); }); // set it series.pointAttr = seriesPointAttr; // Generate the point-specific attribute collections if specific point // options are given. If not, create a referance to the series wide point // attributes i = points.length; if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) { while (i--) { point = points[i]; normalOptions = (point.options && point.options.marker) || point.options; if (normalOptions && normalOptions.enabled === false) { normalOptions.radius = 0; } if (zones.length) { j = 0; threshold = zones[j]; while (point[zoneAxis] >= threshold.value) { threshold = zones[++j]; } point.color = point.fillColor = pick(threshold.color, series.color); // #3636, #4267, #4430 - inherit color from series, when color is undefined } hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868 // check if the point has specific visual options if (point.options) { for (key in pointAttrToOptions) { if (defined(normalOptions[pointAttrToOptions[key]])) { hasPointSpecificOptions = true; } } } // a specific marker config object is defined for the individual point: // create it's own attribute collection if (hasPointSpecificOptions) { normalOptions = normalOptions || {}; pointAttr = []; stateOptions = normalOptions.states || {}; // reassign for individual point pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {}; // Handle colors for column and pies if (!seriesOptions.marker || (point.negative && !pointStateOptionsHover.fillColor && !stateOptionsHover.fillColor)) { // column, bar, point or negative threshold for series with markers (#3636) // If no hover color is given, brighten the normal color. #1619, #2579 pointStateOptionsHover[series.pointAttrToOptions.fill] = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) || Color(point.color) .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness) .get(); } // normal point state inherits series wide normal state attr = { color: point.color }; // #868 if (!defaultFillColor) { // Individual point color or negative color markers (#2219) attr.fillColor = point.color; } if (!defaultLineColor) { attr.lineColor = point.color; // Bubbles take point color, line markers use white } // Color is explicitly set to null or undefined (#1288, #4068) if (normalOptions.hasOwnProperty('color') && !normalOptions.color) { delete normalOptions.color; } pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]); // inherit from point normal and series hover pointAttr[HOVER_STATE] = series.convertAttribs( stateOptions[HOVER_STATE], seriesPointAttr[HOVER_STATE], pointAttr[NORMAL_STATE] ); // inherit from point normal and series hover pointAttr[SELECT_STATE] = series.convertAttribs( stateOptions[SELECT_STATE], seriesPointAttr[SELECT_STATE], pointAttr[NORMAL_STATE] ); // no marker config object is created: copy a reference to the series-wide // attribute collection } else { pointAttr = seriesPointAttr; } point.pointAttr = pointAttr; } } }, /** * Clear DOM objects and free up memory */ destroy: function () { var series = this, chart = series.chart, issue134 = /AppleWebKit\/533/.test(userAgent), destroy, i, data = series.data || [], point, prop, axis; // add event hook fireEvent(series, 'destroy'); // remove all events removeEvent(series); // erase from axes each(series.axisTypes || [], function (AXIS) { axis = series[AXIS]; if (axis) { erase(axis.series, series); axis.isDirty = axis.forceRedraw = true; } }); // remove legend items if (series.legendItem) { series.chart.legend.destroyItem(series); } // destroy all points with their elements i = data.length; while (i--) { point = data[i]; if (point && point.destroy) { point.destroy(); } } series.points = null; // Clear the animation timeout if we are destroying the series during initial animation clearTimeout(series.animationTimeout); // Destroy all SVGElements associated to the series for (prop in series) { if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying // issue 134 workaround destroy = issue134 && prop === 'group' ? 'hide' : 'destroy'; series[prop][destroy](); } } // remove from hoverSeries if (chart.hoverSeries === series) { chart.hoverSeries = null; } erase(chart.series, series); // clear all members for (prop in series) { delete series[prop]; } }, /** * 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, L ); } else if (step === 'center') { segmentPath.push( (lastPoint.plotX + plotX) / 2, lastPoint.plotY, L, (lastPoint.plotX + plotX) / 2, plotY, L ); } else { segmentPath.push( plotX, lastPoint.plotY, L ); } } // 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, options.dashStyle]], lineWidth = options.lineWidth, roundCap = options.linecap !== 'square', graphPath = this.getGraphPath(), fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph zones = this.zones; each(zones, function (threshold, i) { props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]); }); // Draw the graph each(props, function (prop, i) { var graphKey = prop[0], graph = series[graphKey], attribs; if (graph) { graph.animate({ d: graphPath }); } else if ((lineWidth || fillColor) && graphPath.length) { // #1487 attribs = { stroke: prop[1], 'stroke-width': lineWidth, fill: fillColor, zIndex: 1 // #1069 }; if (prop[2]) { attribs.dashstyle = prop[2]; } else if (roundCap) { attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round'; } series[graphKey] = series.chart.renderer.path(graphPath) .attr(attribs) .add(series.group) .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932 } }); }, /** * Clip the graphs into the positive and negative coloured graphs */ applyZones: function () { var series = this, chart = this.chart, renderer = chart.renderer, zones = this.zones, translatedFrom, translatedTo, clips = this.clips || [], clipAttr, graph = this.graph, area = this.area, chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight), axis = this[(this.zoneAxis || 'y') + 'Axis'], extremes, reversed = axis.reversed, inverted = chart.inverted, horiz = axis.horiz, pxRange, pxPosMin, pxPosMax, ignoreZones = false; if (zones.length && (graph || area) && axis.min !== UNDEFINED) { // The use of the Color Threshold assumes there are no gaps // so it is safe to hide the original graph and area if (graph) { graph.hide(); } if (area) { area.hide(); } // Create the clips extremes = axis.getExtremes(); each(zones, function (threshold, i) { translatedFrom = reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(extremes.min)); translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax); translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax); if (ignoreZones) { translatedFrom = translatedTo = axis.toPixels(extremes.max); } pxRange = Math.abs(translatedFrom - translatedTo); pxPosMin = mathMin(translatedFrom, translatedTo); pxPosMax = mathMax(translatedFrom, translatedTo); if (axis.isXAxis) { clipAttr = { x: inverted ? pxPosMax : pxPosMin, y: 0, width: pxRange, height: chartSizeMax }; if (!horiz) { clipAttr.x = chart.plotHeight - clipAttr.x; } } else { clipAttr = { x: 0, y: inverted ? pxPosMax : pxPosMin, width: chartSizeMax, height: pxRange }; if (horiz) { clipAttr.y = chart.plotWidth - clipAttr.y; } } /// VML SUPPPORT if (chart.inverted && renderer.isVML) { if (axis.isXAxis) { clipAttr = { x: 0, y: reversed ? pxPosMin : pxPosMax, height: clipAttr.width, width: chart.chartWidth }; } else { clipAttr = { x: clipAttr.y - chart.plotLeft - chart.spacingBox.x, y: 0, width: clipAttr.height, height: chart.chartHeight }; } } /// END OF VML SUPPORT if (clips[i]) { clips[i].animate(clipAttr); } else { clips[i] = renderer.clipRect(clipAttr); if (graph) { series['zoneGraph' + i].clip(clips[i]); } if (area) { series['zoneArea' + i].clip(clips[i]); } } // if this zone extends out of the axis, ignore the others ignoreZones = threshold.value > extremes.max; }); this.clips = clips; } }, /** * Initialize and perform group inversion on series.group and series.markerGroup */ invertGroups: function () { var series = this, chart = series.chart; // Pie, go away (#1736) if (!series.xAxis) { return; } // A fixed size is needed for inversion to work function setInvert() { var size = { width: series.yAxis.len, height: series.xAxis.len }; each(['group', 'markerGroup'], function (groupName) { if (series[groupName]) { series[groupName].attr(size).invert(); } }); } addEvent(chart, 'resize', setInvert); // do it on resize addEvent(series, 'destroy', function () { removeEvent(chart, 'resize', setInvert); }); // Do it now setInvert(); // do it now // On subsequent render and redraw, just do setInvert without setting up events again series.invertGroups = setInvert; }, /** * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size. */ plotGroup: function (prop, name, visibility, zIndex, parent) { var group = this[prop], isNew = !group; // Generate it on first call if (isNew) { this[prop] = group = this.chart.renderer.g(name) .attr({ visibility: visibility, zIndex: zIndex || 0.1 // IE8 needs this }) .add(parent); group.addClass('highcharts-series-' + this.index); } // 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 () { var chart = this.chart, xAxis = this.xAxis, yAxis = this.yAxis; // Swap axes for inverted (#2339) if (chart.inverted) { xAxis = yAxis; yAxis = this.xAxis; } return { translateX: xAxis ? xAxis.left : chart.plotLeft, translateY: yAxis ? yAxis.top : chart.plotTop, scaleX: 1, // #1623 scaleY: 1 }; }, /** * Render the graph and markers */ render: function () { var series = this, chart = series.chart, group, options = series.options, animation = options.animation, // Animation doesn't work in IE8 quirks when the group div is hidden, // and looks bad in other oldIE animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0, visibility = series.visible ? 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 (animDuration) { series.animate(true); } // cache attributes for shapes series.getAttribs(); // SVGRenderer needs to know this before drawing elements (#1089, #1795) group.inverted = series.isCartesian ? chart.inverted : false; // draw the graph if any if (series.drawGraph) { series.drawGraph(); series.applyZones(); } each(series.points, function (point) { if (point.redraw) { point.redraw(); } }); // draw the data labels (inn pies they go before the points) if (series.drawDataLabels) { series.drawDataLabels(); } // draw the points if (series.visible) { series.drawPoints(); } // draw the mouse tracking area if (series.drawTracker && series.options.enableMouseTracking !== false) { series.drawTracker(); } // Handle inverted series and tracker groups if (chart.inverted) { series.invertGroups(); } // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839). if (options.clip !== false && !series.sharedClipKey && !hasRendered) { group.clip(chart.clipRect); } // Run the animation if (animDuration) { series.animate(); } // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option // which should be available to the user). if (!hasRendered) { if (animDuration) { series.animationTimeout = setTimeout(function () { series.afterAnimate(); }, animDuration); } else { 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 wasDirty = series.isDirty, group = series.group, xAxis = series.xAxis, yAxis = series.yAxis; // reposition on resize if (group) { if (chart.inverted) { group.attr({ width: chart.plotWidth, height: chart.plotHeight }); } group.animate({ translateX: pick(xAxis && xAxis.left, chart.plotLeft), translateY: pick(yAxis && yAxis.top, chart.plotTop) }); } series.translate(); series.render(); if (wasDirtyData) { fireEvent(series, 'updatedData'); } if (wasDirty || wasDirtyData) { // #3945 recalculate the kdtree when dirty delete this.kdTree; // #3868 recalculate the kdtree with dirty data } }, /** * KD Tree && PointSearching Implementation */ kdDimensions: 1, kdAxisArray: ['clientX', 'plotY'], searchPoint: function (e, compareX) { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, inverted = series.chart.inverted; return this.searchKDTree({ clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos, plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos }, compareX); }, buildKDTree: function () { var series = this, dimensions = series.kdDimensions; // Internal function function _kdtree(points, depth, dimensions) { var axis, median, length = points && points.length; if (length) { // alternate between the axis axis = series.kdAxisArray[depth % dimensions]; // sort point array points.sort(function(a, b) { return a[axis] - b[axis]; }); median = Math.floor(length / 2); // build and return nod return { point: points[median], left: _kdtree(points.slice(0, median), depth + 1, dimensions), right: _kdtree(points.slice(median + 1), depth + 1, dimensions) }; } } // Start the recursive build process with a clone of the points array and null points filtered out (#3873) function startRecursive() { var points = grep(series.points || [], function (point) { // #4390 return point.y !== null; }); series.kdTree = _kdtree(points, dimensions, dimensions); } delete series.kdTree; if (series.options.kdSync) { // For testing tooltips, don't build async startRecursive(); } else { setTimeout(startRecursive); } }, searchKDTree: function (point, compareX) { var series = this, kdX = this.kdAxisArray[0], kdY = this.kdAxisArray[1], kdComparer = compareX ? 'distX' : 'dist'; // Set the one and two dimensional distance on the point object function setDistance(p1, p2) { var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null, y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null, r = (x || 0) + (y || 0); p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE; p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE; } function _search(search, tree, depth, dimensions) { var point = tree.point, axis = series.kdAxisArray[depth % dimensions], tdist, sideA, sideB, ret = point, nPoint1, nPoint2; setDistance(search, point); // Pick side based on distance to splitting point tdist = search[axis] - point[axis]; sideA = tdist < 0 ? 'left' : 'right'; sideB = tdist < 0 ? 'right' : 'left'; // End of tree if (tree[sideA]) { nPoint1 =_search(search, tree[sideA], depth + 1, dimensions); ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point); } if (tree[sideB]) { // compare distance to current best to splitting point to decide wether to check side B or not if (Math.sqrt(tdist * tdist) < ret[kdComparer]) { nPoint2 = _search(search, tree[sideB], depth + 1, dimensions); ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret); } } return ret; } if (!this.kdTree) { this.buildKDTree(); } if (this.kdTree) { return _search(point, this.kdTree, this.kdDimensions, this.kdDimensions); } } }; // end Series prototype /** * The class for stack items */ function StackItem(axis, options, isNegative, x, stackOption) { 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 and point index this.points = {}; // Save the stack option on the series configuration object, and whether to treat it as percent this.stack = stackOption; // 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, null, null, 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, reversed = axis.reversed, neg = (this.isNegative && !reversed) || (!this.isNegative && reversed), // #4056 y = axis.translate(axis.usePercentage ? 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[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true); } } }; /** * Generate stacks for each series and calculate stacks total values */ Chart.prototype.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, ''); } }); }; // Stacking methods defined on the Axis prototype /** * Build the stacks from top down */ Axis.prototype.buildStacks = function () { var series = this.series, reversedStacks = pick(this.options.reversedStacks, true), i = series.length; if (!this.isXAxis) { this.usePercentage = false; while (i--) { series[reversedStacks ? i : series.length - i - 1].setStackedPoints(); } // Loop up again to compute percent stack if (this.usePercentage) { for (i = 0; i < series.length; i++) { series[i].setPercentStacks(); } } } }; Axis.prototype.renderStackTotals = function () { var axis = this, chart = axis.chart, renderer = chart.renderer, stacks = axis.stacks, 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); } } }; /** * Set all the stacks to initial states and destroy unused ones. */ Axis.prototype.resetStacks = function () { var stacks = this.stacks, type, i; if (!this.isXAxis) { for (type in stacks) { for (i in stacks[type]) { // Clean up memory after point deletion (#1044, #4320) if (stacks[type][i].touched < this.stacksTouched) { stacks[type][i].destroy(); delete stacks[type][i]; // Reset stacks } else { stacks[type][i].total = null; stacks[type][i].cum = 0; } } } } }; Axis.prototype.cleanStacks = function () { var stacks, type, i; if (!this.isXAxis) { if (this.oldStacks) { stacks = this.stacks = this.oldStacks; } // reset stacks for (type in stacks) { for (i in stacks[type]) { stacks[type][i].cum = stacks[type][i].total; } } } }; // Stacking methods defnied for Series prototype /** * Adds series' points value to corresponding stack */ Series.prototype.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, stackThreshold = seriesOptions.startFromThreshold ? threshold : 0, stackOption = seriesOptions.stack, stacking = seriesOptions.stacking, stackKey = series.stackKey, negKey = '-' + stackKey, negStacks = series.negStacks, yAxis = series.yAxis, stacks = yAxis.stacks, oldStacks = yAxis.oldStacks, stackIndicator, isNegative, stack, other, key, pointKey, i, x, y; yAxis.stacksTouched += 1; // 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]; stackIndicator = series.getStackIndicator(stackIndicator, x, series.index); pointKey = stackIndicator.key; // 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 < (stackThreshold ? 0 : 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); } } // If the StackItem doesn't exist, create it first stack = stacks[key][x]; //stack.points[pointKey] = [stack.cum || stackThreshold]; stack.points[pointKey] = [pick(stack.cum, stackThreshold)]; stack.touched = yAxis.stacksTouched; // 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 = correctFloat(stack.total + (mathAbs(y) || 0)); } } else { stack.total = correctFloat(stack.total + (y || 0)); } stack.cum = pick(stack.cum, stackThreshold) + (y || 0); stack.points[pointKey].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 */ Series.prototype.setPercentStacks = function () { var series = this, stackKey = series.stackKey, stacks = series.yAxis.stacks, processedXData = series.processedXData, stackIndicator; each([stackKey, '-' + stackKey], function (key) { var i = processedXData.length, x, stack, pointExtremes, totalFactor; while (i--) { x = processedXData[i]; stackIndicator = series.getStackIndicator(stackIndicator, x, series.index); stack = stacks[key] && stacks[key][x]; pointExtremes = stack && stack.points[stackIndicator.key]; 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]; } } }); }; /** * Get stack indicator, according to it's x-value, to determine points with the same x-value */ Series.prototype.getStackIndicator = function(stackIndicator, x, index) { if (!defined(stackIndicator) || stackIndicator.x !== x) { stackIndicator = { x: x, index: 0 }; } else { stackIndicator.index++; } stackIndicator.key = [index, x, stackIndicator.index].join(','); return stackIndicator; }; // Extend the Chart prototype for dynamic methods extend(Chart.prototype, { /** * Add a series dynamically after time * * @param {Object} options The config options * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * * @return {Object} series The newly created series object */ addSeries: function (options, redraw, animation) { var series, chart = this; if (options) { redraw = pick(redraw, true); // defaults to true fireEvent(chart, 'addSeries', { options: options }, function () { series = chart.initSeries(options); chart.isDirtyLegend = true; // the series array is out of sync with the display chart.linkSeries(); if (redraw) { chart.redraw(animation); } }); } return series; }, /** * Add an axis to the chart * @param {Object} options The axis option * @param {Boolean} isX Whether it is an X axis or a value axis */ addAxis: function (options, isX, redraw, animation) { var key = isX ? 'xAxis' : 'yAxis', chartOptions = this.options, 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); } }, /** * Dim the chart and show a loading text or symbol * @param {String} str An optional text to show in the loading label instead of the default one */ showLoading: function (str) { var chart = this, options = chart.options, loadingDiv = chart.loadingDiv, loadingOptions = options.loading, setLoadingSize = function () { if (loadingDiv) { css(loadingDiv, { left: chart.plotLeft + PX, top: chart.plotTop + PX, width: chart.plotWidth + PX, height: chart.plotHeight + PX }); } }; // create the layer at the first call if (!loadingDiv) { chart.loadingDiv = loadingDiv = createElement(DIV, { className: PREFIX + 'loading' }, extend(loadingOptions.style, { zIndex: 10, display: NONE }), chart.container); chart.loadingSpan = createElement( 'span', null, loadingOptions.labelStyle, loadingDiv ); addEvent(chart, 'redraw', setLoadingSize); // #1080 } // update text chart.loadingSpan.innerHTML = str || options.lang.loading; // show it if (!chart.loadingShown) { css(loadingDiv, { opacity: 0, display: '' }); animate(loadingDiv, { opacity: loadingOptions.style.opacity }, { duration: loadingOptions.showDuration || 0 }); chart.loadingShown = true; } setLoadingSize(); }, /** * Hide the loading layer */ hideLoading: function () { var options = this.options, loadingDiv = this.loadingDiv; if (loadingDiv) { animate(loadingDiv, { opacity: 0 }, { duration: options.loading.hideDuration || 100, complete: function () { css(loadingDiv, { display: NONE }); } }); } this.loadingShown = false; } }); // extend the Point prototype for dynamic methods extend(Point.prototype, { /** * Update the point with new options (typically x/y data) and optionally redraw the series. * * @param {Object} options Point options as defined in the series.data array * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration * */ update: function (options, redraw, animation, runEvent) { var point = this, series = point.series, graphic = point.graphic, i, chart = series.chart, seriesOptions = series.options, names = series.xAxis && series.xAxis.names; redraw = pick(redraw, true); function update() { point.applyOptions(options); // Update visuals if (point.y === null && graphic) { // #4146 point.graphic = graphic.destroy(); } if (isObject(options) && !isArray(options)) { // Defer the actual redraw until getAttribs has been called (#3260) point.redraw = function () { if (graphic && graphic.element) { if (options && options.marker && options.marker.symbol) { point.graphic = graphic.destroy(); } } if (options && options.dataLabels && point.dataLabel) { // #2468 point.dataLabel = point.dataLabel.destroy(); } point.redraw = null; }; } // record changes in the parallel arrays i = point.index; series.updateParallelArrays(point, i); if (names && point.name) { names[point.x] = point.name; } 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.isDirtyLegend = true; } if (redraw) { chart.redraw(animation); } } // Fire the event with a default handler of doing the update if (runEvent === false) { // When called from setData update(); } else { point.firePointEvent('update', { options: options }, update); } }, /** * Remove a point and optionally redraw the series and if necessary the axes * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { this.series.removePoint(inArray(this, this.series.data), redraw, animation); } }); // Extend the series prototype for dynamic methods extend(Series.prototype, { /** * Add a point dynamically after chart load time * @param {Object} options Point options as given in series.data * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean} shift If shift is true, a point is shifted off the start * of the series as one is appended to the end. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ addPoint: function (options, redraw, shift, animation) { var series = this, seriesOptions = series.options, data = series.data, graph = series.graph, area = series.area, chart = series.chart, names = series.xAxis && series.xAxis.names, currentShift = (graph && graph.shift) || 0, shiftShapes = ['graph', 'area'], dataOptions = seriesOptions.data, point, isInTheMiddle, xData = series.xData, i, x; setAnimation(animation, chart); // Make graph animate sideways if (shift) { i = series.zones.length; while (i--) { shiftShapes.push('zoneGraph' + i, 'zoneArea' + i); } each(shiftShapes, function (shape) { if (series[shape]) { series[shape].shift = currentShift + (seriesOptions.step ? 2 : 1); } }); } if (area) { area.isArea = true; // needed in animation, both with and without shift } // Optional redraw, defaults to true redraw = pick(redraw, true); // Get options and push the point to xData, yData and series.options. In series.generatePoints // the Point instance will be created on demand and pushed to the series.data array. point = { series: series }; series.pointClass.prototype.applyOptions.apply(point, [options]); x = point.x; // Get the insertion point i = xData.length; if (series.requireSorting && x < xData[i - 1]) { isInTheMiddle = true; while (i && xData[i - 1] > x) { i--; } } series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item series.updateParallelArrays(point, i); // update it if (names && point.name) { names[x] = point.name; } dataOptions.splice(i, 0, options); if (isInTheMiddle) { series.data.splice(i, 0, null); series.processData(); } // Generate points to be added to the legend (#1329) if (seriesOptions.legendType === 'point') { series.generatePoints(); } // Shift the first point off the parallel arrays // todo: consider series.removePoint(i) method if (shift) { if (data[0] && data[0].remove) { data[0].remove(false); } else { data.shift(); series.updateParallelArrays(point, 'shift'); dataOptions.shift(); } } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { series.getAttribs(); // #1937 chart.redraw(); } }, /** * Remove a point (rendered or not), by index */ removePoint: function (i, redraw, animation) { var series = this, data = series.data, point = data[i], points = series.points, chart = series.chart, remove = function () { if (data.length === points.length) { points.splice(i, 1); } data.splice(i, 1); series.options.data.splice(i, 1); series.updateParallelArrays(point || { series: series }, 'splice', i, 1); if (point) { point.destroy(); } // redraw series.isDirty = true; series.isDirtyData = true; if (redraw) { chart.redraw(); } }; setAnimation(animation, chart); redraw = pick(redraw, true); // Fire the event with a default handler of removing the point if (point) { point.firePointEvent('remove', null, remove); } else { remove(); } }, /** * Remove a series and optionally redraw the chart * * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call * @param {Boolean|Object} animation Whether to apply animation, and optionally animation * configuration */ remove: function (redraw, animation) { var series = this, chart = series.chart; 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; }, /** * Update the series with a new set of options */ update: function (newOptions, redraw) { var series = this, chart = this.chart, // must use user options when changing type because this.options is merged // in with type specific plotOptions oldOptions = this.userOptions, oldType = this.type, proto = seriesTypes[oldType].prototype, preserve = ['group', 'markerGroup', 'dataLabelsGroup'], n; // If we're changing type or zIndex, create new groups (#3380, #3404) if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) { preserve.length = 0; } // Make sure groups are not destroyed (#3094) each(preserve, function (prop) { preserve[prop] = series[prop]; delete series[prop]; }); // Do the merge, with some forced options newOptions = merge(oldOptions, { animation: false, index: this.index, pointStart: this.xData[0] // when updating after addPoint }, { data: this.options.data }, newOptions); // Destroy the series and delete all properties. Reinsert all methods // and properties from the new type prototype (#2270, #3719) this.remove(false); for (n in proto) { this[n] = UNDEFINED; } extend(this, seriesTypes[newOptions.type || oldType].prototype); // Re-register groups (#3094) each(preserve, function (prop) { series[prop] = preserve[prop]; }); this.init(chart, newOptions); chart.linkSeries(); // Links are lost in this.remove (#3028) if (pick(redraw, true)) { chart.redraw(false); } } }); // Extend the Axis.prototype for dynamic methods extend(Axis.prototype, { /** * Update the axis with a new options structure */ update: function (newOptions, redraw) { var chart = this.chart; newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions); this.destroy(true); this._addedPlotLB = this.chart._labelPanes = UNDEFINED; // #1611, #2887, #4314 this.init(chart, extend(newOptions, { events: UNDEFINED })); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Remove the axis from the chart */ remove: function (redraw) { var chart = this.chart, key = this.coll, // xAxis or yAxis axisSeries = this.series, i = axisSeries.length; // Remove associated series (#2687) while (i--) { if (axisSeries[i]) { axisSeries[i].remove(false); } } // Remove the axis erase(chart.axes, this); erase(chart[key], this); chart.options[key].splice(this.options.index, 1); each(chart[key], function (axis, i) { // Re-index, #1706 axis.options.index = i; }); this.destroy(); chart.isDirtyBox = true; if (pick(redraw, true)) { chart.redraw(); } }, /** * Update the axis title by options */ setTitle: function (newTitleOptions, redraw) { this.update({ title: newTitleOptions }, redraw); }, /** * Set new axis categories and optionally redraw * @param {Array} categories * @param {Boolean} redraw */ setCategories: function (categories, redraw) { this.update({ categories: categories }, redraw); } }); /** * LineSeries object */ var LineSeries = extendClass(Series); seriesTypes.line = LineSeries; /** * Set the default options for area */ defaultPlotOptions.area = merge(defaultSeriesOptions, { softThreshold: false, 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 series = this, segments = [], segment = [], keys = [], xAxis = this.xAxis, yAxis = this.yAxis, stack = yAxis.stacks[this.stackKey], pointMap = {}, plotX, plotY, points = this.points, connectNulls = this.options.connectNulls, stackIndicator, 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) { if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336) keys.push(+x); } } keys.sort(function (a, b) { return a - b; }); each(keys, function (x) { var threshold = null, stackPoint; 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 { // Loop down the stack to find the series below this one that has // a value (#1991) for (i = series.index; i <= yAxis.series.length; i++) { stackIndicator = series.getStackIndicator(null, x, i); stackPoint = stack[x].points[stackIndicator.key]; if (stackPoint) { threshold = stackPoint[1]; break; } } plotX = xAxis.translate(x); plotY = yAxis.getThreshold(threshold); 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, zones = this.zones, props = [['area', this.color, options.fillColor]]; // area name, main color, fill color each(zones, function (threshold, i) { props.push(['zoneArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]); }); 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); } }); }, drawLegendSymbol: LegendSymbolMixin.drawRectangle }); 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: LegendSymbolMixin.drawRectangle }); 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, halo: false }, select: { color: '#C0C0C0', borderColor: '#000000', shadow: false } }, dataLabels: { align: null, // auto verticalAlign: null, // auto y: null }, softThreshold: false, startFromThreshold: true, // docs (but false doesn't work well): http://jsfiddle.net/highcharts/hz8fopan/14/ stickyTracking: false, tooltip: { distance: 6 }, threshold: 0 }); /** * ColumnSeries object */ var ColumnSeries = extendClass(Series, { type: 'column', pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', fill: 'color', r: 'borderRadius' }, cropShoulder: 0, directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply. trackerGroups: ['group', 'dataLabelsGroup'], negStacks: true, // use separate negative stacks, unlike area stacks where a negative // point is substracted from previous (#1910) /** * Initialize the series */ init: function () { Series.prototype.init.apply(this, arguments); var series = this, chart = series.chart; // if the series is added dynamically, force redraw of other // series affected by a new column if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } }, /** * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding, * pointWidth etc. */ getColumnMetrics: function () { var series = this, options = series.options, xAxis = series.xAxis, yAxis = series.yAxis, reversedXAxis = xAxis.reversed, stackKey, stackGroups = {}, 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 || xAxis.tickInterval || 1), // #2610 xAxis.len // #1535 ), groupPadding = categoryWidth * options.groupPadding, groupWidth = categoryWidth - 2 * groupPadding, pointOffsetWidth = groupWidth / columnCount, pointWidth = mathMin( options.maxPointWidth || xAxis.len, pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding)) ), pointPadding = (pointOffsetWidth - pointWidth) / 2, colIndex = (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 }); }, /** * Make the columns crisp. The edges are rounded to the nearest full pixel. */ crispCol: function (x, y, w, h) { var chart = this.chart, borderWidth = this.borderWidth, xCrisp = -(borderWidth % 2 ? 0.5 : 0), yCrisp = borderWidth % 2 ? 0.5 : 1, right, bottom, fromTop; if (chart.inverted && chart.renderer.isVML) { yCrisp += 1; } // Horizontal. We need to first compute the exact right edge, then round it // and compute the width from there. right = Math.round(x + w) + xCrisp; x = Math.round(x) + xCrisp; w = right - x; // Vertical fromTop = mathAbs(y) <= 0.5; // #4504 bottom = Math.round(y + h) + yCrisp; y = Math.round(y) + yCrisp; h = bottom - y; // Top edges are exceptions if (fromTop) { y -= 1; h += 1; } return { x: x, y: y, width: w, height: h }; }, /** * Translate each point to the plot area coordinate system and find shape positions */ translate: function () { var series = this, chart = series.chart, options = series.options, borderWidth = series.borderWidth = pick( options.borderWidth, series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635 ), yAxis = series.yAxis, threshold = options.threshold, translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold), minPointLength = pick(options.minPointLength, 5), metrics = series.getColumnMetrics(), pointWidth = metrics.width, seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width pointXOffset = series.pointXOffset = metrics.offset; if (chart.inverted) { translatedThreshold -= 0.5; // #3355 } // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual // columns to have individual sizes. When pointPadding is greater, we strive for equal-width // columns (#2694). if (options.pointPadding) { seriesBarW = mathCeil(seriesBarW); } Series.prototype.translate.apply(series); // Record the new values each(series.points, function (point) { var yBottom = mathMin(pick(point.yBottom, translatedThreshold), 9e4), // #3575 safeDistance = 999 + mathAbs(yBottom), plotY = mathMin(mathMax(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264) barX = point.plotX + pointXOffset, barW = seriesBarW, barY = mathMin(plotY, yBottom), up, barH = mathMax(plotY, yBottom) - barY; // Handle options.minPointLength if (mathAbs(barH) < minPointLength) { if (minPointLength) { barH = minPointLength; up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative); barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked yBottom - minPointLength : // keep position translatedThreshold - (up ? minPointLength : 0); // #1485, #4051 } } // Cache for access in polar point.barX = barX; point.pointWidth = pointWidth; // Fix the tooltip on center of grouped columns (#1216, #424, #3648) point.tooltipPos = chart.inverted ? [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] : [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH]; // Register shape type and arguments to be used in drawPoints point.shapeType = 'rect'; point.shapeArgs = series.crispCol(barX, barY, barW, barH); }); }, getSymbol: noop, /** * Use a solid rectangle like the area series types */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Columns have no graph */ drawGraph: noop, /** * Draw the columns. For bars, the series.group is rotated, so the same coordinates * apply for columns and bars. This method is inherited by scatter series. * */ drawPoints: function () { var series = this, chart = this.chart, options = series.options, renderer = chart.renderer, animationLimit = options.animationLimit || 250, shapeArgs, pointAttr; // draw the columns each(series.points, function (point) { var plotY = point.plotY, graphic = point.graphic, borderAttr; if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) { shapeArgs = point.shapeArgs; borderAttr = defined(series.borderWidth) ? { 'stroke-width': series.borderWidth } : {}; pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE]; if (graphic) { // update stop(graphic); graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); } else { point.graphic = graphic = renderer[point.shapeType](shapeArgs) .attr(borderAttr) .attr(pointAttr) .add(point.group || series.group) .shadow(options.shadow, null, options.stacking && !options.borderRadius); } } else if (graphic) { point.graphic = graphic.destroy(); // #1269 } }); }, /** * Animate the column heights one by one from zero * @param {Boolean} init Whether to initialize the animation or run it */ animate: function (init) { var series = this, yAxis = this.yAxis, options = series.options, inverted = this.chart.inverted, attr = {}, translatedThreshold; if (hasSVG) { // VML is too slow anyway if (init) { attr.scaleY = 0.001; translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold))); if (inverted) { attr.translateX = translatedThreshold - yAxis.len; } else { attr.translateY = translatedThreshold; } series.group.attr(attr); } else { // run the animation attr.scaleY = 1; attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos; series.group.animate(attr, series.options.animation); // delete this function to allow it only once series.animate = null; } } }, /** * Remove this series from the chart */ remove: function () { var series = this, chart = series.chart; // column and bar series affects other series of the same type // as they are either stacked or grouped if (chart.hasRendered) { each(chart.series, function (otherSeries) { if (otherSeries.type === series.type) { otherSeries.isDirty = true; } }); } Series.prototype.remove.apply(series, arguments); } }); seriesTypes.column = ColumnSeries; /** * Set the default options for 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, marker: { enabled: true // Overrides auto-enabling in line series (#3647) }, tooltip: { headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>' } }); /** * The scatter series class */ var ScatterSeries = extendClass(Series, { type: 'scatter', sorted: false, requireSorting: false, noSharedTooltip: true, trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'], takeOrdinalPosition: false, // #2342 kdDimensions: 2, drawGraph: function () { if (this.options.lineWidth) { Series.prototype.drawGraph.call(this); } } }); seriesTypes.scatter = ScatterSeries; /** * 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 () { // #2945 return this.y === null ? undefined : this.point.name; }, // softConnector: true, x: 0 // 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; point.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, redraw) { var point = this, series = point.series, chart = series.chart, ignoreHiddenPoint = series.options.ignoreHiddenPoint; redraw = pick(redraw, ignoreHiddenPoint); if (vis !== point.visible) { // 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 // Show and hide associated elements. This is performed regardless of redraw or not, // because chart.redraw only handles full series. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) { if (point[key]) { point[key][vis ? 'show' : 'hide'](true); } }); if (point.legendItem) { chart.legend.colorizeItem(point, vis); } // #4170, hide halo after hiding point if (!vis && point.state === 'hover') { point.setState(''); } // Handle ignore hidden slices if (ignoreHiddenPoint) { series.isDirty = true; } if (redraw) { 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); } }, haloPath: function (size) { var shapeArgs = this.shapeArgs, chart = this.series.chart; return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, { innerR: this.shapeArgs.r, start: shapeArgs.start, end: shapeArgs.end }); } }); /** * The Pie series class */ var PieSeries = { type: 'pie', isCartesian: false, pointClass: PiePoint, requireSorting: false, directTouch: true, noSharedTooltip: true, trackerGroups: ['group', 'dataLabelsGroup'], axisTypes: [], pointAttrToOptions: { // mapping between SVG attributes and the corresponding options stroke: 'borderColor', 'stroke-width': 'borderWidth', fill: 'color' }, /** * 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: point.startR || (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; } }, /** * Recompute total chart sum and update percentages of points. */ updateTotals: function () { var i, total = 0, points = this.points, len = points.length, point, ignoreHiddenPoint = this.options.ignoreHiddenPoint; // 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.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0; point.total = total; } }, /** * Extend the generatePoints method by adding total and percentage properties to each point */ generatePoints: function () { Series.prototype.generatePoints.call(this); this.updateTotals(); }, /** * 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 * ((pick(options.endAngle, startAngle + 360)) - 90), 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(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1)); 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 }; // The angle must stay within -90 and 270 (#2645) angle = (end + start) / 2; if (angle > 1.5 * mathPI) { angle -= 2 * mathPI; } else if (angle < -mathPI / 2) { angle += 2 * mathPI; } // Center for the sliced out slice 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 ]; } }, 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, attr; if (shadow && !series.shadowGroup) { series.shadowGroup = renderer.g('shadow') .add(series.group); } // draw the slices each(series.points, function (point) { if (point.y !== null) { 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 .setRadialReference(series.center) .animate(extend(shapeArgs, groupTranslation)); } else { attr = { 'stroke-linejoin': 'round' }; if (!point.visible) { attr.visibility = 'hidden'; } point.graphic = graphic = renderer[point.shapeType](shapeArgs) .setRadialReference(series.center) .attr( point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] ) .attr(attr) .attr(groupTranslation) .add(series.group) .shadow(shadow, shadowGroup); } } }); }, searchPoint: noop, /** * Utility for sorting data labels */ sortByAngle: function (points, sign) { points.sort(function (a, b) { return a.angle !== undefined && (b.angle - a.angle) * sign; }); }, /** * Use a simple symbol from LegendSymbolMixin */ drawLegendSymbol: LegendSymbolMixin.drawRectangle, /** * Use the getCenter method from drawLegendSymbol */ getCenter: CenteredSeriesMixin.getCenter, /** * Pies don't have point marker symbols */ getSymbol: noop }; PieSeries = extendClass(Series, PieSeries); seriesTypes.pie = PieSeries; /** * Draw the data labels */ Series.prototype.drawDataLabels = function () { var series = this, seriesOptions = series.options, cursor = seriesOptions.cursor, options = seriesOptions.dataLabels, points = series.points, pointOptions, generalOptions, hasRendered = series.hasRendered || 0, str, dataLabelsGroup, renderer = series.chart.renderer; if (options.enabled || series._hasPointLabels) { // Process default alignment of data labels for columns if (series.dlProcessOptions) { series.dlProcessOptions(options); } // Create a separate group for the data labels to avoid rotation dataLabelsGroup = series.plotGroup( 'dataLabelsGroup', 'data-labels', options.defer ? HIDDEN : VISIBLE, options.zIndex || 6 ); if (pick(options.defer, true)) { dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300 if (!hasRendered) { addEvent(series, 'afterAnimate', function () { if (series.visible) { // #3023, #3024 dataLabelsGroup.show(); } dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 }); }); } } // Make the labels for each point generalOptions = options; each(points, function (point) { var enabled, dataLabel = point.dataLabel, labelConfig, attr, name, rotation, connector = point.connector, isNew = true, style, moreStyle = {}; // Determine if each data label is enabled pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #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); style = options.style; rotation = options.rotation; // Get the string labelConfig = point.getLabelConfig(); str = options.format ? format(options.format, labelConfig) : options.formatter.call(labelConfig, options); // Determine the color style.color = pick(options.color, style.color, series.color, 'black'); // update existing label if (dataLabel) { if (defined(str)) { dataLabel .attr({ text: str }); isNew = false; } else { // #1437 - the label is shown conditionally point.dataLabel = dataLabel = dataLabel.destroy(); if (connector) { point.connector = connector.destroy(); } } // create new label } else if (defined(str)) { attr = { //align: align, fill: options.backgroundColor, stroke: options.borderColor, 'stroke-width': options.borderWidth, r: options.borderRadius || 0, rotation: rotation, padding: options.padding, zIndex: 1 }; // Get automated contrast color if (style.color === 'contrast') { moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ? renderer.getContrast(point.color || series.color) : '#000000'; } if (cursor) { moreStyle.cursor = cursor; } // Remove unused attributes (#947) for (name in attr) { if (attr[name] === UNDEFINED) { delete attr[name]; } } dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation str, 0, -999, options.shape, null, null, options.useHTML ) .attr(attr) .css(extend(style, moreStyle)) .add(dataLabelsGroup) .shadow(options.shadow); } if (dataLabel) { // Now the data label is created and placed at 0,0, so we need to align it series.alignDataLabel(point, dataLabel, options, null, isNew); } } }); } }; /** * Align each individual data label */ Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var chart = this.chart, inverted = chart.inverted, plotX = pick(point.plotX, -999), plotY = pick(point.plotY, -999), bBox = dataLabel.getBBox(), baseline = chart.renderer.fontMetrics(options.style.fontSize).b, rotCorr, // rotation correction // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700) visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) || (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))), alignAttr; // the final position; 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 rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723 dataLabel[isNew ? 'attr' : 'animate']({ x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x, y: alignTo.y + options.y + alignTo.height / 2 }) .attr({ // #3003 align: options.align }); } else { dataLabel.align(options, null, alignTo); alignAttr = dataLabel.alignAttr; // Handle justify or crop if (pick(options.overflow, 'justify') === '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); } // When we're using a shape, make it possible with a connector or an arrow pointing to thie point if (options.shape) { dataLabel.attr({ anchorX: point.plotX, anchorY: point.plotY }); } } } // Show or hide based on the final aligned position if (!visible) { stop(dataLabel); dataLabel.attr({ y: -999 }); dataLabel.placed = false; // don't animate back in } }; /** * If data labels fall partly outside the plot area, align them back in, in a way that * doesn't hide the point. */ Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) { var chart = this.chart, align = options.align, verticalAlign = options.verticalAlign, off, justified, padding = dataLabel.box ? 0 : (dataLabel.padding || 0); // Off left off = alignAttr.x + padding; if (off < 0) { if (align === 'right') { options.align = 'left'; } else { options.x = -off; } justified = true; } // Off right off = alignAttr.x + bBox.width - padding; if (off > chart.plotWidth) { if (align === 'left') { options.align = 'right'; } else { options.x = chart.plotWidth - off; } justified = true; } // Off top off = alignAttr.y + padding; if (off < 0) { if (verticalAlign === 'bottom') { options.verticalAlign = 'top'; } else { options.y = -off; } justified = true; } // Off bottom off = alignAttr.y + bBox.height - padding; if (off > chart.plotHeight) { if (verticalAlign === 'top') { options.verticalAlign = 'bottom'; } else { options.y = chart.plotHeight - off; } justified = true; } if (justified) { dataLabel.placed = !isNew; dataLabel.align(options, null, alignTo); } }; /** * Override the base drawDataLabels method by pie specific functionality */ if (seriesTypes.pie) { seriesTypes.pie.prototype.drawDataLabels = function () { var series = this, data = series.data, point, chart = series.chart, options = series.options.dataLabels, connectorPadding = pick(options.connectorPadding, 10), connectorWidth = pick(options.connectorWidth, 1), plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, connector, connectorPath, softConnector = pick(options.softConnector, true), distanceOption = options.distance, seriesCenter = series.center, radius = seriesCenter[2] / 2, centerY = seriesCenter[1], outside = distanceOption > 0, dataLabel, dataLabelWidth, labelPos, labelHeight, halves = [// divide the points into right and left halves for anti collision [], // right [] // left ], x, y, visibility, rankArr, i, j, overflow = [0, 0, 0, 0], // top, right, bottom, left sort = function (a, b) { return b.y - a.y; }; // get out if not enabled if (!series.visible || (!options.enabled && !series._hasPointLabels)) { return; } // run parent method Series.prototype.drawDataLabels.apply(series); // arrange points for detection collision each(data, function (point) { if (point.dataLabel && point.visible) { // #407, #2510 halves[point.half].push(point); } }); /* Loop over the points in each half, starting from the top and bottom * of the pie to detect overlapping labels. */ i = 2; while (i--) { var slots = [], slotsLength, usedSlots = [], points = halves[i], pos, bottom, length = points.length, slotIndex; if (!length) { continue; } // Sort by angle series.sortByAngle(points, i - 0.5); // Assume equal label heights on either hemisphere (#2630) j = labelHeight = 0; while (!labelHeight && points[j]) { // #1569 labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968 j++; } // Only do anti-collision when we are outside the pie and have connectors (#856) if (distanceOption > 0) { // Build the slots bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight); for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) { slots.push(pos); } slotsLength = slots.length; /* Visualize the slots if (!series.slotElements) { series.slotElements = []; } if (i === 1) { series.slotElements.forEach(function (elem) { elem.destroy(); }); series.slotElements.length = 0; } slots.forEach(function (pos, no) { var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0), slotY = pos + chart.plotTop; if (!isNaN(slotX)) { series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1) .attr({ 'stroke-width': 1, stroke: 'silver', fill: 'rgba(0,0,255,0.1)' }) .add()); series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4) .attr({ fill: 'silver' }).add()); } }); // */ // if there are more values than available slots, remove lowest values if (length > slotsLength) { // create an array for sorting and ranking the points within each quarter rankArr = [].concat(points); rankArr.sort(sort); j = length; while (j--) { rankArr[j].rank = j; } j = length; while (j--) { if (points[j].rank >= slotsLength) { points.splice(j, 1); } } length = points.length; } // The label goes to the nearest open slot, but not closer to the edge than // the label's index. for (j = 0; j < length; j++) { point = points[j]; labelPos = point.labelPos; var closest = 9999, distance, slotI; // find the closest slot index for (slotI = 0; slotI < slotsLength; slotI++) { distance = mathAbs(slots[slotI] - labelPos[1]); if (distance < closest) { closest = distance; slotIndex = slotI; } } // if that slot index is closer to the edges of the slots, move it // to the closest appropriate slot if (slotIndex < j && slots[j] !== null) { // cluster at the top slotIndex = j; } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom slotIndex = slotsLength - length + j; while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } else { // Slot is taken, find next free slot below. In the next run, the next slice will find the // slot above these, because it is the closest one while (slots[slotIndex] === null) { // make sure it is not taken slotIndex++; } } usedSlots.push({ i: slotIndex, y: slots[slotIndex] }); slots[slotIndex] = null; // mark as taken } // sort them in order to fill in from the top usedSlots.sort(sort); } // now the used slots are sorted, fill them up sequentially for (j = 0; j < length; j++) { var slot, naturalY; point = points[j]; labelPos = point.labelPos; dataLabel = point.dataLabel; visibility = point.visible === false ? HIDDEN : 'inherit'; naturalY = labelPos[1]; if (distanceOption > 0) { slot = usedSlots.pop(); slotIndex = slot.i; // if the slot next to currrent slot is free, the y value is allowed // to fall back to the natural position y = slot.y; if ((naturalY > y && slots[slotIndex + 1] !== null) || (naturalY < y && slots[slotIndex - 1] !== null)) { y = mathMin(mathMax(0, naturalY), chart.plotHeight); } } else { y = naturalY; } // get the x - use the natural x position for first and last slot, to prevent the top // and botton slice connectors from touching each other on either side x = options.justify ? seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) : series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i); // Record the placement and visibility dataLabel._attr = { visibility: visibility, align: labelPos[6] }; dataLabel._pos = { x: x + options.x + ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0), y: y + options.y - 10 // 10 is for the baseline (label vs text) }; dataLabel.connX = x; dataLabel.connY = y; // Detect overflowing data labels if (this.options.size === null) { dataLabelWidth = dataLabel.width; // Overflow left if (x - dataLabelWidth < connectorPadding) { overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]); // Overflow right } else if (x + dataLabelWidth > plotWidth - connectorPadding) { overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]); } // Overflow top if (y - labelHeight / 2 < 0) { overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]); // Overflow left } else if (y + labelHeight / 2 > plotHeight) { overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]); } } } // for each point } // for each half // Do not apply the final placement and draw the connectors until we have verified // that labels are not spilling over. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) { // Place the labels in the final position this.placeDataLabels(); // Draw the connectors if (outside && connectorWidth) { each(this.points, function (point) { connector = point.connector; labelPos = point.labelPos; dataLabel = point.dataLabel; if (dataLabel && dataLabel._pos && point.visible) { visibility = dataLabel._attr.visibility; x = dataLabel.connX; y = dataLabel.connY; connectorPath = softConnector ? [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label 'C', x, y, // first break, next to the label 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5], labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ] : [ M, x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label L, labelPos[2], labelPos[3], // second break L, labelPos[4], labelPos[5] // base ]; if (connector) { connector.animate({ d: connectorPath }); connector.attr('visibility', visibility); } else { point.connector = connector = series.chart.renderer.path(connectorPath).attr({ 'stroke-width': connectorWidth, stroke: options.connectorColor || point.color || '#606060', visibility: visibility //zIndex: 0 // #2722 (reversed) }) .add(series.dataLabelsGroup); } } else if (connector) { point.connector = connector.destroy(); } }); } } }; /** * Perform the final placement of the data labels after we have verified that they * fall within the plot area. */ seriesTypes.pie.prototype.placeDataLabels = function () { each(this.points, function (point) { var dataLabel = point.dataLabel, _pos; if (dataLabel && point.visible) { _pos = dataLabel._pos; if (_pos) { dataLabel.attr(dataLabel._attr); dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos); dataLabel.moved = true; } else if (dataLabel) { dataLabel.attr({ y: -999 }); } } }); }; seriesTypes.pie.prototype.alignDataLabel = noop; /** * Verify whether the data labels are allowed to draw, or we should run more translation and data * label positioning to keep them inside the plot area. Returns true when data labels are ready * to draw. */ seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) { var center = this.center, options = this.options, centerOption = options.center, minSize = options.minSize || 80, newSize = minSize, ret; // Handle horizontal size and center if (centerOption[0] !== null) { // Fixed center newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize); } else { // Auto center newSize = mathMax( center[2] - overflow[1] - overflow[3], // horizontal overflow minSize ); center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center } // Handle vertical size and center if (centerOption[1] !== null) { // Fixed center newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize); } else { // Auto center newSize = mathMax( mathMin( newSize, center[2] - overflow[0] - overflow[2] // vertical overflow ), minSize ); center[1] += (overflow[0] - overflow[2]) / 2; // vertical center } // If the size must be decreased, we need to run translate and drawDataLabels again if (newSize < center[2]) { center[2] = newSize; center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632 this.translate(center); each(this.points, function (point) { if (point.dataLabel) { point.dataLabel._pos = null; // reset } }); if (this.drawDataLabels) { this.drawDataLabels(); } // Else, return true to indicate that the pie and its labels is within the plot area } else { ret = true; } return ret; }; } if (seriesTypes.column) { /** * Override the basic data label alignment by adjusting for the position of the column */ seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) { var inverted = this.chart.inverted, series = point.series, dlBox = point.dlBox || point.shapeArgs, // data label box for alignment below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series inside = pick(options.inside, !!this.options.stacking); // draw it inside the box? // 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: series.yAxis.len - alignTo.y - alignTo.height, y: series.xAxis.len - alignTo.x - alignTo.width, width: alignTo.height, height: alignTo.width }; } // Compute the alignment box if (!inside) { if (inverted) { alignTo.x += below ? 0 : alignTo.width; alignTo.width = 0; } else { alignTo.y += below ? alignTo.height : 0; alignTo.height = 0; } } } // When alignment is undefined (typically columns and bars), display the individual // point below or above the point depending on the threshold options.align = pick( options.align, !inverted || inside ? 'center' : below ? 'right' : 'left' ); options.verticalAlign = pick( options.verticalAlign, inverted || inside ? 'middle' : below ? 'top' : 'bottom' ); // Call the parent method Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew); }; } /** * Highcharts JS v4.1.9 (2015-10-07) * Highcharts module to hide overlapping data labels. This module is included by default in Highmaps. * * (c) 2010-2014 Torstein Honsi * * License: www.highcharts.com/license */ /*global Highcharts, HighchartsAdapter */ (function (H) { var Chart = H.Chart, each = H.each, pick = H.pick, addEvent = HighchartsAdapter.addEvent; // Collect potensial overlapping data labels. Stack labels probably don't need to be // considered because they are usually accompanied by data labels that lie inside the columns. Chart.prototype.callbacks.push(function (chart) { function collectAndHide() { var labels = []; each(chart.series, function (series) { var dlOptions = series.options.dataLabels, collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866 each(collections, function (coll) { each(series.points, function (point) { if (point[coll]) { point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118 labels.push(point[coll]); } }); }); } }); chart.hideOverlappingLabels(labels); } // Do it now ... collectAndHide(); // ... and after each chart redraw addEvent(chart, 'redraw', collectAndHide); }); /** * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth * visual imression. */ Chart.prototype.hideOverlappingLabels = function (labels) { var len = labels.length, label, i, j, label1, label2, isIntersecting, pos1, pos2, padding, intersectRect = function (x1, y1, w1, h1, x2, y2, w2, h2) { return !( x2 > x1 + w1 || x2 + w2 < x1 || y2 > y1 + h1 || y2 + h2 < y1 ); }; // Mark with initial opacity for (i = 0; i < len; i++) { label = labels[i]; if (label) { label.oldOpacity = label.opacity; label.newOpacity = 1; } } // Prevent a situation in a gradually rising slope, that each label // will hide the previous one because the previous one always has // lower rank. labels.sort(function (a, b) { return (b.labelrank || 0) - (a.labelrank || 0); }); // Detect overlapping labels for (i = 0; i < len; i++) { label1 = labels[i]; for (j = i + 1; j < len; ++j) { label2 = labels[j]; if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) { pos1 = label1.alignAttr; pos2 = label2.alignAttr; padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333) isIntersecting = intersectRect( pos1.x, pos1.y, label1.width - padding, label1.height - padding, pos2.x, pos2.y, label2.width - padding, label2.height - padding ); if (isIntersecting) { (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0; } } } } // Hide or show each(labels, function (label) { var complete, newOpacity; if (label) { newOpacity = label.newOpacity; if (label.oldOpacity !== newOpacity && label.placed) { // Make sure the label is completely hidden to avoid catching clicks (#4362) if (newOpacity) { label.show(true); } else { complete = function () { label.hide(); }; } // Animate or set the opacity label.alignAttr.opacity = newOpacity; label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete); } label.isOld = true; } }); }; }(Highcharts));/** * TrackerMixin for points and graphs */ var TrackerMixin = Highcharts.TrackerMixin = { drawTrackerPoint: function () { var series = this, chart = series.chart, pointer = chart.pointer, cursor = series.options.cursor, css = cursor && { cursor: cursor }, onMouseOver = function (e) { var target = e.target, point; while (target && !point) { point = target.point; target = target.parentNode; } if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart point.onMouseOver(e); } }; // Add reference to the point each(series.points, function (point) { if (point.graphic) { point.graphic.element.point = point; } if (point.dataLabel) { point.dataLabel.element.point = point; } }); // Add the event listeners, we need to do this only once if (!series._hasTracking) { each(series.trackerGroups, function (key) { if (series[key]) { // we don't always have dataLabelsGroup series[key] .addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { series[key].on('touchstart', onMouseOver); } } }); series._hasTracking = true; } }, /** * Draw the tracker object that sits above all data labels and markers to * track mouse events on the graph or points. For the line type charts * the tracker uses the same graphPath, but with a greater stroke width * for better control. */ drawTrackerGraph: function () { var series = this, options = series.options, trackByArea = options.trackByArea, trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath), trackerPathLength = trackerPath.length, chart = series.chart, pointer = chart.pointer, renderer = chart.renderer, snap = chart.options.tooltip.snap, tracker = series.tracker, cursor = options.cursor, css = cursor && { cursor: cursor }, singlePoints = series.singlePoints, singlePoint, i, onMouseOver = function () { if (chart.hoverSeries !== series) { series.onMouseOver(); } }, /* * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable * IE6: 0.002 * IE7: 0.002 * IE8: 0.002 * IE9: 0.00000000001 (unlimited) * IE10: 0.0001 (exporting only) * FF: 0.00000000001 (unlimited) * Chrome: 0.000001 * Safari: 0.000001 * Opera: 0.00000000001 (unlimited) */ TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')'; // Extend end points. A better way would be to use round linecaps, // but those are not clickable in VML. if (trackerPathLength && !trackByArea) { i = trackerPathLength + 1; while (i--) { if (trackerPath[i] === M) { // extend left side trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L); } if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]); } } } // handle single points for (i = 0; i < singlePoints.length; i++) { singlePoint = singlePoints[i]; trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY, L, singlePoint.plotX + snap, singlePoint.plotY); } // draw the tracker if (tracker) { tracker.attr({ d: trackerPath }); } else { // create series.tracker = renderer.path(trackerPath) .attr({ 'stroke-linejoin': 'round', // #1225 visibility: series.visible ? VISIBLE : HIDDEN, stroke: TRACKER_FILL, fill: trackByArea ? TRACKER_FILL : NONE, 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap), zIndex: 2 }) .add(series.group); // The tracker is added to the series group, which is clipped, but is covered // by the marker group. So the marker group also needs to capture events. each([series.tracker, series.markerGroup], function (tracker) { tracker.addClass(PREFIX + 'tracker') .on('mouseover', onMouseOver) .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); }) .css(css); if (hasTouch) { tracker.on('touchstart', onMouseOver); } }); } } }; /* End TrackerMixin */ /** * Add tracking event listener to the series group, so the point graphics * themselves act as trackers */ if (seriesTypes.column) { ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.pie) { seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } if (seriesTypes.scatter) { ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint; } /* * Extend Legend for item events */ extend(Legend.prototype, { setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) { var legend = this; // Set the events on the item group, or in case of useHTML, the item itself (#1249) (useHTML ? legendItem : item.legendGroup).on('mouseover', function () { item.setState(HOVER_STATE); legendItem.css(legend.options.itemHoverStyle); }) .on('mouseout', function () { legendItem.css(item.visible ? itemStyle : itemHiddenStyle); item.setState(); }) .on('click', function (event) { var strLegendItemClick = 'legendItemClick', fnLegendItemClick = function () { if (item.setVisible) { item.setVisible(); } }; // Pass over the click/touch event. #4. event = { browserEvent: event }; // click the name or symbol if (item.firePointEvent) { // point item.firePointEvent(strLegendItemClick, event, fnLegendItemClick); } else { fireEvent(item, strLegendItemClick, event, fnLegendItemClick); } }); }, createCheckboxForItem: function (item) { var legend = this; item.checkbox = createElement('input', { type: 'checkbox', checked: item.selected, defaultChecked: item.selected // required by IE7 }, legend.options.itemCheckboxStyle, legend.chart.container); addEvent(item.checkbox, 'click', function (event) { var target = event.target; fireEvent(item.series || item, 'checkboxClick', { // #3712 checked: target.checked, item: item }, function () { item.select(); } ); }); } }); /* * Add pointer cursor to legend itemstyle in defaultOptions */ defaultOptions.legend.itemStyle.cursor = 'pointer'; /* * Extend the Chart object with interaction */ extend(Chart.prototype, { /** * Display the zoom button */ showResetZoom: function () { var chart = this, lang = defaultOptions.lang, btnOptions = chart.options.chart.resetZoomButton, theme = btnOptions.theme, states = theme.states, alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox'; 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, goingLeft = startPos > mousePos; // #3613 if (axis.series.length && (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) && (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) { axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' }); doRedraw = true; } chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run }); if (doRedraw) { chart.redraw(false); } css(chart.container, { cursor: 'move' }); } }); /* * Extend the Point object with interaction */ extend(Point.prototype, { /** * Toggle the selection status of a point * @param {Boolean} selected Whether to select or unselect the point. * @param {Boolean} accumulate Whether to add to the previous selection. By default, * this happens if the control key (Cmd on Mac) was pressed during clicking. */ select: function (selected, accumulate) { var point = this, series = point.series, chart = series.chart; selected = pick(selected, !point.selected); // fire the event with the 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 * * @param {Object} e The event arguments * @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to * actually hovered points. True for other points in shared tooltip. */ onMouseOver: function (e, byProximity) { var point = this, series = point.series, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; if (chart.hoverSeries !== series) { series.onMouseOver(); } // set normal state to previous series if (hoverPoint && hoverPoint !== point) { hoverPoint.onMouseOut(); } if (point.series) { // It may have been destroyed, #4130 // trigger the event point.firePointEvent('mouseOver'); // update the tooltip if (tooltip && (!tooltip.shared || series.noSharedTooltip)) { tooltip.refresh(point, e); } // hover this point.setState(HOVER_STATE); if (!byProximity) { chart.hoverPoint = point; } } }, /** * Runs on mouse out from the point */ onMouseOut: function () { var chart = this.series.chart, hoverPoints = chart.hoverPoints; this.firePointEvent('mouseOut'); if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240 this.setState(); chart.hoverPoint = null; } }, /** * Import events from the series' and point's options. Only do it on * demand, to save processing time on hovering. */ importEvents: function () { if (!this.hasImportedEvents) { var point = this, options = merge(point.series.options.point, point.options), events = options.events, eventType; point.events = events; for (eventType in events) { addEvent(point, eventType, events[eventType]); } this.hasImportedEvents = true; } }, /** * Set the point's state * @param {String} state */ setState: function (state, move) { var point = this, plotX = mathFloor(point.plotX), // #4586 plotY = point.plotY, series = point.series, stateOptions = series.options.states, markerOptions = defaultPlotOptions[series.type].marker && series.options.marker, normalDisabled = markerOptions && !markerOptions.enabled, markerStateOptions = markerOptions && markerOptions.states[state], stateDisabled = markerStateOptions && markerStateOptions.enabled === false, stateMarkerGraphic = series.stateMarkerGraphic, pointMarker = point.marker || {}, chart = series.chart, radius, halo = series.halo, haloOptions, newSymbol, pointAttr; state = state || NORMAL_STATE; // empty string pointAttr = point.pointAttr[state] || series.pointAttr[state]; if ( // already has this state (state === point.state && !move) || // selected points don't respond to hover (point.selected && state !== SELECT_STATE) || // series' state options is disabled (stateOptions[state] && stateOptions[state].enabled === false) || // general point marker's state options is disabled (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) || // individual point marker's state options is disabled (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610 ) { return; } // apply hover styles to the existing point if (point.graphic) { radius = markerOptions && point.graphic.symbolName && pointAttr.r; point.graphic.attr(merge( pointAttr, radius ? { // new symbol attributes (#507, #612) x: plotX - radius, y: plotY - radius, width: 2 * radius, height: 2 * radius } : {} )); // Zooming in from a range with no markers to a range with markers if (stateMarkerGraphic) { stateMarkerGraphic.hide(); } } else { // if a graphic is not applied to each point in the normal state, create a shared // graphic for the hover state if (state && markerStateOptions) { radius = markerStateOptions.radius; newSymbol = pointMarker.symbol || series.symbol; // If the point has another symbol than the previous one, throw away the // state marker graphic and force a new one (#1459) if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) { stateMarkerGraphic = stateMarkerGraphic.destroy(); } // Add a new state marker graphic if (!stateMarkerGraphic) { if (newSymbol) { series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol( newSymbol, plotX - radius, plotY - radius, 2 * radius, 2 * radius ) .attr(pointAttr) .add(series.markerGroup); stateMarkerGraphic.currentSymbol = newSymbol; } // Move the existing graphic } else { stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054 x: plotX - radius, y: plotY - radius }); } } if (stateMarkerGraphic) { stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450 stateMarkerGraphic.element.point = point; // #4310 } } // Show me your halo haloOptions = stateOptions[state] && stateOptions[state].halo; if (haloOptions && haloOptions.size) { if (!halo) { series.halo = halo = chart.renderer.path() .add(chart.seriesGroup); } halo.attr(extend({ fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get() }, haloOptions.attributes))[move ? 'animate' : 'attr']({ d: point.haloPath(haloOptions.size) }); } else if (halo) { halo.attr({ d: [] }); } point.state = state; }, haloPath: function (size) { var series = this.series, chart = series.chart, plotBox = series.getPlotBox(), inverted = chart.inverted; return chart.renderer.symbols.circle( plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size, plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size, size * 2, size * 2 ); } }); /* * Extend the Series object with interaction */ extend(Series.prototype, { /** * Series mouse over handler */ onMouseOver: function () { var series = this, chart = series.chart, hoverSeries = chart.hoverSeries; // set normal state to previous series if (hoverSeries && hoverSeries !== series) { hoverSeries.onMouseOut(); } // trigger the event, but to save processing time, // only if defined if (series.options.events.mouseOver) { fireEvent(series, 'mouseOver'); } // hover this series.setState(HOVER_STATE); chart.hoverSeries = series; }, /** * Series mouse out handler */ onMouseOut: function () { // trigger the event only if listeners exist var series = this, options = series.options, chart = series.chart, tooltip = chart.tooltip, hoverPoint = chart.hoverPoint; chart.hoverSeries = null; // #182, set to null before the mouseOut event fires // trigger mouse out on the point, which must be in this series if (hoverPoint) { hoverPoint.onMouseOut(); } // fire the mouse out event if (series && options.events.mouseOut) { fireEvent(series, 'mouseOut'); } // hide the tooltip if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) { tooltip.hide(); } // set normal state series.setState(); }, /** * Set the state of the graph */ setState: function (state) { var series = this, options = series.options, graph = series.graph, stateOptions = options.states, lineWidth = options.lineWidth, attribs, i = 0; state = state || NORMAL_STATE; if (series.state !== state) { series.state = state; if (stateOptions[state] && stateOptions[state].enabled === false) { return; } if (state) { lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035 } if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML attribs = { 'stroke-width': lineWidth }; // use attr because animate will cause any other animation on the graph to stop graph.attr(attribs); while (series['zoneGraph' + i]) { series['zoneGraph' + i].attr(attribs); i = i + 1; } } } }, /** * Set the visibility of the graph * * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED, * the visibility is toggled. */ setVisible: function (vis, redraw) { var series = this, chart = series.chart, legendItem = series.legendItem, showOrHide, ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries, oldVisibility = series.visible; // if called without an argument, toggle visibility series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis; showOrHide = vis ? 'show' : 'hide'; // show or hide elements each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) { if (series[key]) { series[key][showOrHide](); } }); // hide tooltip (#1361) if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) { series.onMouseOut(); } if (legendItem) { chart.legend.colorizeItem(series, vis); } // rescale or adapt to resized chart series.isDirty = true; // in a stack, all other series are affected if (series.options.stacking) { each(chart.series, function (otherSeries) { if (otherSeries.options.stacking && otherSeries.visible) { otherSeries.isDirty = true; } }); } // show or hide linked series each(series.linkedSeries, function (otherSeries) { otherSeries.setVisible(vis, false); }); if (ignoreHiddenSeries) { chart.isDirtyBox = true; } if (redraw !== false) { chart.redraw(); } fireEvent(series, showOrHide); }, /** * Show the graph */ show: function () { this.setVisible(true); }, /** * Hide the graph */ hide: function () { this.setVisible(false); }, /** * Set the selected state of the graph * * @param selected {Boolean} True to select the series, false to unselect. If * UNDEFINED, the selection state is toggled. */ select: function (selected) { var series = this; // if called without an argument, toggle series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected; if (series.checkbox) { series.checkbox.checked = selected; } fireEvent(series, selected ? 'select' : 'unselect'); }, drawTracker: TrackerMixin.drawTrackerGraph }); // global variables extend(Highcharts, { // Constructors Color: Color, Point: Point, Tick: Tick, Renderer: Renderer, SVGElement: SVGElement, SVGRenderer: SVGRenderer, // Various arrayMin: arrayMin, arrayMax: arrayMax, charts: charts, dateFormat: dateFormat, error: error, format: format, pathAnim: pathAnim, getOptions: getOptions, hasBidiBug: hasBidiBug, isTouchDevice: isTouchDevice, setOptions: setOptions, addEvent: addEvent, removeEvent: removeEvent, createElement: createElement, discardElement: discardElement, css: css, each: each, map: map, merge: merge, splat: splat, extendClass: extendClass, pInt: pInt, svg: hasSVG, canvas: useCanVG, vml: !hasSVG && !useCanVG, product: PRODUCT, version: VERSION }); }());
src/svg-icons/action/zoom-in.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionZoomIn = (props) => ( <SvgIcon {...props}> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/> </SvgIcon> ); ActionZoomIn = pure(ActionZoomIn); ActionZoomIn.displayName = 'ActionZoomIn'; ActionZoomIn.muiName = 'SvgIcon'; export default ActionZoomIn;
build/js/observe-sequence.js
CapsuleCat/OfflineChatRoomExample
////////////////////////////////////////////////////////////////////////// // // // This is a generated file. You can view the original // // source in your browser if your browser supports source maps. // // Source maps are supported by all recent versions of Chrome, Safari, // // and Firefox, and by Internet Explorer 11. // // // ////////////////////////////////////////////////////////////////////////// (function () { /* Imports */ var Meteor = Package.meteor.Meteor; var Tracker = Package.tracker.Tracker; var Deps = Package.tracker.Deps; var MongoID = Package['mongo-id'].MongoID; var DiffSequence = Package['diff-sequence'].DiffSequence; var _ = Package.underscore._; var Random = Package.random.Random; /* Package-scope variables */ var ObserveSequence, seqChangedToEmpty, seqChangedToArray, seqChangedToCursor; (function(){ /////////////////////////////////////////////////////////////////////////////////// // // // packages/observe-sequence/observe_sequence.js // // // /////////////////////////////////////////////////////////////////////////////////// // var warn = function () { // 1 if (ObserveSequence._suppressWarnings) { // 2 ObserveSequence._suppressWarnings--; // 3 } else { // 4 if (typeof console !== 'undefined' && console.warn) // 5 console.warn.apply(console, arguments); // 6 // 7 ObserveSequence._loggedWarnings++; // 8 } // 9 }; // 10 // 11 var idStringify = MongoID.idStringify; // 12 var idParse = MongoID.idParse; // 13 // 14 ObserveSequence = { // 15 _suppressWarnings: 0, // 16 _loggedWarnings: 0, // 17 // 18 // A mechanism similar to cursor.observe which receives a reactive // 19 // function returning a sequence type and firing appropriate callbacks // 20 // when the value changes. // 21 // // 22 // @param sequenceFunc {Function} a reactive function returning a // 23 // sequence type. The currently supported sequence types are: // 24 // Array, Cursor, and null. // 25 // // 26 // @param callbacks {Object} similar to a specific subset of // 27 // callbacks passed to `cursor.observe` // 28 // (http://docs.meteor.com/#observe), with minor variations to // 29 // support the fact that not all sequences contain objects with // 30 // _id fields. Specifically: // 31 // // 32 // * addedAt(id, item, atIndex, beforeId) // 33 // * changedAt(id, newItem, oldItem, atIndex) // 34 // * removedAt(id, oldItem, atIndex) // 35 // * movedTo(id, item, fromIndex, toIndex, beforeId) // 36 // // 37 // @returns {Object(stop: Function)} call 'stop' on the return value // 38 // to stop observing this sequence function. // 39 // // 40 // We don't make any assumptions about our ability to compare sequence // 41 // elements (ie, we don't assume EJSON.equals works; maybe there is extra // 42 // state/random methods on the objects) so unlike cursor.observe, we may // 43 // sometimes call changedAt() when nothing actually changed. // 44 // XXX consider if we *can* make the stronger assumption and avoid // 45 // no-op changedAt calls (in some cases?) // 46 // // 47 // XXX currently only supports the callbacks used by our // 48 // implementation of {{#each}}, but this can be expanded. // 49 // // 50 // XXX #each doesn't use the indices (though we'll eventually need // 51 // a way to get them when we support `@index`), but calling // 52 // `cursor.observe` causes the index to be calculated on every // 53 // callback using a linear scan (unless you turn it off by passing // 54 // `_no_indices`). Any way to avoid calculating indices on a pure // 55 // cursor observe like we used to? // 56 observe: function (sequenceFunc, callbacks) { // 57 var lastSeq = null; // 58 var activeObserveHandle = null; // 59 // 60 // 'lastSeqArray' contains the previous value of the sequence // 61 // we're observing. It is an array of objects with '_id' and // 62 // 'item' fields. 'item' is the element in the array, or the // 63 // document in the cursor. // 64 // // 65 // '_id' is whichever of the following is relevant, unless it has // 66 // already appeared -- in which case it's randomly generated. // 67 // // 68 // * if 'item' is an object: // 69 // * an '_id' field, if present // 70 // * otherwise, the index in the array // 71 // // 72 // * if 'item' is a number or string, use that value // 73 // // 74 // XXX this can be generalized by allowing {{#each}} to accept a // 75 // general 'key' argument which could be a function, a dotted // 76 // field name, or the special @index value. // 77 var lastSeqArray = []; // elements are objects of form {_id, item} // 78 var computation = Tracker.autorun(function () { // 79 var seq = sequenceFunc(); // 80 // 81 Tracker.nonreactive(function () { // 82 var seqArray; // same structure as `lastSeqArray` above. // 83 // 84 if (activeObserveHandle) { // 85 // If we were previously observing a cursor, replace lastSeqArray with // more up-to-date information. Then stop the old observe. // 87 lastSeqArray = _.map(lastSeq.fetch(), function (doc) { // 88 return {_id: doc._id, item: doc}; // 89 }); // 90 activeObserveHandle.stop(); // 91 activeObserveHandle = null; // 92 } // 93 // 94 if (!seq) { // 95 seqArray = seqChangedToEmpty(lastSeqArray, callbacks); // 96 } else if (seq instanceof Array) { // 97 seqArray = seqChangedToArray(lastSeqArray, seq, callbacks); // 98 } else if (isStoreCursor(seq)) { // 99 var result /* [seqArray, activeObserveHandle] */ = // 100 seqChangedToCursor(lastSeqArray, seq, callbacks); // 101 seqArray = result[0]; // 102 activeObserveHandle = result[1]; // 103 } else { // 104 throw badSequenceError(); // 105 } // 106 // 107 diffArray(lastSeqArray, seqArray, callbacks); // 108 lastSeq = seq; // 109 lastSeqArray = seqArray; // 110 }); // 111 }); // 112 // 113 return { // 114 stop: function () { // 115 computation.stop(); // 116 if (activeObserveHandle) // 117 activeObserveHandle.stop(); // 118 } // 119 }; // 120 }, // 121 // 122 // Fetch the items of `seq` into an array, where `seq` is of one of the // 123 // sequence types accepted by `observe`. If `seq` is a cursor, a // 124 // dependency is established. // 125 fetch: function (seq) { // 126 if (!seq) { // 127 return []; // 128 } else if (seq instanceof Array) { // 129 return seq; // 130 } else if (isStoreCursor(seq)) { // 131 return seq.fetch(); // 132 } else { // 133 throw badSequenceError(); // 134 } // 135 } // 136 }; // 137 // 138 var badSequenceError = function () { // 139 return new Error("{{#each}} currently only accepts " + // 140 "arrays, cursors or falsey values."); // 141 }; // 142 // 143 var isStoreCursor = function (cursor) { // 144 return cursor && _.isObject(cursor) && // 145 _.isFunction(cursor.observe) && _.isFunction(cursor.fetch); // 146 }; // 147 // 148 // Calculates the differences between `lastSeqArray` and // 149 // `seqArray` and calls appropriate functions from `callbacks`. // 150 // Reuses Minimongo's diff algorithm implementation. // 151 var diffArray = function (lastSeqArray, seqArray, callbacks) { // 152 var diffFn = Package['diff-sequence'].DiffSequence.diffQueryOrderedChanges; // 153 var oldIdObjects = []; // 154 var newIdObjects = []; // 155 var posOld = {}; // maps from idStringify'd ids // 156 var posNew = {}; // ditto // 157 var posCur = {}; // 158 var lengthCur = lastSeqArray.length; // 159 // 160 _.each(seqArray, function (doc, i) { // 161 newIdObjects.push({_id: doc._id}); // 162 posNew[idStringify(doc._id)] = i; // 163 }); // 164 _.each(lastSeqArray, function (doc, i) { // 165 oldIdObjects.push({_id: doc._id}); // 166 posOld[idStringify(doc._id)] = i; // 167 posCur[idStringify(doc._id)] = i; // 168 }); // 169 // 170 // Arrays can contain arbitrary objects. We don't diff the // 171 // objects. Instead we always fire 'changedAt' callback on every // 172 // object. The consumer of `observe-sequence` should deal with // 173 // it appropriately. // 174 diffFn(oldIdObjects, newIdObjects, { // 175 addedBefore: function (id, doc, before) { // 176 var position = before ? posCur[idStringify(before)] : lengthCur; // 177 // 178 if (before) { // 179 // If not adding at the end, we need to update indexes. // 180 // XXX this can still be improved greatly! // 181 _.each(posCur, function (pos, id) { // 182 if (pos >= position) // 183 posCur[id]++; // 184 }); // 185 } // 186 // 187 lengthCur++; // 188 posCur[idStringify(id)] = position; // 189 // 190 callbacks.addedAt( // 191 id, // 192 seqArray[posNew[idStringify(id)]].item, // 193 position, // 194 before); // 195 }, // 196 movedBefore: function (id, before) { // 197 if (id === before) // 198 return; // 199 // 200 var oldPosition = posCur[idStringify(id)]; // 201 var newPosition = before ? posCur[idStringify(before)] : lengthCur; // 202 // 203 // Moving the item forward. The new element is losing one position as it // 204 // was removed from the old position before being inserted at the new // 205 // position. // 206 // Ex.: 0 *1* 2 3 4 // 207 // 0 2 3 *1* 4 // 208 // The original issued callback is "1" before "4". // 209 // The position of "1" is 1, the position of "4" is 4. // 210 // The generated move is (1) -> (3) // 211 if (newPosition > oldPosition) { // 212 newPosition--; // 213 } // 214 // 215 // Fix up the positions of elements between the old and the new positions // 216 // of the moved element. // 217 // // 218 // There are two cases: // 219 // 1. The element is moved forward. Then all the positions in between // 220 // are moved back. // 221 // 2. The element is moved back. Then the positions in between *and* the // element that is currently standing on the moved element's future // 223 // position are moved forward. // 224 _.each(posCur, function (elCurPosition, id) { // 225 if (oldPosition < elCurPosition && elCurPosition < newPosition) // 226 posCur[id]--; // 227 else if (newPosition <= elCurPosition && elCurPosition < oldPosition) // 228 posCur[id]++; // 229 }); // 230 // 231 // Finally, update the position of the moved element. // 232 posCur[idStringify(id)] = newPosition; // 233 // 234 callbacks.movedTo( // 235 id, // 236 seqArray[posNew[idStringify(id)]].item, // 237 oldPosition, // 238 newPosition, // 239 before); // 240 }, // 241 removed: function (id) { // 242 var prevPosition = posCur[idStringify(id)]; // 243 // 244 _.each(posCur, function (pos, id) { // 245 if (pos >= prevPosition) // 246 posCur[id]--; // 247 }); // 248 // 249 delete posCur[idStringify(id)]; // 250 lengthCur--; // 251 // 252 callbacks.removedAt( // 253 id, // 254 lastSeqArray[posOld[idStringify(id)]].item, // 255 prevPosition); // 256 } // 257 }); // 258 // 259 _.each(posNew, function (pos, idString) { // 260 var id = idParse(idString); // 261 if (_.has(posOld, idString)) { // 262 // specifically for primitive types, compare equality before // 263 // firing the 'changedAt' callback. otherwise, always fire it // 264 // because doing a deep EJSON comparison is not guaranteed to // 265 // work (an array can contain arbitrary objects, and 'transform' // 266 // can be used on cursors). also, deep diffing is not // 267 // necessarily the most efficient (if only a specific subfield // 268 // of the object is later accessed). // 269 var newItem = seqArray[pos].item; // 270 var oldItem = lastSeqArray[posOld[idString]].item; // 271 // 272 if (typeof newItem === 'object' || newItem !== oldItem) // 273 callbacks.changedAt(id, newItem, oldItem, pos); // 274 } // 275 }); // 276 }; // 277 // 278 seqChangedToEmpty = function (lastSeqArray, callbacks) { // 279 return []; // 280 }; // 281 // 282 seqChangedToArray = function (lastSeqArray, array, callbacks) { // 283 var idsUsed = {}; // 284 var seqArray = _.map(array, function (item, index) { // 285 var id; // 286 if (typeof item === 'string') { // 287 // ensure not empty, since other layers (eg DomRange) assume this as well // 288 id = "-" + item; // 289 } else if (typeof item === 'number' || // 290 typeof item === 'boolean' || // 291 item === undefined) { // 292 id = item; // 293 } else if (typeof item === 'object') { // 294 id = (item && _.has(item, '_id')) ? item._id : index; // 295 } else { // 296 throw new Error("{{#each}} doesn't support arrays with " + // 297 "elements of type " + typeof item); // 298 } // 299 // 300 var idString = idStringify(id); // 301 if (idsUsed[idString]) { // 302 if (typeof item === 'object' && '_id' in item) // 303 warn("duplicate id " + id + " in", array); // 304 id = Random.id(); // 305 } else { // 306 idsUsed[idString] = true; // 307 } // 308 // 309 return { _id: id, item: item }; // 310 }); // 311 // 312 return seqArray; // 313 }; // 314 // 315 seqChangedToCursor = function (lastSeqArray, cursor, callbacks) { // 316 var initial = true; // are we observing initial data from cursor? // 317 var seqArray = []; // 318 // 319 var observeHandle = cursor.observe({ // 320 addedAt: function (document, atIndex, before) { // 321 if (initial) { // 322 // keep track of initial data so that we can diff once // 323 // we exit `observe`. // 324 if (before !== null) // 325 throw new Error("Expected initial data from observe in order"); // 326 seqArray.push({ _id: document._id, item: document }); // 327 } else { // 328 callbacks.addedAt(document._id, document, atIndex, before); // 329 } // 330 }, // 331 changedAt: function (newDocument, oldDocument, atIndex) { // 332 callbacks.changedAt(newDocument._id, newDocument, oldDocument, // 333 atIndex); // 334 }, // 335 removedAt: function (oldDocument, atIndex) { // 336 callbacks.removedAt(oldDocument._id, oldDocument, atIndex); // 337 }, // 338 movedTo: function (document, fromIndex, toIndex, before) { // 339 callbacks.movedTo( // 340 document._id, document, fromIndex, toIndex, before); // 341 } // 342 }); // 343 initial = false; // 344 // 345 return [seqArray, observeHandle]; // 346 }; // 347 // 348 /////////////////////////////////////////////////////////////////////////////////// }).call(this); /* Exports */ if (typeof Package === 'undefined') Package = {}; Package['observe-sequence'] = { ObserveSequence: ObserveSequence }; })();
test/PopoverSpec.js
apisandipas/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Popover from '../src/Popover'; describe('Popover', function () { it('Should output a popover title and content', function () { let instance = ReactTestUtils.renderIntoDocument( <Popover title="Popover title"> <strong>Popover Content</strong> </Popover> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'popover-title')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'popover-content')); assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong')); }); });
Redux-Weather/src/containers/searchBar.js
vivekbharatha/ModernReactWithReduxCourseUdemy
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from './../actions/index'; class SearchBar extends Component { constructor(props){ super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onSearchFormSubmit = this.onSearchFormSubmit.bind(this); } render() { return ( <form className="input-group" onSubmit={this.onSearchFormSubmit}> <input className="form-control" placeholder="Grab 5 day forecast in any city" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } onInputChange(event) { this.setState({ term: event.target.value }); } onSearchFormSubmit(event) { event.preventDefault(); // Let's call OpenWeatherAPI here and nail it! this.props.fetchWeather(this.state.term); this.setState({ term: '' }); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
stories/Welcome.js
OperationCode/operationcode_frontend
import React from 'react'; const styles = { main: { margin: 15, maxWidth: 600, lineHeight: 1.4, fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif', }, logo: { width: 200, }, link: { color: '#1474f3', textDecoration: 'none', borderBottom: '1px solid #1474f3', paddingBottom: 2, }, code: { fontSize: 15, fontWeight: 600, padding: "2px 5px", border: "1px solid #eae9e9", borderRadius: 4, backgroundColor: '#f3f2f2', color: '#3a3a3a', }, note: { opacity: 0.5, } }; export default class Welcome extends React.Component { showApp(e) { e.preventDefault(); if(this.props.showApp) this.props.showApp(); } render() { return ( <div style={styles.main}> <h1>Welcome to STORYBOOK</h1> <p> This is a UI component dev environment for your app. </p> <p> We've added some basic stories inside the <code style={styles.code}>src/stories</code> directory. <br/> A story is a single state of one or more UI components. You can have as many stories as you want. <br/> (Basically a story is like a visual test case.) </p> <p> See these sample <a style={styles.link} href='#' onClick={this.showApp.bind(this)}>stories</a> for a component called <code style={styles.code}>Button</code>. </p> <p> Just like that, you can add your own components as stories. <br /> You can also edit those components and see changes right away. <br /> (Try editing the <code style={styles.code}>Button</code> component located at <code style={styles.code}>src/stories/Button.js</code>.) </p> <p> This is just one thing you can do with Storybook. <br/> Have a look at the <a style={styles.link} href="https://github.com/kadirahq/react-storybook" target="_blank">React Storybook</a> repo for more information. </p> <p style={styles.note}> <b>NOTE:</b> <br/> Have a look at the <code style={styles.code}>.storybook/webpack.config.js</code> to add webpack loaders and plugins you are using in this project. </p> </div> ); } }
app/javascript/mastodon/features/explore/links.js
musashino205/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import Story from './components/story'; import LoadingIndicator from 'mastodon/components/loading_indicator'; import { connect } from 'react-redux'; import { fetchTrendingLinks } from 'mastodon/actions/trends'; const mapStateToProps = state => ({ links: state.getIn(['trends', 'links', 'items']), isLoading: state.getIn(['trends', 'links', 'isLoading']), }); export default @connect(mapStateToProps) class Links extends React.PureComponent { static propTypes = { links: ImmutablePropTypes.list, isLoading: PropTypes.bool, dispatch: PropTypes.func.isRequired, }; componentDidMount () { const { dispatch } = this.props; dispatch(fetchTrendingLinks()); } render () { const { isLoading, links } = this.props; return ( <div className='explore__links'> {isLoading ? (<LoadingIndicator />) : links.map(link => ( <Story key={link.get('id')} url={link.get('url')} title={link.get('title')} publisher={link.get('provider_name')} sharedTimes={link.getIn(['history', 0, 'accounts']) * 1 + link.getIn(['history', 1, 'accounts']) * 1} thumbnail={link.get('image')} blurhash={link.get('blurhash')} /> ))} </div> ); } }
packages/material-ui-icons/src/CallSplit.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let CallSplit = props => <SvgIcon {...props}> <path d="M14 4l2.29 2.29-2.88 2.88 1.42 1.42 2.88-2.88L20 10V4zm-4 0H4v6l2.29-2.29 4.71 4.7V20h2v-8.41l-5.29-5.3z" /> </SvgIcon>; CallSplit = pure(CallSplit); CallSplit.muiName = 'SvgIcon'; export default CallSplit;
files/domcom/0.5.2/domcom.min.js
as-com/jsdelivr
!function(t){function e(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return t[i].call(r.exports,r,r.exports,e),r.loaded=!0,r.exports}var n={};return e.m=t,e.c=n,e.p="/assets/",e(0)}([function(t,e,n){var i,r;t.exports=i=n(2),"undefined"!=typeof window&&(window.dc=i),i.DomNode=n(4),i.extend=r=n(3),i.EventMixin=n(8),r(i,i.flow=n(6)),n(9),i.bindings=i.flow.bindings,n(10),r(i,n(1),n(5),n(11),n(12),n(46)),i.property=n(41),i.builtinDirectives=n(47),r(i,i.property,i.builtinDirectives)},function(t,e){var n,i,r,o,s=[].slice;e.isArray=o=function(t){return"[object Array]"===Object.prototype.toString.call(t)},e.isObject=function(t){return"object"==typeof t&&null!==t},e.cloneObject=function(t){var e,n;n={};for(e in t)n[e]=t[e];return n},e.pairListDict=function(){var t,e,n,i;for(e=1<=arguments.length?s.call(arguments,0):[],1===e.length&&(e=e[0]),n=e.length,t=0,i={};n>t;)i[e[t]]=e[t+1],t+=2;return i},n=function(t,e){var n,i;for(i="",n=0;n++<e;)i+=t;return i},e.newLine=function(t,e,i){return i?"\n"+n(" ",e)+t:t},e.funcString=function(t){var e,n;if("function"!=typeof t){if(null==t)return"null";if(t.getBaseComponent)return t.toString();try{return JSON.stringify(t)}catch(i){return e=i,t.toString()}}return n=t.toString(),t.invalidate?n:(n="function (){"===n.slice(0,12)?n.slice(12,n.length-1):"function () {"===n.slice(0,13)?n.slice(13,n.length-1):n.slice(9),n=n.trim(),"return "===n.slice(0,7)&&(n=n.slice(7)),";"===n[n.length-1]&&(n=n.slice(0,n.length-1)),"fn:"+n)},i=1,e.newDcid=function(){return i++},e.isEven=function(t){for(0>t&&(t=-t);t>0;)t-=2;return 0===t},e.matchCurvedString=function(t,e){var n,i;if("("===t[e])for(i=0;n=t[++e];)if("\\"===n){if(!(n=t[++e]))return}else if("("===n)i++;else if(")"===n){if(0===i)return++e;i--}},e.intersect=function(t){var e,n,i,r,o,s,a,h;o={},i=t[0];for(n in i){for(e=!0,h=t.slice(1),s=0,a=h.length;a>s;s++)if(r=h[s],!r[n]){e=!1;break}e&&(o[n]=i[n])}return o},e.substractSet=function(t,e){var n;for(n in e)delete t[n];return t},e.binarySearch=function(t,e){var n,i,r,o;if(r=e.length,!r)return 0;if(1===r)return e[0]>=t?0:1;for(o=0,n=r-1;;){if(i=o+Math.floor((n-o)/2),o===n)return e[i]>=t?i:i+1;if(t===e[i])return i;if(t===e[i+1])return i+1;if(t<e[i])n=i;else{if(!(t>e[i+1]))return i+1;o=i+1}}},e.binaryInsert=function(t,e){var n,i,r,o;if(r=e.length,!r)return e[0]=t,0;if(1===r)return e[0]===t?0:e[0]>t?(e[1]=e[0],e[0]=t,0):(e[1]=t,1);for(o=0,n=r-1;;){if(i=o+Math.floor((n-o)/2),o===n)return e[i]===t?i:e[i]>t?(e.splice(i,0,t),i):(e.splice(i+1,0,t),i+1);if(t===e[i])return i;if(t===e[i+1])return i+1;if(t<e[i])n=i;else{if(!(t>e[i+1]))return e.splice(i+1,0,t),i+1;o=i+1}}},e.foreach=function(t,e){var n,i,r,s,a,h;if(t){if(o(t))for(s=[],n=a=0,h=t.length;h>a;n=++a)i=t[n],s.push(e(i,n));else{s={};for(r in t)i=t[r],s[r]=e(i,r)}return s}},r=Object.hasOwnProperty,e.mixin=function(t,e){var n,i;for(n in e)i=e[n],r.call(t,n)||(t[n]=i);return t},e.makeReactMap=function(t){var e,n,i,r,o,s,a,h,c,l,u;for(s={},i=t.split(/\s*,\s*/),a=0,c=i.length;c>a;a++)if(n=i[a],r=n.trim().split(/\s*:\s*/),1===r.length)s[r[0]]="";else for(o=r[1],u=r[0].split(/\s+/),h=0,l=u.length;l>h;h++)e=u[h],s[e]=o;return s}},function(t,e,n){var i,r,o,s,a,h;a=n(3),i=n(4),r=n(5).addEventListener,h=n(7),t.exports=o=function(t,e){if("string"==typeof t)return o(e?document.querySelectorAll(t):document.querySelector(t));if(t instanceof Node)return t.component?t.component:new i(t);if(t instanceof NodeList||t instanceof Array)return new i(t);throw new Error("error type for dc")},o.toString=function(){return"domcom"},o.directiveRegistry=s={},o.clearDirectives=function(){return o.directiveRegistry=s={}},o.directives=function(t,e){var n,i,r;if(1===arguments.length){r=[];for(i in t)n=t[i],"$"!==i[0]&&(i="$"+i),r.push(s[i]=n);return r}return"$"!==t[0]&&(t="$"+t),s[t]=e},"undefined"!=typeof window&&(window.$document=o.$document=new i(document)),o.ready=function(){o.listeners.ready&&o.emit("ready")},"undefined"!=typeof window&&(r(document,"DOMContentLoaded",o.ready,!1),r(document,"DOMContentLoaded",function(){return window.$body=o.$body=new i(document.body)})),a(o,n(8))},function(t,e){var n,i=Object.prototype.hasOwnProperty,r=Object.prototype.toString,o=function(t){return"function"==typeof Array.isArray?Array.isArray(t):"[object Array]"===r.call(t)},s=function(t){"use strict";if(!t||"[object Object]"!==r.call(t))return!1;var e=i.call(t,"constructor"),o=t.constructor&&t.constructor.prototype&&i.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!e&&!o)return!1;var s;for(s in t);return s===n||i.call(t,s)};t.exports=function a(){"use strict";var t,e,i,r,h,c,l=arguments[0],u=1,d=arguments.length,f=!1;for("boolean"==typeof l?(f=l,l=arguments[1]||{},u=2):("object"!=typeof l&&"function"!=typeof l||null==l)&&(l={});d>u;++u)if(t=arguments[u],null!=t)for(e in t)i=l[e],r=t[e],l!==r&&(f&&r&&(s(r)||(h=o(r)))?(h?(h=!1,c=i&&o(i)?i:[]):c=i&&s(i)?i:{},l[e]=a(f,c,r)):r!==n&&(l[e]=r));return l}},function(t,e,n){var i,r,o,s,a,h;o=n(1).newLine,h=n(5),r=h.addEventListener,a=h.removeEventListener,s=function(t,e,n,i){var r,o,s;if(null==i){if("string"==typeof n)return t[n];for(i=o=0,s=n.length;s>o;i=++o)r=n[i],(null==cacheProps[r]||i!==cacheProps[r])&&(cacheProps[r]=t[r]=i)}else if(null==cacheProps[n]||i!==cacheProps[n])return cacheProps[n]=this.node[n]=i},t.exports=i=function(){function t(t){var e;this.node=t,t instanceof Node?(this.cacheProps={},this.cacheStyle={}):(this.cacheProps=function(){var t,n,i,r;for(i=this.node,r=[],t=0,n=i.length;n>t;t++)e=i[t],r.push({});return r}.call(this),this.cacheStyle=function(){var t,n,i,r;for(i=this.node,r=[],t=0,n=i.length;n>t;t++)e=i[t],r.push({});return r}.call(this))}return t.prototype.prop=function(t,e){var n,i,r,o,a;if(r=this.node,!arguments.length)return r;if(r instanceof Node)return s(r,this.cacheProps,t,e);for(n=o=0,a=r.length;a>o;n=++o)i=r[n],s(i,this.cacheProps[n],t,e)},t.prototype.css=function(t,e){var n,i,r,o,a;if(r=this.node,!arguments.length)return ndoe.style;if(r instanceof Node)return s(r.style,this.cacheStyle,t,e);for(n=o=0,a=r.length;a>o;n=++o)i=r[n],s(i.style,this.cacheStyle[n],t,e)},t.prototype.bind=function(t,e){var n,i,o,s,a,h,c,l;for(o=this.node,l=t.split(/\s+/),s=0,h=l.length;h>s;s++)if(i=l[s],"on"===i.slice(0,2)&&(i=i.slice(2)),o instanceof Node)r(o,i,e);else for(a=0,c=o.length;c>a;a++)n=o[a],r(n,i,e)},t.prototype.unbind=function(t,e){var n,i,r,o,s,h,c,l;for(r=this.node,l=t.split(/\s+/),o=0,h=l.length;h>o;o++)if(i=l[o],"on"===i.slice(0,2)&&(i=i.slice(2)),r instanceof Node)a(r,i,e);else for(s=0,c=r.length;c>s;s++)n=r[s],a(n,i,e)},t.prototype.toString=function(t,e){return null==t&&(t=0),o("",t,e)+"<DomNode>"+o(this.node.toString(),t+2,!0)+o("</DomNode>",t,!0)},t}()},function(t,e,n){var i;"undefined"!=typeof window&&(e.normalizeDomElement=function(t){return"string"==typeof t&&(t=document.querySelector(t)),t}),e.getBindProp=function(t){var e;if(e=t.tagName)return"textarea"===e||"select"===e?"value":"checkbox"===t.props.type?"checked":"value";throw new Error("trying to bind a Component which is not a Tag")},"undefined"!=typeof window&&(document.addEventListener?(e.addEventListener=function(t,e,n,i){t.addEventListener(e,n,i)},e.removeEventListener=function(t,e,n){t.removeEventListener(e,n)}):(e.addEventListener=function(t,e,n){t.attachEvent(e,n)},e.removeEventListener=function(t,e,n){t.detachEvent(e,n)}),e.isElement=function(t){return"object"==typeof HTMLElement?t instanceof HTMLElement:t&&"object"==typeof t&&null!==t&&1===t.nodeType&&"string"==typeof t.nodeName}),i=n(6).renew,e.domField=function(t,e){var n;return null==t?"":"function"!=typeof t?t.then&&t["catch"]?(n=react(function(){return n.promiseResult}),t.then(function(t){return n.promiseResult=t,n.invalidate()})["catch"](function(t){return n.promiseResult=t,n.invalidate()}),n):t:t.bindComponent?t.bindComponent(e):t.invalidate?t:i(t)},e.domValue=function(t,e){return null==t?"":"function"!=typeof t?t:(t=t.call(e),null==t?"":t)},e.extendChildFamily=function(t,e){var n;for(n in e.family){if(t[n])throw new Error("do not allow to have the same component to be referenced in different location of one List");t[n]=!0}}},function(t,e,n){var i,r,o,s,a,h,c,l,u=[].slice;l=n(1),s=l.newLine,r=l.funcString,a=function(t){return t.invalidate?t:(t.valid=!1,t.invalidateCallbacks=[],t.onInvalidate=function(e){var n;if("function"!=typeof e)throw new Error("call back should be a function");return n=t.invalidateCallbacks||(t.invalidateCallbacks=[]),n.push(e)},t.offInvalidate=function(e){var n,i;return i=t.invalidateCallbacks,i&&(n=i.indexOf(e))>=0&&(i.splice(n,1),i.length||(t.invalidateCallbacks=null)),t},t.invalidate=function(){var e,n,i,r;if(t.valid&&t.invalidateCallbacks){for(r=t.invalidateCallbacks,n=0,i=r.length;i>n;n++)(e=r[n])();t.valid=!1}return t},t)},h=function(t){var e;return e=function(){var n;if(arguments.length)throw new Error("flow.renew is not allowed to accept arguments");return n=t.call(this),e.valid=!0,e.invalidate(),n},e.toString=function(){return"renew: "+r(t)},a(e)},o=function(t){return a(t),t.invalidate=function(){var e,n,i,r;if(t.invalidateCallbacks)for(r=t.invalidateCallbacks,n=0,i=r.length;i>n;n++)(e=r[n])();return t},t.toString=function(){return"lazy: "+r(t)},t},t.exports=i=function(){var t,e,n,i,s,c,l,d,f,p;if(i=2<=arguments.length?u.call(arguments,0,c=arguments.length-1):(c=0,[]),e=arguments[c++],!i.length)return o(e);for(l=0,f=i.length;f>l;l++)if(n=i[l],"function"==typeof n&&!n.invalidate)return h(e);for(t=null,s=a(function(n){return arguments.length?n===t?n:(t=e.call(this,n),s.invalidate(),t):s.valid?t:(s.valid=!0,t=e.call(this))}),d=0,p=i.length;p>d;d++)n=i[d],n&&n.onInvalidate&&n.onInvalidate(s.invalidate);return s.toString=function(){return"flow: ["+function(){var t,e,r;for(r=[],t=0,e=i.length;e>t;t++)n=i[t],r.push(n.toString());return r}().join(",")+"] --> "+r(e)},s},i.pipe=function(){var t,e,n,i,r,o,s,h,c;for(n=2<=arguments.length?u.call(arguments,0,r=arguments.length-1):(r=0,[]),t=arguments[r++],o=0,h=n.length;h>o;o++)if(e=n[o],"function"==typeof e&&!e.invalidate)return i=a(function(){var r,o,s,a;if(arguments.length)throw new Error("flow.pipe is not allow to have arguments");for(r=[],s=0,a=n.length;a>s;s++)e=n[s],"function"==typeof e?r.push(e()):r.push(e);return o=t.apply(this,r),i.valid=!0,i.invalidate(),o});for(i=a(function(){var r,o,s;for(i.valid=!0,r=[],o=0,s=n.length;s>o;o++)e=n[o],"function"==typeof e?r.push(e()):r.push(e);return t.apply(this,r)}),s=0,c=n.length;c>s;s++)e=n[s],e&&e.onInvalidate&&e.onInvalidate(i.invalidate);return i},i.react=a,i.lazy=o,i.renew=h,i.flow=i,i.see=c=function(t,e){var n,i;return n=t,i=function(t){return arguments.length?(t=e?e(t):t,t!==n&&(n=t,i.invalidate()),t):(i.valid=!0,n)},i.isDuplex=!0,i.toString=function(){return"see: "+t},a(i)},i.seeN=function(){var t,e,n,i,r;for(e=1<=arguments.length?u.call(arguments,0):[],r=[],n=0,i=e.length;i>n;n++)t=e[n],r.push(c(t));return r},Object.defineProperty?(i.bind=function(t,e,n){var i,r,o,s;return i=Object.getOwnPropertyDescriptor(t,e),i&&(r=i.get,o=i.set),r&&r.invalidate||(r=function(){if(arguments.length)throw new Error("should not set value on flow.bind");return r.valid=!0,r.cacheValue},r.cacheValue=t[e],s=function(n){return n!==t[e]?(o&&o.call(t,n),r.cacheValue=n,r.invalidate(),n):void 0},a(r),r.toString=function(){return""+(n||"m")+"["+e+"]"},Object.defineProperty(t,e,{get:r,set:s})),r},i.duplex=function(t,e,n){var i,r,o,s;return i=Object.getOwnPropertyDescriptor(t,e),i&&(r=i.get,s=i.set),s&&s.invalidate?s:(o=function(n){return arguments.length?n!==t[e]?(s&&s.call(t,n),r&&r.invalidate&&r.invalidate(),o.cacheValue=n,o.invalidate(),n):void 0:(o.valid=!0,o.cacheValue)},o.cacheValue=t[e],a(o),o.isDuplex=!0,o.toString=function(){return""+(n||"m")+"["+e+"]"},Object.defineProperty(t,e,{get:o,set:o}),o)}):(i.bind=function(t,e,n){var i,r;return r=t._dcBindMethodMap,r||(r=t._dcBindMethodMap={}),t.dcSet$||(t.dcSet$=function(e,n){var i;return n!==t[e]?(r&&r[e]&&r[e].invalidate(),(i=this._dcDuplexMethodMap)&&i[e]&&i[e].invalidate()):void 0}),i=r[e],i||(i=r[e]=function(){return i.valid=!0,t[e]},i.toString=function(){return""+(n||"m")+"["+e+"]"},a(i)),i},i.duplex=function(t,e,n){var i,r;return r=t._dcDuplexMethodMap,r||(r=t._dcDuplexMethodMap={}),t.dcSet$||(t.dcSet$=function(e,n){var i;return n!==t[e]&&((i=this._dcBindMethodMap)&&i[e]&&i[e].invalidate(),r&&r[e]&&r[e].invalidate()),n}),i=r[e],i||(i=r[e]=function(n){return arguments.length?t.dcSet$(e,n):(i.valid=!0,t[e])},i.isDuplex=!0,i.toString=function(){return""+(n||"m")+"["+e+"]"},a(i)),i}),i.unary=function(t,e){return"function"!=typeof t?e(t):t.invalidate?i(t,function(){return e(t())}):function(){return e(t())}},i.binary=function(t,e,n){return"function"==typeof t&&"function"==typeof e?t.invalidate&&e.invalidate?i(t,e,function(){return n(t(),e())}):function(){return n(t(),e())}:"function"==typeof t?t.invalidate?i(t,function(){return n(t(),e)}):function(){return n(t(),e)}:"function"==typeof e?e.invalidate?i(e,function(){return n(t,e())}):function(){return n(t,e())}:n(t,e)}},function(t,e){t.exports=function(t){return t&&null!=t.renderDom}},function(t,e){var n,i=[].slice;t.exports=n={on:function(t,e){var n,i,r,o,s,a;if(arguments.length||dc.error("missing arguments for Component.on(event, callback)"),1===arguments.length)if(t&&"object"==typeof t)for(i in t)e=t[i],this.on(i,e);else dc.error("wrong arguments for Component.on(event, callback)");else for(e||dc.error("Component.on: callback is undefined for event: "+t),(r=this.listeners)||(this.listeners=r={}),a=t.split(/\s*,\s*|\s+/),o=0,s=a.length;s>o;o++)t=a[o],(n=r[t])?n.indexOf(e)<0&&n.push(e):r[t]=[e];return this},off:function(t,e){var n,i,r,o,s,a,h,c,l;if(arguments.length)if(1===arguments.length)for(r=this.listeners,c=t.split(/\s*,\s*|\s+/),o=0,a=c.length;a>o;o++)t=c[o],r[t]=null;else for(r=this.listeners,l=t.split(/\s*,\s*|\s+/),s=0,h=l.length;h>s;s++)t=l[s],n=r[t],n&&(i=n.indexOf(e))>=0&&(n.splice(i,1),n.length||(r[t]=null));else this.listeners={};return this},once:function(t,e){var n;return e||dc.error("Component.once: callback is undefined for event: "+t),n=function(){var r;return r=1<=arguments.length?i.call(arguments,0):[],this.off(t,n),e.apply(this,r)},this.on(t,n)},emit:function(){var t,e,n,r,o,s,a;if(r=arguments[0],t=2<=arguments.length?i.call(arguments,1):[],!this.destroyed)if(this.listeners&&(n=this.listeners[r]))for(n=n.slice(),s=0,a=n.length;a>s;s++)e=n[s],e.apply(this,t);else(o=this["on"+r])&&o.apply(this,t);return this}}},function(t,e,n){var i,r,o,s,a,h,c,l;l=n(6),a=l.react,h=l.see,r=l.bind,o=l.duplex,s=l.flow,c=l.unary,i=l.binary,t.exports=s,s.bindings=function(t,e){var n,i;i={};for(n in t)i[n+"$"]=o(t,n,e),i[n+"_"]=r(t,n,e);return i},s.seeAttrs=function(t,e){var n,i,r;for(i in e)r=e[i],n=t[i],"function"==typeof n?n(r):t[i]=h(r);return t},s.neg=function(t){return c(t,function(t){return-t})},s.not=function(t){return c(t,function(t){return!t})},s.bitnot=function(t){return c(t,function(t){return~t})},s.reciprocal=function(t){return c(t,function(t){return 1/t})},s.abs=function(t){return c(t,Math.abs)},s.floor=function(t){return c(t,Math.floor)},s.ceil=function(t){return c(t,Math.ceil)},s.round=function(t){return c(t,Math.round)},s.add=function(t,e){return i(t,e,function(t,e){return t+e})},s.sub=function(t,e){return i(t,e,function(t,e){return t-e})},s.mul=function(t,e){return i(t,e,function(t,e){return t*e})},s.div=function(t,e){return i(t,e,function(t,e){return t/e})},s.min=function(t,e){return i(t,e,function(t,e){return Math.min(t,e)})},s.and=function(t,e){return i(t,e,function(t,e){return t&&e})},s.or=function(t,e){return i(t,e,function(t,e){return t||e})},s.funcAttr=function(t,e){return s(t,e,function(n){var i;return i=t(),null==i?i:arguments.length?i[e]=n:i[e]})},s.toggle=function(t){return t(!t())},s.if_=function(t,e,n){return"function"!=typeof t?t?e:n:t.invalidate?"function"==typeof e&&"function"==typeof n?e.invalidate&&n.invalidate?s(t,e,n,function(){return t()?e():n()}):function(){return t()?e():n()}:"function"==typeof e?e.invalidate?s(t,e,function(){return t()?e():n}):function(){return t()?e():n}:"function"==typeof n?n.invalidate?s(n,function(){return t()?e:n()}):function(){return t()?e:n()}:s(t,function(){return t()?e:n}):"function"==typeof e&&"function"==typeof n?function(){return t()?e():n()}:"function"===e?function(){return t()?e():n}:"function"===n?function(){return t()?e:n()}:t()?e:n},s.thisBind=function(t){var e;return e=a(function(){return this[t]}),e.bindComponent=function(n){var i;return i=s.bind(n,t),i.onInvalidate(function(){return e.valid=!0,e.invalidate()}),e},e}},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f=[].slice;c=(s=n(6)).react,a=n(1).isArray,o=n(3),t.exports=s,l=Array.prototype.slice,s.watchList=u=function(t,e){var n;return n=t.watchingListComponents||(t.watchingListComponents={}),n[e.dcid]=e,t.eachWatching?void 0:(t.eachWatching=!0,t._shift=t.shift,t._pop=t.pop,t._push=t.push,t._reverse=t.reverse,t._sort=t.sort,t._splice=t.splice,t._unshift=t.unshift,t.shift=i.shift,t.pop=i.pop,t.push=i.push,t.reverse=i.reverse,t.sort=i.sort,t.splice=i.splice,t.unshift=i.unshift,t.setItem=i.setItem,t.setLength=i.setLength,t.updateComponents=i.updateComponents,t.updateComponent=i.updateComponent,t.getListChildren=i.getListChildren,t.replaceAll=i.replaceAll)},i={},i.getListChildren=function(t,e,n){var i,r,o;for(i=[],r=e;n>r;)o=t.getItemComponent(this[r],r),o.valid=!0,i.push(o),r++;return i},i.updateComponent=function(t,e,n){var i;return i=this.getListChildren(t,e,n),t.setChildren(e,i),this},i.updateComponents=function(t,e){var n,i,r;i=this.watchingListComponents;for(r in i)n=i[r],this.updateComponent(n,t,e);return this},i.setItem=function(){var t,e,n,i,r,o;for(e=arguments[0],i=2<=arguments.length?f.call(arguments,1):[],e>>>=0,0>e&&(e=0),t=r=0,o=i.length;o>r;t=++r)n=i[t],this[e+t]=i[t];return this.updateComponents(e,e+i.length),this},i.pop=function(){var t,e,n,i;if(this.length){n=this.watchingListComponents,e=this._pop();for(i in n)t=n[i],t.popChild();return e}},i.push=function(){var t,e,n,i,r,o,s;t=1<=arguments.length?f.call(arguments,0):[],o=this.watchingListComponents,n=this.length,r=this._push.apply(this,arguments);for(s in o)i=o[s],e=i.getItemComponent(this[n],n),i.pushChild(e);return r},i.unshift=function(){var t,e,n,i,r;if(t=1<=arguments.length?f.call(arguments,0):[],this.length){i=this.watchingListComponents,this._shift(),e=this.length;for(r in i)n=i[r],n.updateSuccChild?this.updateComponent(n,e):n.shiftChild();return this}return this},i.unshift=function(t){var e,n,i,r;this._unshift(t),n=this.watchingListComponents,r=[];for(i in n)e=n[i],e.updateSuccChild?r.push(this.updateComponent(e,this.length)):(t=e.getItemComponent(this[0],0),r.push(e.unshiftChild(t)));return r},i.reverse=function(){var t;return t=this.length,1>=t?this:(this._reverse(),this.updateComponents(0,t))},i.sort=function(){var t;return t=this.length,1>=t?this:(this._sort(),this.updateComponents(0,t))},i.splice=function(t,e){var n,i,r,o,s,a,h,c,u,d,f;if(r=l.call(arguments,2),o=r.length,0===e&&0===o)return this;if(c=this.length,t>>>=0,0>t?t=0:t>c&&(t=c),u=this._splice.apply(this,[t,e].concat(r)),h=this.length,h===c)this.updateComponents(t,t+o);else{d=this.watchingListComponents;for(f in d)if(a=d[f],a.updateSuccChild)this.updateComponent(a,t,h);else if(o>e){for(i=t,s=0;e>s;)n=a.getItemComponent(this[i],i),a.replaceChild(i,n),i++,s++;for(;o>s;)n=a.getItemComponent(this[i],i),a.insertChild(i,n),i++,s++}else{for(i=t,s=0;o>s;)n=a.getItemComponent(this[i],i),a.replaceChild(i,n),i++,s++;for(;e>s;)a.removeChild(i),s++}}return this},i.setLength=function(t){var e,n,i,r;if(n=this.length,t===n)return this;if(n>=t){i=this.watchingListComponents,this.length=t;for(r in i)e=i[r],e.setLength(t);return this}return this.updateComponents(n,t),this},i.replaceAll=function(t){return this.setItem.apply(this,[0].concat(f.call(t))),this.setLength(t.length),this},s.watchObject=d=function(t,e,n){var i;return i=t.watchingListComponents||(t.watchingListComponents={}),i[e.dcid]=e,t.eachWatching?void 0:(t.eachWatching=!0,o(t,r))},r={},r.deleteItem=function(){var t,e,n,i,r,o,s,a,h,c,l,u,d,p;if(o=1<=arguments.length?f.call(arguments,0):[],l=this.watchingListComponents,!l.length)return this;for(d=0,p=o.length;p>d;d++)if(i=o[d],this.hasOwnProperty(i)){if("$dc"===i.slice(0,3))throw new Error("do not remove the key: "+i+', which is used by "each component" of dc');delete this[i];for(u in l){a=l[u],r=a.keyChildMap,n=r[i],t=a.children,s=t.length;break}for(u in l){if(a=l[u],a.updateSuccChild){for(e=n+1,t=a.children;s>e;)c=t[e],h=a.getItemComponent(c.$watchingKey,e,this,a),a.replaceChild(c,h),e++;a.removeChild(n)}else a.removeChild(n);delete r[i]}}return this},r.setItem=function(t,e){var n,i,r,o,s,a;if(h(t))throw new Error("do not use the key: "+t+', which is used by "each component" of dc');if(s=this.watchingListComponents,this.hasOwnProperty(t)){this[t]=e;for(a in s)i=s[a],o=i.keyChildMap[t],r=i.getItemComponent(t,o,this,i),i.replaceChild(oldChild,r)}else{n=i.children.length;for(a in s)i=s[a],r=i.getItemComponent(t,n,this,i),i.pushChild(r)}return this},r.extendItems=function(t){var e,n;for(e in t)n=t[e],this.setItem(e,n);return this},r.replaceAll=function(t){var e,n,i,r;for(n=Object.keys(this),i=0,r=n.length;r>i;i++)e=n[i],t.hasOwnProperty(e)||this.deleteItem(e);return this.extendItems(t),this},s.isEachObjectSystemKey=h=function(t){return/setItem|deleteItem|extendItems|watchingListComponents|eachWatching/.test(t)},s.watchItems=function(t,e){if(!t)throw new Error("items to be watched should be an array or object.");return a(t)?u(t,e):d(t,e),e}},function(t,e,n){var i,r,o,s,a,h,c,l,u;if(i=n(1).isArray,r=n(7),"undefined"!=typeof window){if(!window.requestAnimationFrame)for(u=["webkit","ms","moz","o"],c=0,l=u.length;l>c;c++)if(h=u[c],window.requestAnimationFrame=window[h+"RequestAnimationFrame"]){window.cancelAnimationFrame=window[h+"CancelAnimationFrame"]||window[h+"CancelRequestAnimationFrame"];break}window.requestAnimationFrame||(o=0,window.requestAnimationFrame=function(t){var e,n,i;return e=(new Date).getTime(),i=Math.max(0,16-(e-o)),n=window.setTimeout(function(){t(e+i)},i),o=e+i,n}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(t){clearTimeout(t)})}dc.reset=function(){return dc.renderBySystemLoop=!1,dc.listeners={},dc.rootComponentMap={},dc.removingChildren={}},dc.reset(),dc.render=function(t){var e,n,i,r,o;if(dc.emit("willRender"),!dc.valid)for(dc.valid=!0,i=dc.rootComponentMap,dc.rootComponentMap={},e=r=0,o=i.length;o>r;e=++r)n=i[e],e.render(!0);return dc.emit("didRender")},dc.rafRender=s=function(){dc.renderBySystemLoop=!0,requestAnimFrame(s),dc.render(!0)},dc.renderWhen=function(t,e,n){var i,o,s,h,c,l,u,d,f,p,m;if(h=n.target,"string"==typeof e&&(e=e.split(/\s+/)),r(t)&&(t=[t]),t instanceof Array)for(d=0,p=t.length;p>d;d++)for(s=t[d],f=0,m=e.length;m>f;f++)c=e[f],a(s,c,h);else t===window.setInterval?(u=n.test,o=n.clear,l=null,i=function(){var t,e,n;if(!u||u()){for(e=0,n=h.length;n>e;e++)t=h[e],t.render();dc.clean()}return o&&o()?clearInterval(l):void 0},l=setInterval(i,e||16)):t===setTimeout&&(i=function(){var t,e,n;for(e=0,n=h.length;n>e;e++)t=h[e],t.render();return dc.clean()},setTimeout(i,e))},a=function(t,e,n){var i,r,o;for("on"!==e.slice(0,2)&&(e="on"+e),i=t.eventUpdateConfig[e]||(t.eventUpdateConfig[e]={}),r=0,o=n.length;o>r;r++)t=n[r],i[t.dcid]=t},dc.stopRenderWhen=function(t,e,n){var i,r;if("on"!==e.slice(0,2)&&(e="on"+e),n){if(i=t.eventUpdateConfig[e])for(r in n)t=n[r],delete i[r]}else delete t.eventUpdateConfig[e]},dc.invalidate=function(){return dc.valid=!1},dc.invalidateContent=function(t){dc.valid=!1,dc.rootComponentMap[t.dcid]=t},dc.invalidateAttach=function(){},dc.propagateChildNextNode=function(t,e){},dc.removingChildren={},dc.clean=function(){var t,e,n;n=dc.removingChildren;for(e in n)t=n[e],t.removeDom();dc.removingChildren={}}},function(t,e,n){var e,i;i=n(3),t.exports=e=i({},n(14),n(41),n(13),n(44),n(45))},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g,y,w,C,N,x,_,b,P,A,S,E,L=[].slice;S=n(14),o=S.Component,P=S.toComponent,w=S.isComponent,f=S.Tag,p=S.Text,r=S.Comment,h=S.Html,c=S.If,i=S.Case,a=S.Func,l=S.List,d=S.Pick,u=S.Nothing,s=S.Defer,C=n(1).isEven,v=n(3),e.isAttrs=y=function(t){return!("object"!=typeof t||null===t||w(t)||t instanceof Array)},E=n(1),g=E.isArray,N=E.isObject,_=n(6).renew,m=function(t){var e;return e=t[0],t.length?null==e?[{},t.slice(1)]:e instanceof Array?[{},t]:"function"==typeof e?[{},t]:"object"==typeof e?w(e)?[{},t]:[e,t.slice(1)]:[{},t]:[{},[]]},A=function(t){return t instanceof Array?t.length?1===t.length?A(t[0]):t:[]:[t]},b=e.tag=function(){var t,e,n,i,r;return i=arguments[0],t=2<=arguments.length?L.call(arguments,1):[],r=m(t),e=r[0],n=r[1],new f(i,e,A(n))},e.nstag=function(){var t,e,n,i,r,o;return r=arguments[0],i=arguments[1],t=3<=arguments.length?L.call(arguments,2):[],o=m(t),e=o[0],n=o[1],new f(r,e,A(n),i)},e.txt=function(t,e){return y(t)?new f("div",t,[new p(e)]):new p(t)},e.comment=function(t,e){return y(t)?new f("div",t,[new r(e)]):new r(t)},e.html=function(t,e,n){return new h(t,e,n)},e.if_=function(t,e,n,i,r,o){return y(t)?new f("div",t,[new c(e,n,i,r,o)]):new c(t,e,n,r,o)},e.forceIf=function(t,e,n,i){return y(t)?new f("div",t,[new c(e,n,i,!0,!1,!0)]):new c(t,e,n,!0,!1,!0)},e.mergeIf=function(t,e,n,i,r){return y(t)?new f("div",t,[new c(e,n,i,!0,r)]):new c(t,e,n,!0,r)},e.recursiveIf=function(t,e,n,i){return y(t)?new f("div",t,[new c(e,n,i,!0,!0)]):new c(t,e,n,!0,!0)},e.case_=function(t,e,n,r){return y(t)?new f("div",t,[new i(e,n,r)]):new i(t,e,n)},e.forceCase=function(t,e,n,r){return y(t)?new f("div",t,[new i(e,n,r,!0)]):new i(t,e,n,!0)},e.cond=function(){var t,e,n,i;return t=arguments[0],e=3<=arguments.length?L.call(arguments,1,i=arguments.length-1):(i=1,[]),n=arguments[i++],y(t)?(C(e)||(e.push(n),n=null),new f("div",t,[new Cond(e,n)])):(e.unshift(t),C(e)||(e.push(n),n=null),new Cond(e,n))},e.func=function(t,e){return y(t)?new f("div",t,[new a(e)]):new a(t)},e.pick=function(t,e,n){return new d(t,e,n)},e.list=x=function(){var t,e;return t=arguments[0],e=2<=arguments.length?L.call(arguments,1):[],y(t)?new f("div",t,[new l(e)]):(e.unshift(t),1===e.length?P(e[0]):new l(e))},e.defer=function(t,e,n,i,r){return y(t)?new f("div",t,[new s(e,n,i,r)]):new s(t,e,n,i)}},function(t,e,n){var i;i=n(15),t.exports={isComponent:n(7),toComponent:n(18),toComponentArray:n(27),Component:n(17),BaseComponent:n(20),ListMixin:n(28),List:n(26),Tag:n(30),Text:n(21),Comment:n(32),Cdata:n(33),Html:n(34),Nothing:n(19),TransformComponent:n(16),TestComponent:n(35),If:n(36),Case:n(38),Func:n(29),Pick:n(39),Defer:n(40),Route:i.Route,route:i}},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g,y=[].slice,w={}.hasOwnProperty,C=function(t,e){function n(){this.constructor=t}for(var i in e)w.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};r=n(16),s=n(7),m=n(18),v=n(1),a=v.isEven,h=v.matchCurvedString,t.exports=p=function(){var t,e,n,i;return n=3<=arguments.length?y.call(arguments,0,i=arguments.length-2):(i=0,[]),e=arguments[i++],t=arguments[i++],g(n,e,t,0)},g=function(t,e,n,r){var o,h,c;if("function"==typeof n?(t.push(e),t.push(n),e=null,n=r):s(n)?(t.push(e),e=n,n=r):n&&!s(n)&&n.otherwise?(t.push(e),e=n.otherwise,n=r):(n>>>=0,e&&!s(e)&&e.otherwise&&(e=e.otherwise)),h=t.length,!a(h))throw new Error("route parameter error: missing matched handler");if(2>h||"function"!=typeof t[h-1])throw new Error("route parameter error:\n expect route(pattern, handler, pattern, handler, ..., otherwise, baseIndex)");for(c=[],o=0;h>o;)c.push([t[o],t[o+1]]),o+=2;return new i(c,e,n)},p._navigateTo=u=function(t,e,n){var i,r;if(null==n&&(n=0),e=""+e,"/"!==e[0]){for(r=0;e;)if("./"===e.slice(0,2))e=e.slice(2);else{if("../"!==e.slice(0,3))break;e=e.slice(3),r++}return n-=r,0>n&&(n=0),i=t.split("/").slice(0,n).join("/")+"/","/"===i&&(i=""),e=i+e}return e=e.slice(1)},l=function(t){return function(e){var n,i;return i=window.history&&window.history.pushState?decodeURI(location.pathname+location.search).replace(/\?(.*)$/,""):(n=location.href.match(/#(.*)$/))?n[1]:"",u(i,e,t),window.history&&window.history.pushState?history.pushState(null,null,e):location.href=location.href.replace(/#(.*)$/,"")+"#"+e,e}},p.to=l(0),p.Route=i=function(t){function e(t,n,i){var r,s,a;for(this.routeList=t,this.otherwise=n,this.baseIndex=i,e.__super__.constructor.call(this),s=0,a=t.length;a>s;s++)r=t[s],r[0]=o(r[0]);this.otherwise=m(n)}return C(e,t),e.prototype.getContentComponent=function(){var t,e,n,i,r,o;for(e=this.getPath(),o=this.routeList,i=0,r=o.length;r>i;i++)if(n=o[i],t=f(n,e,this.baseIndex))return t;return this.otherwise},e.prototype.getPath=function(){var t;return window.history&&window.history.pushState?decodeURI(location.pathname+location.search).replace(/\?(.*)$/,""):(t=location.href.match(/#(.*)$/))?t[1]:""},e}(r),p._processRouteItem=f=function(t,e,n){var i,r,o,s,a,h;return s=t[0],r=t[1],s instanceof Array&&(h=s,s=h[0],a=h[1]),o=c(s,e,n),!o||a&&!(o=a(o,e,n))?void 0:(i=function(){var t,e,n,i;return n=3<=arguments.length?y.call(arguments,0,i=arguments.length-2):(i=0,[]),e=arguments[i++],t=arguments[i++],g(n,e,t,o.base)},i.to=l(o.base),m(r(o,i)))},p._processPiecePatterns=d=function(t,e,n){var i,r,o,s,a,c;for(r=0,s=t.length,a=[];i=t[r];)if(c=r,":"===i){if(i=t[++r],!i.match(/[A-Za-z_$]/))throw new Error("route pattern error: expect a parameter identifier "+t);for(i=t[++r];i&&i.match(/[$\w]/);)i=t[++r];if(r===c+1)throw new Error("route pattern error: expect a parameter identifier "+t);if(o=t.slice(c+1,r),e[o])throw new Error("route pattern error: repeated parameter name");if(e[o]=!0,"("===i){if(c=r,!(r=h(t,r)))throw new Error("route pattern error: missing ) for regexp");if(c+1===r-1)throw new Error("route pattern error: empty regexp: ()");a.push({key:o,pattern:new RegExp(t.slice(c+1,r-1))}),i=t[r]}else a.push({key:o,pattern:new RegExp("\\w+")}),++r}else if("("===i){if(!(r=h(t,r)))throw new Error("route pattern error: missing ) for regexp");if(c+1===r-1)throw new Error("route pattern error: empty regexp: ()");a.push({key:n++,pattern:new RegExp(t.slice(c+1,r-1))})}else{for(++r;(i=t[r])&&":"!==i&&"("!==i;)r++;a.push({pattern:t.slice(c,r)})}return[a,n]},p._getRoutePattern=o=function(t){var e,n,i,r,o,s,a,h,c,l,u,f,p,m;for(t=""+t,t.match(/\\\//)&&new Error("should not include /\\// in pattern"),f=""===t?[]:t.split("/"),p=0,e=!1,n=!0,i=!1,s=!1,u=[],h={},o=f.length,r=0,a=0;o>r;){if(l=f[r++],"."===l){if(n)continue;throw new Error("route pattern error: do not use ./ pattern except the start")}if(".."===l){if(n){p++;continue}throw new Error("route pattern error: do not use ../ except the start")}if(""===l)if(n)e=!0;else{if(r!==o)throw new Error("route pattern error: do not use ../ except the start");i=!0}else if("*"===l)u.push("*");else if("**"===l){if(r!==o)throw new Error("route pattern error: do not use ** except the last segment");s=!0}else m=d(l,h,a),c=m[0],a=m[1],u.push(c);n=!1}return{segmentPatterns:u,absolute:e,upCount:p,endSlash:i,moreComing:s}},p._matchRoute=c=function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g,y,w,C,N,x;if(!t.endSlash||"/"===e[e.length-1]){for(t.absolute?n=0:(n-=t.upCount,0>n&&(n=0)),"/"===e||""===e?d=[]:(d=e.split("/"),""===e[0]&&d.shift()),h=d.length,i=n,s={},g=[],x=t.segmentPatterns,o=y=0,C=x.length;C>y;o=++y){if(m=x[o],i>=h)return;if("*"!==m){for(l=0,v=u=d[i],w=0,N=m.length;N>w;w++)if(f=m[w],p=f.pattern,"string"==typeof p){if(0!==u.indexOf(p))break;u=u.slice(p.length),l+=p.length}else{if(!(c=u.match(p)))break;s[f.key]=c,l+=c[0].length}if(l!==v.length)return;g.push(v),i++}else g.push(d[i]),i++}if(i===h||t.moreComing)return r="/"+d.slice(0,n+1).join("/")+"/",a="/"+d.slice(i).join("/"),{items:s,basePath:r,segments:g,leftPath:a,base:i}}}},function(t,e,n){var i,r,o={}.hasOwnProperty,s=function(t,e){function n(){this.constructor=t}for(var i in e)o.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};i=n(17),t.exports=r=function(t){function e(){e.__super__.constructor.apply(this,arguments),this.transformValid=!1; }return s(e,t),e.prototype.isTransformComponent=!0,e.prototype.invalidate=function(){return this.valid&&(this.valid=!1,this.holder&&this.holder.invalidateContent(this)),this},e.prototype.invalidateContent=function(t){return this.invalidate()},e.prototype.invalidateAttach=function(t){return this.attachValid&&(this.attachValid=!1,this.holder&&this.holder.invalidateAttach(this)),this},e.prototype.invalidateTransform=function(){return this.transformValid&&(this.transformValid=!1,this.invalidate()),this},e.prototype.refreshDom=function(t){return this.renderDom(t),this.attachParent()},e.prototype.renderDom=function(t){var e,n;return this.emit("willRenderDom"),this.valid=!0,this.attachValid=!0,this.transformValid||(this.transformValid=!0,n=this.content,n&&n.holder===this&&(this.content.holder=null),this.content=this.getContentComponent(),this.content.clearRemoving()),n=this.content,n.holder=this,n.parentNode=this.parentNode,n.nextNode=this.nextNode,n.renderDom(t),e=n.baseComponent,this.baseComponent=e,this.node=e.node,this.firstNode=e.firstNode,this.node.parentNode||(n.attachValid=!1,this.invalidateAttach(n)),this.emit("didRenderDom"),this},e.prototype.markRemovingDom=function(){return this.removing=!0,this.holder=null,dc.removingChildren[this.dcid]=this,this.content&&this.content.markRemoving(),this},e.prototype.markRemoving=function(){this.removing=!0,this.content&&this.content.markRemoving()},e.prototype.clearRemoving=function(){this.removing=this.removed=!1,this.content&&this.content.clearRemoving()},e.prototype.removeDom=function(){return this.removing&&(this.removing=!1,this.removed=!0,this.content&&this.content.removeDom()),this},e.prototype.removeNode=function(){this.removing=!1,this.removed=!0,this.content&&this.content.removeNode()},e.prototype.attachParent=function(){var t;this.attachValid||(this.attachValid=!0,t=this.content,t.parentNode=this.parentNode,t.nextNode=this.nextNode,t.attachParent())},e.prototype.propagateChildNextNode=function(t,e){this.holder&&this.holder.propagateChildNextNode(this,e)},e}(i)},function(t,e,n){var i,r,o,s,a,h,c,l,u,d;s=n(3),u=n(5).normalizeDomElement,d=n(1),l=d.newDcid,h=d.isArray,a=n(6).flow,c=n(7),r=n(2),t.exports=i=function(){function t(){this.dcid=l(),this.listeners=this.listeners||{},this.baseComponent=null,this.parentNode=null,this.nextNode=null,this.node=null,this.holder=null,this.valid=!0,this.attachValid=!0,this.removing=!1,this.removed=!1,this.destroyed=!1,this.setReactive()}return t.prototype._prepareMount=function(t,e){if(t&&t.component)t=t.component;else if(e&&e.component)throw console.log(t),console.log(e),new Error("error while mounting: mountNode is not a component, but beforeNode is a component");if(c(t)){if(e){if(!c(e)&&(e=e.component,!e))throw console.log(e),new Error("error while mounting: can not mount beforeNode");if(e.holder!==t||!t.children)throw console.log(t),console.log(e),new Error("both mountNode and beforeNode is component, but mountNode is not the parent of beforeNode");return t.insertChildBefore(this,e)}if(!t.children)throw console.log(t),new Error("error while mounting: mountNode is a component, but is not a Tag or List component");return t.pushChild(this)}return this.parentNode=u(t)||this.parentNode||document.body,this.nextNode=e||this.nextNode,this.setHolder(r),this.clearRemoving(),r.rootComponentMap[this.dcid]=this},t.prototype.create=function(t,e,n){return this._prepareMount(t,e),this.render(n)},t.prototype.mount=function(t,e,n){return this.emit("willMount"),this._prepareMount(t,e),this.render(n),this.emit("didMount")},t.prototype.unmount=function(t){return this.emit("willUnmount"),this.remove(),this.emit("didUnmount")},t.prototype.remove=function(){var t,e,n,i;return e=this.holder,e&&e!==r?e&&e.children?e.removeChild(this):e&&r.error("Should not remove the content of TransformComponent"):(delete r.rootComponentMap[this.dcid],t=this.firstNode,t&&t.parentNode&&((i=t.previousSibling)&&(n=i.component)&&n.setNextNode(this.nextNode),this.removeNode())),this},t.prototype.render=function(t){return this.destroyed||!t&&!r.alwaysRender&&r.renderBySystemLoop||(this.removing?this.removeDom():this.removed||this.refreshDom(this.baseComponent)),this},t.prototype.replace=function(t,e){var n;return this.destroyed||this===t||t.removing||t.removed||(n=t.holder,n&&n!==r?n.isTransformComponent?r.error("Should not replace the content of TransformComponent"):(n.replaceChild(t,this),n.render(e),t.removeDom()):n===r&&(this.parentNode=t.parentNode,this.nextNode=t.nextNode,t.markRemovingDom(),this.setHolder(n),this.invalidate(),r.rootComponentMap[this.dcid]=this,r.rootComponentMap[t.dcid]=t,this.render(e),t.removeDom())),this},t.prototype.renderWhen=function(t,e,n){return n=n||{},n.target=[this],r.renderWhen(t,e,n),this},t.prototype.destroy=function(){return this.emit("willDestroy"),this.executeDestroy(),this.emit("didDestroy")},t.prototype.executeDestroy=function(){return this.unmount(!0),this.destroyed=!0,this.listeners=null,this.node&&(this.node.component=null,this.node=null),this.baseComponent=null,this.parentNode=null},t.prototype.getPrevComponent=function(){var t,e;return(e=this.holder)?(t=e.children)?t[t.indexOf(this)-1]:void 0:null},t.prototype.getNextComponent=function(){var t,e;return(e=this.holder)?(t=e.holder.children)?t[t.indexOf(this)-1]:void 0:null},t.prototype.setNextNode=function(t){this.nextNode=t},t.prototype.setHolder=function(t){return this.holder&&this.holder!==t&&this.holder.invalidateAttach(this),this.holder=t,this},t.prototype.isOffspringOf=function(t){var e;for(e=this.holder;e;){if(e===t)return!0;e=e.holder}return!1},t.prototype.inFamilyOf=function(t){return this===t||this.isOffspringOf(t)},t.prototype.setReactive=function(){var t,e,n,i,r,o;if(this.reactMap){e=this,t=function(){return e.invalidate()},o=this.reactMap;for(r in o)n=o[r],i=a.bind(this,r),"string"==typeof n?i.onInvalidate(function(){var t;return(t=e[n])?t.invalidate():void 0}):i.onInvalidate(t)}return this},t.prototype.copyEventListeners=function(t){var e,n,i;n=this.listeners,i=t.listeners;for(e in i)i[e]&&(n[e]=i[e].splice());return this},t}(),o=n(8),s(i.prototype,o)},function(t,e,n){var i,r,o,s,a;o=n(7),i=n(19),r=n(21),s=n(6).react,t.exports=a=function(t){var e,h,c,l;return o(t)?t:"function"==typeof t?new r(t):t instanceof Array?new(h=n(26))(function(){var e,n,i;for(i=[],e=0,n=t.length;n>e;e++)l=t[e],i.push(a(l));return i}()):null==t?new i:t.then&&t["catch"]?(e=n(29),c=new e(s(function(){return c.promiseResult})),t.then(function(t){return c.promiseResult=t,c.invalideTransform()})["catch"](function(t){return c.promiseResult=t,c.invalideTransform()}),c):new r(t)}},function(t,e,n){var i,r,o,s={}.hasOwnProperty,a=function(t,e){function n(){this.constructor=t}for(var i in e)s.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};i=n(20),o=n(1).newLine,t.exports=r=function(t){function e(){e.__super__.constructor.apply(this,arguments),this.firstNode=null,this.family={},this.baseComponent=this}return a(e,t),e.prototype.invalidate=function(){return this},e.prototype.renderDom=function(t){return t&&t.markRemovingDom(),this.valid=!0,this.node=[],this},e.prototype.createDom=function(){return this.node=[]},e.prototype.attachParent=function(){return this.node},e.prototype.attachChildren=function(){return this.node},e.prototype.markRemovingDom=function(){return this},e.prototype.removeDom=function(){return this},e.prototype.removeNode=function(){},e.prototype.clone=function(){return new e},e.prototype.toString=function(t,e){return null==t&&(t=2),o("<Nothing/>",t,e)},e}(i)},function(t,e,n){var i,r,o={}.hasOwnProperty,s=function(t,e){function n(){this.constructor=t}for(var i in e)o.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};r=n(17),t.exports=i=function(t){function e(){e.__super__.constructor.call(this),this.isBaseComponent=!0,this.removing=!1,this.baseComponent=this}return s(e,t),e.prototype.refreshDom=function(t){return this.renderDom(),this.attachParent(),this},e.prototype.renderDom=function(t){return this.emit("willRenderDom"),t&&t!==this&&t.markRemovingDom(),this.renderBaseComponent(t),this.emit("didRenderDom"),this},e.prototype.renderBaseComponent=function(t){t&&t!==this&&(this.attachValid=!1,this.holder&&this.holder.invalidateAttach(this)),this.node?(!this.valid||this.isTag)&&this.updateDom():(this.createDom(),this.holder&&this.holder.invalidateAttach(this))},e.prototype.invalidate=function(){return this.valid?(this.valid=!1,this.holder&&this.holder.invalidateContent(this)):this},e.prototype.attachChildren=function(){},e.prototype.markRemovingDom=function(){return this.removing=!0,this.holder=null,dc.removingChildren[this.dcid]=this,this},e.prototype.markRemoving=function(){this.removing=!0},e.prototype.clearRemoving=function(){return this.removing=this.removed=!1},e.prototype.removeDom=function(){var t,e,n,i;if(this.removing){if(this.removing=!1,this.removed=!0,this.emit("willDetach"),this.isList)for(this.node.parentNode=null,this.childParentNode=null,i=this.children,e=0,n=i.length;n>e;e++)t=i[e],t.removeDom();else this.removeNode();this.emit("didDetach")}return this},e.prototype.removeNode=function(){var t;this.removing=!1,this.removed=!0,(t=this.node)&&t.parentNode&&t.parentNode.removeChild(t)},e.prototype.executeAttachParent=function(){var t,e,n;e=this.node,n=this.parentNode,t=this.nextNode,this.removing=!1,!n||n===e.parentNode&&t===e.nextSibling||(this.emit("willAttach"),n.insertBefore(e,t),this.emit("didAttach"))},e.prototype.attachParent=function(){return this.executeAttachParent(),this.node},e}(r)},function(t,e,n){var i,r,o,s,a,e,h,c,l,u,d,f,p,m={}.hasOwnProperty,v=function(t,e){function n(){this.constructor=t}for(var i in e)m.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};i=n(20),f=n(1),h=f.funcString,l=f.newLine,d=f.value,a=f.dynamic,p=n(5),o=p.domField,s=p.domValue,u=n(22).setText,c="textContent"in document.documentElement?!0:!1,e=t.exports=r=function(t){function e(t){var n,i,r;e.__super__.constructor.call(this),this.setText(t),Object.defineProperty&&(i=this,n=function(){return i._text},r=function(t){return i.setText(t),t},Object.defineProperty(this,"text",{get:n,set:r})),this.family={},this.family[this.dcid]=!0}return v(e,t),e.prototype.isText=!0,e.prototype.setText=u,e.prototype.createDom=function(){var t,e;return this.valid=!0,e=s(this.text,this),t=document.createTextNode(e),t.component=this,this.node=t,this.firstNode=t,t},e.prototype.updateDom=function(){var t,e;return t=this.node,this.valid=!0,e=s(this.text,this),c?e!==t.textContent&&(t.textContent=e):e!==t.innerText&&(t.innerText=e),t},e.prototype.clone=function(){var t;return t=new this.constructor(this.text),t.copyEventListeners(this)},e.prototype.toString=function(t,e){return null==t&&(t=2),l(h(this.text),t,e)},e}(i)},function(t,e,n){var i,r,o,s,a,h,c,l;s=n(3),h=n(7).isComponent,a=n(24).extendEventValue,r=n(23),l=n(25).styleFrom,o=n(5).domField,e.extendAttrs=function(t,e,n){var i,o,h,c;if(null==n&&(n={}),!e)return t;if(!t)return e;o=r([e["class"],e.className]),n.replaceClass?t.className=o:(t.className=r([t["class"],t.className]),delete t["class"],t.className=r([t.className,o])),h=l(t.style),e.style?t.style=s(h,e.style):t.style=h;for(i in e)if(c=e[i],"class"!==i&&"className"!==i)if("on"===i.slice(0,2))n["replace_"+i]||n.replaceEvents?t[i]=c:a(t,i,c);else{if("style"===i)continue;t[i]=c}return t},e.overAttrs=c=function(t,e){var n,i;if(e){if(t){for(n in t)i=t[n],null==e[n]&&(e[n]=i),"style"===n&&(e[n]=c(t[n],e[n]));return e}return e}return t=s({},t),t.style&&(t.style=s({},l(t.style))),t},i={"for":"htmlFor"},e.attrToPropName=function(t){var e,n,r,o;if(r=i[t])return r;if(o=t.split("-"),1===o.length)return t;for(e=1,n=o.length;n>e;)o[e]=o[e][0].toUpperCase()+o[e].slice(1),e++;return o.join("")},e.setText=function(t){var e;return t=o(t,this),this._text===t?this:(this._text=t,e=this,"function"==typeof t&&t.onInvalidate(function(){return e.invalidate()}),this.invalidate(),this)}},function(t,e,n){var i,r,e,o,s,a=[].slice;s=n(6).react,r=n(5).domField,o=n(1).isArray,t.exports=e=i=function(){var t,e,n,h,c;return n=1<=arguments.length?a.call(arguments,0):[],t={},h=function(){var n,i,r;if(!arguments.length){i=[],h.valid=!0;for(n in t)r=t[n],"function"==typeof r&&(r=r.call(this)),r&&i.push(n);return i.join(" ")}e([].slice(arguments))},c=function(e,n){var i;return n=r(n),i=t[e],"function"==typeof i&&i.offInvalidate(h.invalidate),!n&&i?(h.invalidate(),delete t[e]):i!==n?(h.invalidate(),"function"==typeof n&&n.onInvalidate(h.invalidate),t[e]=n):void 0},e=function(t){var n,i,r,s,a,h,l,u,d;if(t)for(o(t)||(t=[t]),a=0,l=t.length;l>a;a++)if(n=t[a])if("string"==typeof n)for(r=n.trim().split(/\s+(?:,\s+)?/),h=0,u=r.length;u>h;h++)i=r[h],"!"===i[0]?c(i.slice(1),!1):c(i,!0);else if(n instanceof Array)e(n);else if(n&&n.classMap){d=n.classMap;for(i in d)s=d[i],"function"!=typeof s&&(s=!0),c(i,s)}else if("object"==typeof n)for(i in n)s=n[i],"function"!=typeof s&&(s=!0),c(i,s)},s(h),e(n),h.classMap=t,h.valid=!Object.keys(t).length,h.removeClass=function(){var t,e,n,i,r;for(e=1<=arguments.length?a.call(arguments,0):[],r=[],n=0,i=e.length;i>n;n++)t=e[n],r.push(c(t,!1));return r},h.extend=function(){var t;return t=1<=arguments.length?a.call(arguments,0):[],e(t)},h.clone=function(){var t;return t=i(),t.extend(h)},h},e.classFn=i},function(t,e){var n,i,r,o,s,a;for(e.domEventHandler=function(t){var e,n,i,r,o,s,a,h,c,l;if(n=this.component){for(o="on"+t.type,r=n.domEventCallbackMap[o],c=0,l=r.length;l>c;c++)s=r[c],a=s.call(n,t,this);if(i=n.eventUpdateConfig[o]){for(h in i)e=i[h],e.render();dc.clean()}t&&(!t.executeDefault&&t.preventDefault&&t.preventDefault(),!t.continuePropagation&&t.stopPropagation&&t.stopPropagation())}return t&&null!=t.dcEventResult?t.dcEventResult:a},e.addEventListenerMap=n={},a="compositionstart compositionupdate compositionend".split(/\s/),o=0,s=a.length;s>o;o++)i=a[o],n["on"+i]=!0;e.domEventHandlerFromArray=function(t){return function(e){var n,i,r;for(i=0,r=t.length;r>i;i++)n=t[i],n&&n.call(this.component,e,this)}},e.extendEventValue=r=function(t,e,n,i){var r;return r=t[e],r?r instanceof Array||(r=[r]):r=[],n?n instanceof Array||(n=[n]):n=[],i?t[e]=n.concat(r):t[e]=r.concat(n)},e.addHandlerToCallbackArray=function(t,e,n){var i,r,o,s;if("function"==typeof t&&(t=[t]),n)for(i=t.pop();i;)i||dc.error("addHandlerToCallbackArray: callback is undefined"),r=e.indexOf(i),0>=r&&e.unshift(i),i=t.pop();else for(o=0,s=t.length;s>o;o++)i=t[o],i||dc.error("addHandlerToCallbackArray: callback is undefined"),r=e.indexOf(i),0>=r&&e.push(i)}},function(t,e,n){var i,r;i=n(1).cloneObject,e.styleFrom=r=function(t){var e,n,r,o,s,a,h,c,l,u;if("string"==typeof t){for(r={},t=t.trim().split(/\s*;\s*/),s=0,h=t.length;h>s;s++)e=t[s],e=e.trim(),e&&(l=e.split(/\s*:\s*/),n=l[0],o=l[1],r[n]=o);return r}if(t instanceof Array){for(r={},a=0,c=t.length;c>a;a++){if(e=t[a],"string"==typeof e){if(e=e.trim(),!e)continue;u=e.split(/\s*:\s*/),n=u[0],t=u[1]}else n=e[0],t=e[1];r[n]=t}return r}return t&&"object"!=typeof t?{}:i(t)}},function(t,e,n){var i,r,o,s,a,e,h,c,l,u={}.hasOwnProperty,d=function(t,e){function n(){this.constructor=t}for(var i in e)u.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};i=n(20),c=n(1).newLine,l=n(27),h=n(1).mixin,o=n(28),a=n(1).binaryInsert,t.exports=e=r=function(t){function e(t){e.__super__.constructor.call(this),this.children=l(t),this.initListMixin(),this.isList=!0}return d(e,t),e.prototype.refreshDom=function(t){return this.renderDom(),this.attachChildren(),this},e.prototype.createDom=function(){return this.valid=!0,this.node=this.childNodes,this.createChildrenDom(),this.firstNode=this.childrenFirstNode,this.node},e.prototype.updateDom=function(){return this.valid=!0,this.updateChildrenDom(),this.firstNode=this.childrenFirstNode,this.node},e.prototype.markRemovingDom=function(){var t,e,n,i;for(this.removing=!0,this.holder=null,i=this.children,e=0,n=i.length;n>e;e++)t=i[e],t.markRemoving();return dc.removingChildren[this.dcid]=this,this},e.prototype.markRemoving=function(){var t,e,n,i;for(this.removing=!0,i=this.children,e=0,n=i.length;n>e;e++)t=i[e],t.markRemoving()},e.prototype.clearRemoving=function(){var t,e,n,i;for(this.removing=this.removed=!1,i=this.children,e=0,n=i.length;n>e;e++)t=i[e],t.clearRemoving()},e.prototype.removeNode=function(){var t,e,n,i;for(this.removing=!1,this.removed=!0,this.node.parentNode=null,this.childParentNode=null,i=this.children,e=0,n=i.length;n>e;e++)t=i[e],t.baseComponent.removeNode()},e.prototype.invalidateAttach=function(t){var e;return e=this.children.indexOf(t),a(e,this.attachParentIndexes),this.attachValid&&(this.attachValid=!1,this.holder&&this.holder.invalidateAttach(this)),this},e.prototype.attachParent=function(){var t,e,n;return e=this.node,n=this.parentNode,t=this.nextNode,this.removing=!1,!n||n===e.parentNode&&t===e.nextSibling?void 0:(this.emit("willAttach"),s.call(this),this.emit("didAttach"))},e.prototype.setNextNode=function(t){var e,n,i;for(this.nextNode=t,this.childrenNextNode=t,n=this.children,i=n.length-1;(e=n[i])&&(e.setNextNode(t),!e.firstNode);)i--},e.prototype.clone=function(t){var n;return n=new e(this.cloneChildren(t)),n.constructor=this.constructor,n.copyEventListeners(this)},e.prototype.toString=function(t,e){var n,i,r,o,s;if(null==t&&(t=0),this.children.length){for(i=c("<List>",t,e),s=this.children,r=0,o=s.length;o>r;r++)n=s[r],i+=n.toString(t+2,!0);return i+=c("</List>",t,!0)}return c("<List/>",t,e)},e}(i),h(r.prototype,o),s=o.attachChildren},function(t,e,n){var i,r;i=n(18),t.exports=r=function(t){var e,n,r,o;if(t){if(t instanceof Array){for(o=[],n=0,r=t.length;r>n;n++)e=t[n],o.push(i(e));return o}return[i(t)]}return[]}},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g=[].slice;m=n(1),c=m.isArray,f=m.substractSet,l=n(7),p=n(18),i=n(19),v=n(1),s=v.binarySearch,o=v.binaryInsert,f=v.substractSet,a=n(5).extendChildFamily,h=function(t,e){var n;n=s(t,e),e.splice(n,0,t),r(e,1,n+1)},u=function(t,e){var n;n=s(t,e),e[n]===t&&e.splice(n,1),r(e,-1,n)},r=function(t,e,n){var i,r;for(r=t.length,i=n;r>i;){if(t[i]+=e,t[i]<0)throw"negative index in ListMixin component";i++}},d=function(t,e,n,i){var r,o;for(o=n;o>=i&&(r=t[o],r.nextNode!==e)&&(r.nextNode=e,!r.firstNode);)o--,e=r.firstNode},t.exports={initListMixin:function(){var t,e,n,i,r,o;for(this.updatingChildren=[],this.attachingChildren={},this.attachParentIndexes=[],this.childNodes=[],this.family=e={},e[this.dcid]=!0,this.children=this.children||[],o=this.children,n=i=0,r=o.length;r>i;n=++i)t=o[n],t.setHolder(this),t.clearRemoving(),a(e,t)},cloneChildrenFrom:function(t,e){var n,i,r,o,s,a;for(i=[],a=t.children,r=o=0,s=a.length;s>o;r=++o)n=a[r],i.push(this.cloneChild(n,r,e,t));return this.setChildren(0,i)},cloneChild:function(t,e,n,i){return t.clone(n)},createChildrenDom:function(){var t,e,n,i,r,o,s,a;for(r=this.childNodes,e=null,this.updatingChildren=[],a=this.children,i=o=0,s=a.length;s>o;i=++o)t=a[i],t.setHolder(this),t.renderDom(t.baseComponent),r.push(t.node),!e&&t.firstNode&&(e=t.firstNode,n=i);this.childrenFirstNode=e,this.firstNodeIndex=n},updateChildrenDom:function(){var t,e,n,i,r,o,s;for(r=this.updatingChildren,this.updatingChildren=[],i=this.childNodes,e=this.children,o=0,s=r.length;s>o;o++)n=r[o],t=e[n],t.setHolder(this),t.renderDom(t.baseComponent),n=e.indexOf(t),i[n]=t.node,this.updateChildrenFirstNode(t,n)},insertChildBefore:function(t,e){return this.insertChild(e,t)},insertChildAfter:function(t,e){var n;return n=this.children,l(e)&&(e=n.indexOf(e),0>e&&(e=0)),this.insertChild(e+1,t)},pushChild:function(){var t,e,n,i;for(t=1<=arguments.length?g.call(arguments,0):[],i=this.children,n=t.length,e=0;n>e;)this.insertChild(i.length,t[e]),e++;return this},insertChild:function(t,e){var n,i,r;return n=this.children,r=n.length,null==t?i=r:l(t)?(i=n.indexOf(t),0>i&&(i=r)):t>r?(i=r,t=null):0>t?(i=0,t=null):(i=t,t=n[i]),this.emit("onInsertChild",i,t,e),e=p(e),this._insertChild(i,e)},_insertChild:function(t,e){var n;return n=this.children,n.splice(t,0,e),e.setHolder(this),e.clearRemoving(),e.parentNode=this.childParentNode,t===n.length-1?e.setNextNode(this.childrenNextNode):e.setNextNode(n[t+1].firstNode||n[t+1].nextNode),this.node&&(this.childNodes.splice(t,0,e.node),e.node&&e.valid||(this.valid=!1,h(t,this.updatingChildren),this.holder&&this.holder.invalidateContent(this)),this.holder&&this.holder.invalidateAttach(this),this.attachValid=!1,h(t,this.attachParentIndexes),e.firstNode&&(!this.childrenFirstNode||t<=this.firstNodeIndex)&&(this.childrenFirstNode=e.firstNode,this.firstNodeIndex=t)),this},unshiftChild:function(){var t,e;for(t=1<=arguments.length?g.call(arguments,0):[],e=t.length-1;e>=0;)this.insertChild(0,t[e]),e--;return this},shiftChild:function(){return this.removeChild(0)},popChild:function(){var t;return t=this.children.length,t?this.removeChild(t-1):this},removeChild:function(t){var e,n,i;return null==t&&dc.error("child to be removed is undefined"),n=this.children,l(t)?(i=n.indexOf(t),0>i&&dc.error("child to be removed is not in the children")):t>=n.length||0>t?dc.error("child("+t+") to be removed is out of range"):(i=t,t=n[i]),u(i,this.updatingChildren),t=n[i],this.node&&(this.childNodes.splice(i,1),(e=t.firstNode)&&(this.firstNodeIndex===i&&this.setFollowingChildrenFirstNode(i),this.childParentNode&&e.parentNode===this.childParentNode&&(this.propagateChildNextNode(i,t.nextNode),t.removeNode())),u(i,this.attachParentIndexes)),f(this.family,t.family),n.splice(i,1),t.holder===this&&(t.holder=null),this},setFollowingChildrenFirstNode:function(t){var e,n,i;for(e=this.children,i=e.length,t++;i>t;){if(n=e[t].firstNode)return this.childrenFirstNode=n,void(this.firstNodeIndex=t);t++}this.childrenFirstNode=null},replaceChild:function(t,e){var n,i;return n=this.children,l(t)?(i=n.indexOf(t),0>i&&dc.error("oldChild to be replaced is not in the children")):((t>=n.length||0>t)&&dc.error("oldChild("+t+") to be replaced is out of range"),i=t,t=n[i]),this.emit("onReplaceChild",i,t,e),e=p(e),this._replaceChild(i,t,e)},_replaceChild:function(t,e,n){var i;return i=this.children,e===n?this:(i[t]=n,e.holder===this&&(e.holder=null),e.markRemovingDom(),n.setHolder(this),n.clearRemoving(),n.parentNode=e.parentNode,n.nextNode=e.nextNode,f(this.family,e.family),a(this.family,n),this.node&&(this.childNodes[t]=n.node,n.node&&n.valid||this.invalidateContent(n),this.invalidateAttach(n),dc.removingChildren[e.dcid]=e,this.updateChildrenFirstNode(n,t)),this)},updateChildrenFirstNode:function(t,e){this.childrenFirstNode?t.firstNode?e<=this.firstNodeIndex&&(this.childrenFirstNode=t.firstNode,this.firstNodeIndex=e):e===this.firstNodeIndex&&this.setFollowingChildrenFirstNode(e):t.firstNode&&(this.childrenFirstNode=t.firstNode,this.firstNodeIndex=e)},setChildren:function(t,e){var n,r,o,s,a,h,c;for(r=this.children,a=r.length,s=a;t>s;)this.pushChild(new i),s++;for(o=h=0,c=e.length;c>h;o=++h)n=e[o],a>t+o?this.replaceChild(t+o,e[o]):this.pushChild(e[o]);return this},setLength:function(t){var e,n;if(e=this.children,t>=e.length)return this;for(n=e.length-1;n>=t;)this.removeChild(n),n--;return this},invalidateContent:function(t){var e;return e=this.children.indexOf(t),o(e,this.updatingChildren),this.valid&&(this.valid=!1,this.holder&&this.holder.invalidateContent(this)),this},invalidateChildren:function(){var t,e,n,i;for(this.invalidate(),i=this.children,e=0,n=i.length;n>e;e++)t=i[e],t.valid=!1;return this},attachChildren:function(){var t;t=this.childParentNode,t&&this.attachValid&&this.childNodes.parentNode||(this.attachValid=!0,this.isList?(this.childParentNode=this.parentNode,this.childrenNextNode=this.nextNode):t||(this.childParentNode=this.node,this.childrenNextNode=null),this.childParentNode!==this.childNodes.parentNode?this.attachEachChildren():this.attachInvalidChildren())},attachEachChildren:function(){var t,e,n,i,r,o;if(o=this.childParentNode,e=this.children,i=e.length){for(r=this.childrenNextNode,n=i-1;t=e[n];)t.setHolder(this),t.parentNode=o,t.setNextNode(r),t.attachParent(),r=t.firstNode||r,n--;t=e[0],this.childNodes.parentNode=o}},attachInvalidChildren:function(){var t,e,n,i,r,o,s,a;if(t=this.attachParentIndexes,t.length&&(this.attachParentIndexes=[],s=this.childParentNode)){for(o=this.childrenNextNode,n=this.children,i=t.length-1,a=n.length-1;i>=0;)r=t[i],d(n,o,a,r),e=n[r],e.setHolder(this),e.parentNode=s,e.attachParent(),o=e.firstNode||e.nextNode,a=r-1,i--;d(n,o,a,0),this.childNodes.parentNode=s}},propagateChildNextNode:function(t,e){var n,i;for(n=this.children,i=l(t)?n.indexOf(t)-1:t-1;t=n[i];){if(t.setNextNode(e),t.firstNode)return;i--}!this.isTag&&this.holder&&this.holder.propagateChildNextNode(this,e)}}},function(t,e,n){var i,r,o,s,a,h,c,l={}.hasOwnProperty,u=function(t,e){function n(){this.constructor=t}for(var i in e)l.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};h=n(18),r=n(16),c=n(1),o=c.funcString,s=c.newLine,a=n(6).renew,t.exports=i=function(t){function e(t){var n;e.__super__.constructor.call(this),t.invalidate?this.func=t:this.func=a(t),n=this,this.func.onInvalidate(function(){return n.invalidateTransform()})}return u(e,t),e.prototype.getContentComponent=function(){return h(this.func())},e.prototype.clone=function(){return new e(this.func).copyEventListeners(this)},e.prototype.toString=function(t,e){return null==t&&(t=2),s("<Func "+o(this.func)+"/>",t,e)},e}(r)},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g,y,w,C,N,x,_,b,P,A,S,E,L,D,I,O,k={}.hasOwnProperty,T=function(t,e){function n(){this.constructor=t}for(var i in e)k.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t},F=[].slice;w=n(3),P=(p=n(2)).refreshComponents,E=n(5),g=E.domField,y=E.domValue,m=n(2).directiveRegistry,u=n(23),A=n(25).styleFrom,h=n(22).attrToPropName,L=n(24),v=L.domEventHandler,s=L.addEventListenerMap,a=L.addHandlerToCallbackArray,i=n(20),D=n(1),N=D.funcString,_=D.newLine,d=D.cloneObject,I=n(6),C=I.flow,b=I.react,S=n(27),c=n(1).binaryInsert,O=n(31),f=O.createElement,l=O.cacheElement,t.exports=o=function(t){function e(t,n,i){if(null==n&&(n={}),!(this instanceof e))throw"should use new SubclassComponent(...) with the subclass of Tag";e.__super__.constructor.call(this),this.isTag=!0,t=t||"div",this.tagName=t.toLowerCase(),this.namespace=n.namespace,this.poolLabel=this.generatePoolLabel(),this.children=S(i),this.initListMixin(),this.initProperties(),this.extendAttrs(n)}return T(e,t),e.prototype.FakeTag=function(){return e},e.prototype.initProperties=function(){var t,e;this.hasActiveProperties=!1,this.cacheClassName="",this.className=t=u(),e=this,this.className.onInvalidate(function(){return t.valid?(e.hasActiveProperties=!0,e.invalidate()):void 0}),this.hasActiveProps=!1,this.cacheProps={},this.props={},this.boundProps={},this.invalidateProps={},this.hasActiveNodeAttrs=!1,this.cacheNodeAttrs={},this.nodeAttrs={},this.boundNodeAttrs={},this.invalidateNodeAttrs={},this.hasActiveStyle=!1,this.cacheStyle={},this.style={},this.boundStyle={},this.invalidateStyle={},this.hasActiveDomEvents=this.hasActiveDomEvents||!1,this.domEventCallbackMap||(this.domEventCallbackMap={}),this.eventUpdateConfig={}},e.prototype.extendAttrs=function(t){var e,n,i,r,o,s,a,h,c,l,u,d,f,p,v,g;e=this.className,a=this.style,s=this.props,o=this.nodeAttrs;for(r in t)if(u=t[r],"style"===r){h=A(u);for(r in h)u=h[r],this.setProp(r,u,a,"Style")}else if("class"===r||"className"===r)this.hasActiveProperties=!0,e.extend(u);else if("on"===r.slice(0,2)){if(!u)continue;if("function"==typeof u)this.bindOne(r,u);else if(l=u[0],"before"===l||"after"===l)for(g=u.slice(1),d=0,p=g.length;p>d;d++)c=g[d],this.bindOne(r,c,"before"===l);else for(f=0,v=u.length;v>f;f++)c=u[f],this.bindOne(r,c)}else if("$"===r[0])n=m[r],(i=u instanceof Array?n.apply(null,u):n.apply(null,[u]))(this);else if("attr_"===r.slice(0,5))this.setProp(r.slice(5),u,o,"NodeAttrs");else{if("xxx"===r.slice(0,3))continue;this.setProp(r,u,s,"Props")}return this},e.prototype.prop=function(){var t;return t=1<=arguments.length?F.call(arguments,0):[],this._prop(t,this.props,"Props")},e.prototype.css=function(){var t;return t=1<=arguments.length?F.call(arguments,0):[],this._prop(t,this.style,"Style")},e.prototype.attr=function(){var t;return t=1<=arguments.length?F.call(arguments,0):[],this._prop(t,this.nodeAttrs,"NodeAttrs")},e.prototype._prop=function(t,e,n){var i,r,o;if(0===t.length)return e;if(1===t.length){if(r=t[0],"string"==typeof r)return e.hasOwnProperty(r)?y(e[r],this):this["cache"+n][r];for(i in r)o=r[i],this.setProp(i,o,e,n)}else 2===t.length&&("NodeAttrs"===n?this.setProp(t[0],t[1],e,n):this.setProp(t[0],t[1],e,n));return this},e.prototype.setProp=function(t,e,n,i){var r,o,s,a;return t=h(t),e=g(e,this),a=n[t],e===a?this:(null==a?"function"==typeof e?(s=this,this["invalidate"+i][t]=o=function(){var r;return s.addActivity(n,t,i,!0),(r=s["bound"+i][t])&&r.invalidate(),n[t]=e},e.onInvalidate(o),this.addActivity(n,t,i),n[t]=e):e!==this["cache"+i][t]&&(this.addActivity(n,t,i),(r=this["bound"+i][t])&&r.invalidate(),n[t]=e):("function"==typeof a&&a.offInvalidate(this["invalidate"+i][t]),"function"==typeof e&&(s=this,this["invalidate"+i][t]=o=function(){return s.addActivity(n,t,i,!0),(r=s["bound"+i][t])&&r.invalidate(),n[t]=e},e.onInvalidate(o)),(r=this["bound"+i][t])&&r.invalidate(),n[t]=e),this)},e.prototype.propBind=function(t){return this._propBind(t,this.props,"Props")},e.prototype.cssBind=function(t){return this._propBind(t,this.style,"Style")},e.prototype.attrBind=function(t){return this._propBind(t,this.nodeAttrs,"NodeAttrs")},e.prototype._propBind=function(t,e,n){var i,r;return r=this["bound"+n],(i=r[t])?i:r[t]=b(function(){return this._prop([t],e,n)})},e.prototype.addActivity=function(t,e,n){return this["hasActive"+n]=!0,this.hasActiveProperties=!0,this.node?this.invalidate():void 0},e.prototype.bind=function(t,e,n){var i,r,o,s,a;if(this.domEventCallbackMap||(this.domEventCallbackMap={}),1===arguments.length)for(i in t)e=t[i],this.bind(i,e);else for(a=t.split(/\s*:\s*/),t=a[0],r=a[1],t=t.split(/\s+/),o=0,s=t.length;s>o;o++)i=t[o],this.bindOne(i,e,n||r);return this},e.prototype.bindOne=function(t,e,n){var i,r;return e||p.error("Tag.bind: handler is undefined for event: "+t),"on"!==t.slice(0,2)&&(t="on"+t),i=this.domEventCallbackMap||(this.domEventCallbackMap={}),r=i[t]||(i[t]=[]),this.node?s[t]?node.addEventListener(t.slice(2),v):this.node[t]=v:(this.hasActiveDomEvents=!0,this.hasActiveProperties=!0),a(e,r,n),this},e.prototype.unbind=function(t,e){var n,i,r,o,s,a,h;for(t=t.split("s+"),n=this.domEventCallbackMap,a=0,h=t.length;h>a;a++)r=t[a],"on"!==r.slice(0,2)&&(r="on"+r),i=n[r],i&&(o=i.indexOf(e),o>=0&&(i.splice(o,1),i.length||(n[r]=null,(s=this.node)&&(s[prop]=null,s.removeEventListener(v)))));return this},e.prototype.addClass=function(){var t;return t=1<=arguments.length?F.call(arguments,0):[],this.className.extend(t),this.node&&!this.className.valid&&(this.hasActiveProperties=!0,this.invalidate()),this},e.prototype.removeClass=function(){var t,e;return t=1<=arguments.length?F.call(arguments,0):[],(e=this.className).removeClass.apply(e,t),this.node&&!this.className.valid&&(this.hasActiveProperties=!0,this.invalidate()),this},e.prototype.show=function(t){return"function"==typeof t&&(t=t(),null==t&&(t="")),null==t?this.setProp("display","block",this.style,"Style"):"visible"===t?this.setProp("visibility","visible",this.style,"Style"):this.setProp("display",t,this.style,"Style"),this},e.prototype.hide=function(t){return"function"==typeof t&&(t=t(),null==t&&(t="")),t?"hidden"===t?this.setProp("visibility","hidden",this.style,"Style"):this.setProp("display",t,this.style,"Style"):this.setProp("display","none",this.style,"Style"),this},e.prototype.showHide=function(t,e,n){var i,r,o,s,a;return a=this.style,e=g(e,this),s=a.display,s?"function"==typeof s&&s.offInvalidate&&s.offInvalidate(this.invalidateStyle.display):this.addActivity(a,"display","Style",this.node), a.display=o=C(e,s,function(){var i;return("function"==typeof e?!!e():!!e)===t?n?"function"==typeof n?n():n:null!=s?(i="function"==typeof s?s():s,"none"!==i?i:"block"):s="block":"none"}),r=this,this.invalidateStyle.display=i=function(){return r.addActivity(a,"display","Style",!0),a.display=o},o.onInvalidate(i),this.style=a,this},e.prototype.showOn=function(t,e){return this.showHide(!0,t,e)},e.prototype.hideOn=function(t,e){return this.showHide(!1,t,e)},e.prototype.refreshDom=function(t){this.renderDom(t),this.attachParent()},e.prototype.createDom=function(){var t;return this.valid=!0,this.node=this.firstNode=t=f(this.namespace,this.tagName,this.poolLabel),t.component=this,this.updateProperties(),this.createChildrenDom(),this.attachChildren(),this.valid=!this.hasActiveProperties&&!this.updatingChildren.length,t},e.prototype.updateDom=function(){return this.valid=!0,this.updateProperties(),this.updateChildrenDom(),this.attachChildren(),this.valid=!this.hasActiveProperties&&!this.updatingChildren.length,this.node},e.prototype.invalidateAttach=function(t){var e;return e=this.children.indexOf(t),c(e,this.attachParentIndexes),this.holder&&(this.attachValid&&this.valid&&this.holder.invalidateContent(this),this.valid=!1,this.attachValid=!1),this},e.prototype.updateProperties=function(){var t,e,n,i,r,o,a,h,c,l,u,d,f,p,m;if(this.hasActiveProperties){if(this.hasActiveProperties=!1,c=this.node,r=this.className,r.valid||(o=r.call(this),o!==this.cacheClassName&&(this.cacheClassName=c.className=o)),this.hasActiveNodeAttrs){l=this.nodeAttrs,t=this.cacheNodeAttrs,this.hasActiveNodeAttrs=!1;for(u in l)p=l[u],delete l[u],p=y(p,this),t[u]=c[u]=p,c.setAttribute(u,p)}if(this.hasActiveProps){d=this.props,e=this.cacheProps,this.hasActiveProps=!1;for(u in d)p=d[u],delete d[u],p=y(p,this),e[u]=c[u]=p}if(this.hasActiveStyle){f=this.style,n=this.cacheStyle,this.hasActiveStyle=!1,a=c.style;for(u in f)p=f[u],delete f[u],p=y(p,this),n[u]=a[u]=p}if(this.hasActiveDomEvents){m=this.domEventCallbackMap;for(h in m)i=m[h],i&&i.length&&(s[h]?c.addEventListener(h.slice(2),v):c[h]=v)}this.hasActiveDomEvents=!1}},e.prototype.setPoolLabel=function(t){return this.poolLabel=t,this},e.prototype.generatePoolLabel=function(){return""},e.prototype.destroy=function(){var t;return this.poolLabel&&(t=this.node)&&l(t,this.poolLabel),e.__super__.destroy.call(this),this.poolLabel&&t&&(t.innerHTML=""),this},e.prototype.clone=function(t){var e,n,i,r,o,s;n={className:this.className.clone(),style:w({},this.cacheStyle,this.style)},w(n,this.cacheProps,this.props,this.cacheNodeAttrs,this.nodeAttrs),s=this.domEventCallbackMap;for(r in s)i=s[r],n[r]=i.slice(0);return e=this.FakeTag(),o=new e(this.tagName,n,[]),o.__proto__=this.__proto__,o.constructor=this.constructor,o.cloneChildrenFrom(this,t),o.copyEventListeners(this),o.setupCloneComponent(this,t)},e.prototype.setupCloneComponent=function(t,e){return this.setReactive()},e.prototype.toString=function(t,e){var n,i,r,o,s,a,h,c,l,u,d;null==t&&(t=0),o=_("<"+this.tagName,t,e),l=this.props;for(r in l)a=l[r],o+=" "+r+"="+N(a);if(this.hasActiveStyle){o+=" style={",u=this.style;for(r in u)if(a=u[r],"string"==typeof a)o+=a;else for(r in a)s=a[r],o+=" "+r+"="+N(s);o+="}"}if(o+=">",i=this.children,i.length>1){for(d=this.children,h=0,c=d.length;c>h;h++)n=d[h],o+=n.toString(t+2,!0);return o+=_("</"+this.tagName+">",t+2,!0)}return 1===i.length&&(o+=i[0].toString(t+2)),o+=_("</"+this.tagName+">",t+2)},e}(i),x=n(1).mixin,r=n(28),x(o.prototype,r)},function(t,e){var n,i,r,o;n={},i=0,r=500,o={},e.createElement=function(t,e,r){var o,s,a;return null==t&&(t=""),null==e&&(e="div"),r&&(o=e+":"+r,a=n[o])?(s=a.pop(),i--,s):t?document.createElementNS(t||"",e):document.createElement(e)},e.cacheElement=function(t,e){var s,a,h;return r>i&&(s=t.tagName.toLowerCase()+":"+e,a=o[s]||10,h=n[s]||(n[s]=[]),h.length<a)?(h.push(t),i++):void 0}},function(t,e,n){var i,r,o,s,a,h,c,l={}.hasOwnProperty,u=function(t,e){function n(){this.constructor=t}for(var i in e)l.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};i=n(20),o=n(21),c=n(1),a=c.funcString,h=c.newLine,s=n(5).domValue,t.exports=r=function(t){function e(t){e.__super__.constructor.call(this,t)}return u(e,t),e.prototype.createDom=function(){var t,e;return this.valid=!0,e=s(this.text,this),t=document.createComment(e),this.node=this.firstNode=t,this.cacheText=e,this.node},e.prototype.updateDom=function(){var t,e,n;return this.valid=!0,n=s(this.text,this),n!==this.cacheText&&(e=t.parentNode,e&&e.removeChild(t),t=document.createComment(n),this.node=this.firstNode=t,this.cacheText=n),this.node},e.prototype.toString=function(t,e){return null==t&&(t=2),h("<Comment "+a(this.text)+"/>",t,e)},e}(o)},function(t,e,n){var i,r,o,s,a,h,c,l={}.hasOwnProperty,u=function(t,e){function n(){this.constructor=t}for(var i in e)l.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};i=n(20),o=n(21),c=n(1),a=c.funcString,h=c.newLine,s=n(5).domValue,t.exports=r=function(t){function e(t){e.__super__.constructor.call(this,t)}return u(e,t),e.prototype.createDom=function(){return this.node=document.createCDATASection(s(this.text,this)),this.node},e.prototype.updateDom=function(){return this.text&&(this.node.data=s(this.text,this)),this.node},e.prototype.toString=function(t,e){return null==t&&(t=2),h("<CDATA "+a(this.text)+"/>",t,e)},e}(o)},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g,y={}.hasOwnProperty,w=function(t,e){function n(){this.constructor=t}for(var i in e)y.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};s=n(30),v=n(1),l=v.funcString,f=v.newLine,d=v.mixin,g=n(5),h=g.domValue,a=g.domField,p=n(22).setText,t.exports=i=function(t){function e(t,n,i){var r;"string"==typeof t||"function"==typeof t?(i=n,n=t,t={}):t=t||{},t.tagName?(r=t.tagName,delete t.tagName):r="div",this.initHtmlComponent(n,i),e.__super__.constructor.call(this,r,t,[])}return w(e,t),e.prototype.toString=function(t,e){return null==t&&(t=2),f("<Html "+l(this._text)+"/>",t,e)},e}(s),i.HtmlMixin=r={setText:p,initHtmlComponent:function(t,e){var n,i,r;return this.transform=e,this.setText(t),Object.defineProperty?(i=this,n=function(){return i._text},r=function(t){return i.setText(t),t},Object.defineProperty(this,"text",{get:n,set:r})):void 0},initListMixin:function(){},attachChildren:function(){},createDom:function(){var t,e;return this.valid=!0,this.node=this.firstNode=t=document.createElement(this.tagName),t.component=this,this.updateProperties(),e=h(this._text,this),this.transform&&(e=this.transform(e)),this.cacheText=t.innerHTML=e,this},updateDom:function(){var t,e;return this.valid=!0,e=h(this._text,this),this.transform&&(e=this.transform(e)),t=this.node,e!==this.cacheText&&(t.childNodes.length>=2&&(t.parentNode&&this.removeNode(),this.node=this.firstNode=t=t.cloneNode(!1),t.component=this),t.innerHTML=e,this.cacheText=e),this.updateProperties(),this}},o=n(28),m=function(t){return i.prototype[t]=function(){return dc.error("Html component has no children components, do not call ListMixin method("+t+") on it")}};for(u in o)m(u);(c=n(3))(i.prototype,r)},function(t,e,n){var i,r,o,s,a,h,c,l,u={}.hasOwnProperty,d=function(t,e){function n(){this.constructor=t}for(var i in e)u.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};o=n(16),l=n(1),s=l.funcString,h=l.newLine,a=l.intersect,c=n(6).renew,i=Object.defineProperty,t.exports=r=function(t){function e(t){var n,r,o;e.__super__.constructor.apply(this,arguments),this.__cacheTest=null,r=this,this.invalidateHandler=function(){return r.invalidateTransform()},i&&(n=function(){return r._test},o=function(t){return r.setTest(t),t},i(this,"test",{get:n,set:o})),this.setTest(t)}return d(e,t),e.prototype.getTestValue=function(){var t;return t=this.test,"function"==typeof t?this.__cacheTest=t.call(this):this.__cacheTest=t},e.prototype.setTest=function(t){var e,n;if(e=this.test,t===e)return t;if("function"==typeof e){if(t===this.__originalTest)return t;this.__originalTest.offInvalidate(this.invalidateHandler)}return n=i?"_test":"test","function"==typeof t&&(this.__originalTest=t,t.invalidate||(t=c(t)),t.onInvalidate(this.invalidateHandler)),this.__cacheTest!==t&&this.invalidateTransform(),this[n]=t},e}(o)},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f={}.hasOwnProperty,p=function(t,e){function n(){this.constructor=t}for(var i in e)f.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};u=n(18),o=n(35),d=n(1),s=d.funcString,c=d.newLine,a=d.intersect,l=n(6).renew,h=n(37),r=Object.defineProperty,t.exports=i=function(t){function e(t,n,i,r,o,s){var c;if(null==s&&(s=!1),n===i)return u(n);if(n=u(n),i=u(i),!s){if("function"!=typeof t)return t?n:i;if(r)return h(t,n,i,o)}return e.__super__.constructor.call(this,t),this.then_=n,this.else_=i,this.family=c=a([n.family,i.family]),c[this.dcid]=!0,this}return p(e,t),e.prototype.getContentComponent=function(){return this.getTestValue()?this.then_:this.else_},e.prototype.clone=function(){return new e(this.test,this.then_.clone(),this.else_.clone()).copyEventListeners(this)},e.prototype.toString=function(t,e){return null==t&&(t=0),null==e&&(e=""),c("",t,e)+"<if "+s(this.test)+">"+this.then_.toString(t+2,!0)+this.else_.toString(t+2,!0)+c("</if>",t,!0)},e}(o)},function(t,e,n){var i,r,o,s,a,e,h,c,l,u,d,f,p,m,v;h=n(3),o=n(30),i=n(26),r=n(19),s=n(24).domEventHandlerFromArray,c=n(9),l=c.if_,e=t.exports=u=function(t,e,s,a){var h,c,u,d,g,y,w,C,N,x;return h=n(36),e===s?e:e.constructor===o&&s.constructor===o&&e.tagName===s.tagName&&e.namespace===s.namespace?(c=f(t,e,s,a),d=new o(e.tagName,{},c),u=p(t,e.className,s.className),w=v(t,e.props,s.props),C=v(t,e.style,s.style),y=m(t,e.domEventCallbackMap,s.domEventCallbackMap),d.addClass(u).prop(w).css(C).bind(y)):e.isHtml&&s.isHtml?(N=e.transform,g=s.transform,x=function(e){return t()?N&&N(e)||e:g&&g(e)||e},new e.constructor(l(t,e.text,s.text),x)):e.isText&&s.isText&&e.constructor===s.constructor?new e.constructor(l(t,e.text,s.text)):e instanceof r&&s instanceof r?e:e.isList&&s.isList?new i(f(t,e,s,a)):new h(t,e,s,!1,!1,!0)},d=function(t,e,i,r){var o;return r||!e.isList&&!i.isList?u(t,e,i,r):new(o=n(36))(t,e,i,!1,!1,!0)},e.mergeIfChildren=f=function(t,e,n,i){var o,s,a,h,c,l,f,p,m,v,g,y,w,C;if(l=e.children,s=n.children,f=l.length,a=s.length,f===a)for(o=new Array(f),c=m=0,y=l.length;y>m;c=++m)p=l[c],o[c]=d(t,p,s[c],i);else if(a>f){for(o=new Array(a),c=v=0,w=l.length;w>v;c=++v)p=l[c],o[c]=d(t,p,s[c],i);for(;a>c;)o[c]=u(t,new r,s[c]),c++}else{for(o=new Array(f),c=g=0,C=s.length;C>g;c=++g)h=s[c],o[c]=d(t,l[c],h,i);for(;f>c;)o[c]=u(t,l[c],new r),c++}return o},p=function(t,e,n){return v(t,e.classMap,n.classMap)},v=function(t,e,n){var i,r;r=h({},e,n);for(i in r)r[i]=l(t,e[i],n[i]);return r},a=function(){},m=function(t,e,n){var i,r,o,c,l,u;u=h({},e,n);for(o in u)l=(c=e[o])?s(c.slice(0)):a,r=(i=n[o])?s(i.slice(0)):a,u[o]=function(e){return t()?l.call(this,e):r.call(this,e)};return u}},function(t,e,n){var i,r,o,s,a,h,c,l,u,d={}.hasOwnProperty,f=function(t,e){function n(){this.constructor=t}for(var i in e)d.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};l=n(18),r=n(35),u=n(1),o=u.foreach,s=u.funcString,h=u.newLine,a=u.intersect,c=n(6).renew,t.exports=i=function(t){function e(t,n,i,r){var s,h;return this.map=n,null==r&&(r=!1),r||"function"==typeof t?(o(n,function(t,e){return n[e]=l(t)}),this.else_=l(i),s=[],o(n,function(t){return s.push(t.family)}),s.push(this.else_.family),this.family=h=a(s),h[this.dcid]=!0,void e.__super__.constructor.call(this,t)):l(n.hasOwnPoperty(t)?n[key]:i)}return f(e,t),e.prototype.getContentComponent=function(){return this.map[this.getTestValue()]||this.else_},e.prototype.clone=function(){var t;return t=o(this.map,function(t){return t.clone()}),new e(this.test,t,this.else_.clone()).copyEventListeners(this)},e.prototype.toString=function(t,e){var n;return null==t&&(t=0),n=h("",t,e)+"<Case "+s(this.test)+">",o(this.map,function(e,i){return n+=h(i+": "+e.toString(t+2,!1),t+2,!0)}),n+=this.else_.toString(t+2,!0)+h("</Case>",t,!0)},e}(r)},function(t,e,n){var i,r,o,s,a,h={}.hasOwnProperty,c=function(t,e){function n(){this.constructor=t}for(var i in e)h.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};a=n(18),r=n(16),s=n(1).newLine,o=n(3),t.exports=i=function(t){function e(t,n,i){var r,s,h,c;this.host=t,e.__super__.constructor.call(this),h=this,null==n?this.field=n="content":this.field=n,i?this._content=t[n]=a(i):this._content=t[n]=a(t[n]),this.family=r=o({},this._content.family),r[this.dcid]=!0,Object.defineProperty&&(s=function(){return h._content},c=function(t){return h.setContent(t),t},Object.defineProperty(t,n,{get:s,set:c}))}return c(e,t),e.prototype.setContent=function(t){var e;return e=this._content,t===e?this:(this.invalidateTransform(),this.onSetContent(t,e),this._content=a(t),this)},e.prototype.onSetContent=function(t,e){return this},e.prototype.getContentComponent=function(){return this._content},e.prototype.clone=function(){return new this.constructor(this.host,this.field).copyEventListeners(this)},e.prototype.toString=function(t,e){return null==t&&(t=0),null==e&&(e=""),s("",t,e)+"<Pick:"+this.field+": "+this._content.toString(t+2,!0)+">"},e}(r)},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m={}.hasOwnProperty,v=function(t,e){function n(){this.constructor=t}for(var i in e)m.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};f=n(18),a=n(16),h=n(3),p=n(1),c=p.funcString,u=p.newLine,l=p.intersect,d=n(6).renew,o=0,r=1,s=2,t.exports=i=function(t){function e(t,n,i,a){var h,c;return this.promise=t,e.__super__.constructor.apply(this,arguments),this.fulfill=n||function(t){return t},c=i||function(t){return t},this.init=a&&a(t,this)||new Nothing,this.family=h=l([fullfill.family,i.family,a.family]),h[this.dcid]=!0,this.promiseState=o,t.then(function(t){return this.promiseResult=t,this.promiseState=r,this.invalidateTransform()})["catch"](function(t){return this.promiseResult=t,this.promiseState=s,this.invalidateTransform()}),this}return v(e,t),e.prototype.getContentComponent=function(){var t;return(t=this.promiseState)===o?init:f(t===r?this.fulfill(this.promiseResult,this.promise,this):this.reject(this.promiseResult,this.promise,this))},e.prototype.clone=function(){return new e(this.promise,this.fulfill,this.reject,this.init.clone).copyEventListeners(this)},e.prototype.toString=function(t,e){return null==t&&(t=0),null==e&&(e=""),u("",t,e)+"<Defer "+this.promise+">"+u("",t,e)+c(this.fulfill)+u("",t,e)+c(this.reject)+this.init.toString(t+2,!0)+u("</Defer>",t,!0)},e}(a),h(i,{INIT:o,FULFILL:r,REJECT:s})},function(t,e,n){var e,i;i=n(3),t.exports=e=i({},n(22),n(23),n(25),n(42),n(24),n(43)),e.classFn=n(23)},function(t,e,n){var i,r,o,s,a,h;i=n(30),r=/[\d\s\.-]/g,e.unitAdd=o=function(t,e){var n;return n=parseFloat(t),isNaN(n)&&console.log("wrong type in unitAdd(prop, value)"),n+parseFloat(e)+t.replace(r,"")},e.unitSub=h=function(t,e){var n;return n=parseFloat(t),isNaN(n)&&console.log("wrong type in unitSub(prop, value)"),n-parseFloat(e)+t.replace(r,"")},e.unitMul=a=function(t,e){var n;return n=parseFloat(t),isNaN(n)&&console.log("wrong type in unitMul(prop, value)"),n*parseFloat(e)+t.replace(r,"")},e.unitDiv=s=function(t,e){var n;return n=parseFloat(t),isNaN(n)&&console.log("wrong type in unitDiv(prop, value)"),n/parseFloat(e)+t.replace(r,"")},i.prototype.cssAdd=function(t,e){var n;return n=o(this.css(t),e),this.css(t,n)},i.prototype.cssSub=function(t,e){return this.css(t,h(this.css(t),e))},i.prototype.cssMul=function(t,e){return this.css(t,a(this.css(t),e))},i.prototype.cssDiv=function(t,e){return this.css(t,s(this.css(t),e))}},function(t,e,n){var i,r,o,s,a;r=n(30),i=n(4),e.makeDelegationHandler=s=function(){return function(t){var e,n;return n=t.target,e=n.component,e["do_"+t.type](t)}},r.prototype.delegate=i.prototype.delegate=function(t,e){return null==e&&(e=s()),this.bind(t,e)},e.makeHolderDelegationHandler=a=function(){return function(t){var e,n,i,r;for(r=t.target,i=r.component,n="do_"+t.type;i;)if(e=i[n]){if(e.call(i,t),!t.continueDelegating)break;i=i.holder}else i=i.holder}},r.prototype.delegateByHolder=i.prototype.delegateByHolder=function(t,e){return null==e&&(e=a()),this.bind(t,e)},o=function(t){return function(e){var n;(n=t["do_"+e.type])&&n.call(t,e)}},r.prototype.delegateByComponent=i.prototype.delegateByComponent=function(t,e){return this.bind(t,o(e))}},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g,y,w,C=[].slice;for(i=n(3),y=n(13),h=y.tag,a=y.isAttrs,r=n(5).getBindProp,l="a abbr acronym address area b base bdo big blockquote body br button caption cite code col colgroup dd del dfn div dl dt em fieldset form h1 h2 h3 h4 h5 h6 head hr i img input ins kbd label legend li link map meta noscript object ol optgroup option p param pre q samp script select small span strong style sub sup table tbody td textarea tfoot th thead title tr tt ul var header footer section svg iframe",l=l.split(" "),d=function(t){return e[t]=function(){var e;return e=1<=arguments.length?C.call(arguments,0):[],h.apply(null,[t].concat(C.call(e)))}},p=0,v=l.length;v>p;p++)c=l[p],d(c);for(e.tagHtml=function(){var t;return t=1<=arguments.length?C.call(arguments,0):[],h.apply(null,["html"].concat(C.call(t)))},s="text checkbox radio date email number".split(" "),o=e.input=function(t,e,n){var o;return"object"==typeof t&&(n=e,e=t,t="text"),e=i({type:t},e),o=h("input",e),null!=n&&(o.prop(r(o),n),n.isDuplex&&o.bind("onchange",function(t,e){return n.call(this,e.value)},"before")),o},w="text checkbox radio date email tel number".split(" "),f=function(t){return e[t]=function(e,n){var i;return"object"==typeof e&&(i=n,n=e,e=i),n=n||{},o(t,n,e)}},m=0,g=w.length;g>m;m++)u=w[m],f(u);e.textarea=function(t,e){var n;return a(t)?null!=e?(t=i({value:e},t),n=h("textarea",t),e.isDuplex&&n.bind("onchange",function(t,n){return e.call(this,n.value)},"before")):n=h("textarea",t):null!=t?(n=h("textarea",{value:t}),t.isDuplex&&n.bind("onchange",function(e,n){return t.call(this,n.value)},"before")):n=h("textarea"),n}},function(t,e,n){var i,r,o,s,a,h,c,l,u,d,f,p,m,v,g,y=[].slice;m=n(14),i=m.List,r=m.Tag,d=m.toComponent,v=n(1),c=v.isArray,u=v.isObject,g=n(10),f=g.watchItems,l=g.isEachObjectSystemKey,o=function(t){return t},p=function(t,e,n){var s,a,h,l,u,f,p,m,v,g,y;if(t?(t.tagName?(v=t.tagName,delete t.tagName):v="div",t.EachClass?(s=t.EachClass,delete t.EachClass):s=r,m=new s(v,t,[])):(s=e.EachClass||i,m=new s([])),m.items=e,"function"==typeof n?(m.itemFunc=n,n={}):(n=n||{},m.itemFunc=n.itemFunc||o),m.separatorFunc=n.separatorFunc,m.updateSuccChild=n.updateSuccChild,m.updateSuccIndex=n.updateSuccIndex,m.keyChildMap=p={},c(e)?m.getItemComponent=h=function(t,n){var r,o;return r=d(m.itemFunc(t,n,e,m)),m.separatorFunc&&n&&(o=d(m.separatorFunc(n,t,e,m)),r=new i([o,r])),r.itemIndex=n,r}:m.getItemComponent=h=function(t,n){var r,o,s;return s=e[t],p[t]=n,r=d(m.itemFunc(s,t,n,m)),m.separatorFunc&&n&&(o=d(m.separatorFunc(n,s,t,m)),r=new i([o,r])),r.$watchingKey=t,r.itemIndex=n,r},a=[],c(e))for(l=g=0,y=e.length;y>g;l=++g)u=e[l],a.push(h(u,l));else{l=0;for(f in e)a.push(h(f,l)),l++}return m.setChildren(0,a)},h=function(t){var e,n,i,r;if(e=t[0],n=t[1],r=t[2],1===t.length)return[null,e,{}];if(3===t.length)return[e,n,r];if("function"==typeof n)return[null,e,{itemFunc:n}];if(c(n))return[e,n,{}];if(c(e))return[null,e,n];if(n){if(u(n)){for(i in n)if(!n.hasOwnProperty(i)&&i.test(/itemFunc|separatorFunc|updateSuccChild|updateSuccIndex/))return[null,e,n];return[e,n,{}]}throw new Error("wrong parameter")}return[null,e,{}]},e.every=a=function(){var t,e,n,i,r;return t=1<=arguments.length?y.call(arguments,0):[],r=h(t),e=r[0],n=r[1],i=r[2],p(e,n,i)},e.each=s=function(){var t,e,n,i,r,o;return t=1<=arguments.length?y.call(arguments,0):[],o=h(t),e=o[0],n=o[1],r=o[2],i=a(e,n,r),f(n,i)},e.funcEach=function(t,e,n){var i,r,o,a;return"function"==typeof t&&(n=e,e=t,t=null,i=e.EachClass),o=e(),o=c(o)?o.slice(0):extend({},o),i&&(o.EachClass=i),r=s(t,o,n),a=function(){var t;return t=e(),o.replaceAll(t)},e.onInvalidate?e.onInvalidate(a):(r.on("willRenderDom",function(){return r.node?a():void 0}),r.on("didRenderDom",function(){return r.invalidate()})),r}},function(t,e){var n,i,r,o,s,a,h={}.hasOwnProperty,c=function(t,e){function n(){this.constructor=t}for(var i in e)h.call(e,i)&&(t[i]=e[i]);return n.prototype=e.prototype,t.prototype=new n,t.__super__=e.prototype,t};r=[].slice,o=/at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi,s=/at\s+()(.*):(\d*):(\d*)/gi,a=function(t,e){var n,r,a,h,c,l,u,d,f;for(null==e&&(e=1),t?(i.prodution||console.log(t),t+=":\n"):t="",n=new Error,i.prodution||console.log(n),d=n.stack.split("\n").slice(3),e=1,f=d.length;f>e;)u=d[e],a=o.exec(u)||s.exec(u),a&&5===a.length&&(c=a[1],r=a[2],h=a[3],l=a[4],t+=r+":"+h+":"+l+":"+c+"\n"),e++;return t},e.DomcomError=n=function(t){function e(t,e){this.message=t,this.component=e}return c(e,t),e.prototype.toString=function(){return this.component?this.component.toString()+"\n"+this.message:this.message},e}(Error),e.error=i=function(t,e){throw t=a(t,2),new n(t,e)},e.onerror=function(t,e){throw t instanceof n?(console.log(t),new Error(t.message)):t instanceof Error?t:(e?(console.log(e),console.log(t)):console.log(t),new Error(t+":\n"+a()))}},function(t,e,n){var i,r,o;e.$model=n(48),e.$bind=n(49),o=n(50),r=o.$show,i=o.$hide,e.$show=r,e.$hide=i,e.$options=n(51)},function(t,e,n){var i;i=n(5).getBindProp,t.exports=function(t,e){return function(n){var r,o;return o=n.props,r=i(n),n.setProp(r,t,o,"Props"),n.bind(e||"onchange",function(e,n){return t(n[r])},"before"),n}}},function(t,e,n){var i;i=n(5).getBindProp,t.exports=function(t){return function(e){return e.setProp(i(e),t,e.props,"Props"),e}}},function(t,e){var n;n=function(t){return function(e,n){return function(i){return i.showHide(t,e,n),i}}},e.$show=n(!0),e.$hide=n(!1)},function(t,e,n){var i,r,o;o=n(13).txt,r=n(44).option,i=n(30),t.exports=function(t,e){return function(n){var s,a,h,c;if(!(n instanceof i)||"select"!==n.tagName)throw new Error("options should be only used in select tag");if(a=[],t)for(h=0,c=t.length;c>h;h++)s=t[h],a.push(r(e,[o(s)]));return n.setChildren(0,a)}}}]);
packages/my-joy-images/src/mocks/theme.js
geek/joyent-portal
import React from 'react'; import { ThemeProvider } from 'styled-components'; import { theme, RootContainer, PageContainer, ViewContainer } from 'joyent-ui-toolkit'; export default ({ children, ss }) => ( <ThemeProvider theme={theme}> {ss ? ( <RootContainer> <PageContainer> <ViewContainer>{children}</ViewContainer> </PageContainer> </RootContainer> ) : ( children )} </ThemeProvider> );
src/screens/Shared/RelatedIllusts.js
alphasp/pxview
import React, { Component } from 'react'; import { View, StyleSheet, InteractionManager } from 'react-native'; import { connect } from 'react-redux'; import { connectLocalization } from '../../components/Localization'; import IllustList from '../../components/IllustList'; import IllustItem from '../../components/IllustItem'; import NoResult from '../../components/NoResult'; import ViewMoreButton from '../../components/ViewMoreButton'; import Loader from '../../components/Loader'; import * as relatedIllustsActionCreators from '../../common/actions/relatedIllusts'; import { makeGetRelatedIllustsItems } from '../../common/selectors'; import { globalStyles } from '../../styles'; import { SCREENS } from '../../common/constants'; const styles = StyleSheet.create({ viewMoreButtonContainer: { margin: 10, }, // should be same with FlatList listContainer: { flexGrow: 1, flexShrink: 1, flexDirection: 'row', flexWrap: 'wrap', overflow: 'scroll', }, }); class RelatedIllusts extends Component { componentDidMount() { const { relatedIllusts, illustId, fetchRelatedIllusts, clearRelatedIllusts, } = this.props; // will render blank unless scrolled // https://github.com/facebook/react-native/issues/10142 if (!relatedIllusts || !relatedIllusts.items) { clearRelatedIllusts(illustId); InteractionManager.runAfterInteractions(() => { fetchRelatedIllusts(illustId); }); } } loadMoreItems = () => { const { relatedIllusts, illustId, fetchRelatedIllusts } = this.props; if (relatedIllusts && !relatedIllusts.loading && relatedIllusts.nextUrl) { fetchRelatedIllusts(illustId, null, relatedIllusts.nextUrl); } }; handleOnRefresh = () => { const { illustId, fetchRelatedIllusts, clearRelatedIllusts } = this.props; clearRelatedIllusts(illustId); fetchRelatedIllusts(illustId, null, null, true); }; handleOnPressViewMoreRelatedIllusts = () => { const { illustId, navigation: { push }, } = this.props; push(SCREENS.RelatedIllusts, { illustId, }); }; handleOnPressItem = (item, index) => { const { items, navigation: { push }, maxItems, } = this.props; push(SCREENS.Detail, { items: maxItems ? items.slice(0, maxItems) : items, index, }); }; renderList = () => { const { relatedIllusts, items, maxItems, isFeatureInDetailPage, isDetailPageReady, listKey, } = this.props; if (isFeatureInDetailPage) { if (!isDetailPageReady) { return <Loader />; } if (relatedIllusts?.loaded && items?.length) { return ( <View style={styles.listContainer}> {items.slice(0, maxItems).map((item, index) => { return ( <IllustItem key={item.id} illustId={item.id} index={index} numColumns={3} onPressItem={() => this.handleOnPressItem(item, index)} /> ); })} </View> ); } return null; } return ( <IllustList data={{ ...relatedIllusts, items }} listKey={listKey} loadMoreItems={this.loadMoreItem} onRefresh={this.handleOnRefresh} /> ); }; render() { const { relatedIllusts, items, i18n, isFeatureInDetailPage, isDetailPageReady, } = this.props; return ( <View style={globalStyles.container}> {this.renderList()} {relatedIllusts?.loaded && !items?.length && ( <NoResult text={i18n.noRelatedWorks} /> )} {isFeatureInDetailPage && isDetailPageReady && relatedIllusts?.loaded && items?.length ? ( <View style={styles.viewMoreButtonContainer}> <ViewMoreButton onPress={this.handleOnPressViewMoreRelatedIllusts} /> </View> ) : null} </View> ); } } export default connectLocalization( connect(() => { const getRelatedIllustsItems = makeGetRelatedIllustsItems(); return (state, props) => { const { relatedIllusts } = state; const { listKey } = props; const illustId = props.illustId || props.route.params.illustId; return { relatedIllusts: relatedIllusts[illustId], items: getRelatedIllustsItems(state, props), illustId, listKey: listKey || `${props.route.key}-${illustId}`, }; }; }, relatedIllustsActionCreators)(RelatedIllusts), );
src/svg-icons/device/storage.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceStorage = (props) => ( <SvgIcon {...props}> <path d="M2 20h20v-4H2v4zm2-3h2v2H4v-2zM2 4v4h20V4H2zm4 3H4V5h2v2zm-4 7h20v-4H2v4zm2-3h2v2H4v-2z"/> </SvgIcon> ); DeviceStorage = pure(DeviceStorage); DeviceStorage.displayName = 'DeviceStorage'; DeviceStorage.muiName = 'SvgIcon'; export default DeviceStorage;
examples/react/src/players/FullControl.js
thangngoc89/react-howler
import React from 'react' import ReactHowler from 'ReactHowler' import raf from 'raf' // requestAnimationFrame polyfill import Button from '../components/Button' class FullControl extends React.Component { constructor (props) { super(props) this.state = { playing: false, loaded: false, loop: false, mute: false, volume: 1.0, seek: 0.0, rate: 1, isSeeking: false } this.handleToggle = this.handleToggle.bind(this) this.handleOnLoad = this.handleOnLoad.bind(this) this.handleOnEnd = this.handleOnEnd.bind(this) this.handleOnPlay = this.handleOnPlay.bind(this) this.handleStop = this.handleStop.bind(this) this.renderSeekPos = this.renderSeekPos.bind(this) this.handleLoopToggle = this.handleLoopToggle.bind(this) this.handleMuteToggle = this.handleMuteToggle.bind(this) this.handleMouseDownSeek = this.handleMouseDownSeek.bind(this) this.handleMouseUpSeek = this.handleMouseUpSeek.bind(this) this.handleSeekingChange = this.handleSeekingChange.bind(this) this.handleRate = this.handleRate.bind(this) } componentWillUnmount () { this.clearRAF() } handleToggle () { this.setState({ playing: !this.state.playing }) } handleOnLoad () { this.setState({ loaded: true, duration: this.player.duration() }) } handleOnPlay () { this.setState({ playing: true }) this.renderSeekPos() } handleOnEnd () { this.setState({ playing: false }) this.clearRAF() } handleStop () { this.player.stop() this.setState({ playing: false // Need to update our local state so we don't immediately invoke autoplay }) this.renderSeekPos() } handleLoopToggle () { this.setState({ loop: !this.state.loop }) } handleMuteToggle () { this.setState({ mute: !this.state.mute }) } handleMouseDownSeek () { this.setState({ isSeeking: true }) } handleMouseUpSeek (e) { this.setState({ isSeeking: false }) this.player.seek(e.target.value) } handleSeekingChange (e) { this.setState({ seek: parseFloat(e.target.value) }) } renderSeekPos () { if (!this.state.isSeeking) { this.setState({ seek: this.player.seek() }) } if (this.state.playing) { this._raf = raf(this.renderSeekPos) } } handleRate (e) { const rate = parseFloat(e.target.value) this.player.rate(rate) this.setState({ rate }) } clearRAF () { raf.cancel(this._raf) } render () { return ( <div className='full-control'> <ReactHowler src={['sound.ogg', 'sound.mp3']} playing={this.state.playing} onLoad={this.handleOnLoad} onPlay={this.handleOnPlay} onEnd={this.handleOnEnd} loop={this.state.loop} mute={this.state.mute} volume={this.state.volume} ref={(ref) => (this.player = ref)} /> <p>{(this.state.loaded) ? 'Loaded' : 'Loading'}</p> <div className='toggles'> <label> Loop: <input type='checkbox' checked={this.state.loop} onChange={this.handleLoopToggle} /> </label> <label> Mute: <input type='checkbox' checked={this.state.mute} onChange={this.handleMuteToggle} /> </label> </div> <p> {'Status: '} {this.state.seek.toFixed(2)} {' / '} {(this.state.duration) ? this.state.duration.toFixed(2) : 'NaN'} </p> <div className='volume'> <label> Volume: <span className='slider-container'> <input type='range' min='0' max='1' step='.05' value={this.state.volume} onChange={e => this.setState({ volume: parseFloat(e.target.value) })} /> </span> {this.state.volume.toFixed(2)} </label> </div> <div className='seek'> <label> Seek: <span className='slider-container'> <input type='range' min='0' max={this.state.duration ? this.state.duration.toFixed(2) : 0} step='.01' value={this.state.seek} onChange={this.handleSeekingChange} onMouseDown={this.handleMouseDownSeek} onMouseUp={this.handleMouseUpSeek} /> </span> </label> </div> <div className='rate'> <label> Rate: <span className='slider-container'> <input type='range' min='0.1' max='3' step='.01' value={this.state.rate} onChange={this.handleRate} /> </span> {this.state.rate.toFixed(2)} </label> </div> <Button onClick={this.handleToggle}> {(this.state.playing) ? 'Pause' : 'Play'} </Button> <Button onClick={this.handleStop}> Stop </Button> </div> ) } } export default FullControl
flow-typed/npm/babel-plugin-flow-runtime_vx.x.x.js
amilajack/compat-db
// flow-typed signature: 37efe00f0076b72e21d93eb1f00dc237 // flow-typed version: <<STUB>>/babel-plugin-flow-runtime_v^0.18.0/flow_v0.94.0 /** * This is an autogenerated libdef stub for: * * 'babel-plugin-flow-runtime' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'babel-plugin-flow-runtime' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'babel-plugin-flow-runtime/babel-plugin-flow-runtime' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/config/eslint' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/cli_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/core_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/generator_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/helper-plugin-utils_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/parser_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-class-properties_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-decorators_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-object-rest-spread_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/polyfill_v7.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-env_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-flow_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-react_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/register_v7.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/traverse_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/babel-eslint_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/camelcase_v3.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/dedent_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-babel_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-flowtype_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-import_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-jsx-a11y_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-react_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/flow-bin_v0.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/flow-config-parser_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/json-loader_vx.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/mocha_v5.x.x' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/100-typed-object-spread' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/123-extend-interface' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/135-quoted-property-keys' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/137-support-$Values' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultArrowFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultClassNoName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultFunctionNoName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/140-reexport-flow-type' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/141-symbol-type' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/159-quoted-interface-method-names' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/159-quoted-property-names-in-object-literal' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/24-allow-import-star-react' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/24-allow-import-star' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/28-decorate-with-export-default' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/38-intersection-object' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/46-static-properties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/47-arguments-hoisting' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/49-invalid-transform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/56-indexer-no-identifier' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/65-arrow-function-name' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/67-async-destructuring-with-multiple' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/67-async-destructuring' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/72-generators' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/77-generator-transform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/78-support-$Exact' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/constTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/generatorFunctions' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/missingNode' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/stringPropertyKeys' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/tdzExportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importClashName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntime' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntimeReify' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntimeReifyNoDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/shorthandImportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/simplestExportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/simplestImportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/arrayPatternWithRest' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedMultipleRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestMatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedRestMatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithClashingArgs' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithClashingVars' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithMultipleArgs' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithUnion' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleArrayPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleMatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleMatchNoDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleObjectPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplePattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplePatternNoDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplestRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaIgnore' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaOptInStrict' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarn' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarnAndDecorate' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarnClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressComment' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressCommentClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressCommentIfBlock' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/specialForms/classAnnotation' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/arrays/arrayOfArrays' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/arrays/numberArray' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/builtins/date' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/builtins/map' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/defaultTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithAnonymousParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleOptionalParams' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleParams' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithOptionalParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithRestParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithTrailingRestParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestBoundTypeParameterizedFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestTypeParameterizedFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/typeParameterizedFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/hoistedNestedType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/hoistedType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/mutualRecursion' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleCallProperties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleIndexers' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleProperties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithOptionalProperties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithPropertiesCallPropertiesIndexers' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/personObjectWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestExactObject' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObject' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectCallProperty' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectIndexer' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/boolean' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/booleanLiteral' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/number' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/numericLiteral' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/string' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/stringLiteral' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/selfReferentialType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/simplestParameterizedType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/simplestTypeParameterApplication' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/tuples/tuple' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/unions/numberStringUnion' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithInterfaceAndConstructor' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithMultipleInterfacesAndSuper' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithTypeParametersAndStaticMethods' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassNoDefaults' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithAccessors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithComputedProperty' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithInterface' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethod' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethodWithDefaultArg' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMultipleInterface' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithParent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithStatics' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/thisTypeAnnotation' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/typeParametersWithInheritance' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/arrayPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/boundTypeParameter' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/defaultParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/delegatingGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/functionReturnsPromise' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/multipleParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/multipleTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nestedAsyncFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nestedFunctionWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nextGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPatternLastParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPatternWithDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/optionalObjectPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/optionalParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/restParams' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/returningGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestAsyncFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/modules/simplestExport' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/modules/simplestImport' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactClassWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportComponent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportComponentWithAlias' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportPureComponent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactPureComponent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/simplestReactClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/tryCatch/simplestTryCatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/inlineTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/repeatedTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/simplestTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/typeCastMemberExpression' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/qualifiedTypeOf' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/simplestTypeOf' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/typeQualifiedTypeOf' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/constDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithAssignment' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithMultipleAssignments' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/patternDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/varDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/varDeclarationWithAssignment' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/awaitAndPromise' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithConcreteSuper' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithSuperTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/simplestClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/simplestClassWithSuper' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/functions/simplestFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModule' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleExports' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleWithStringName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/types/simplestType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/vars/simplestVar' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/vars/simplestVarWithAnnotation' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/fixtures' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/pragmaOptInOnly.test' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/testTransform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/__tests__/transform.test' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/annotateVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/attachImport' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/collectProgramOptions' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/ConversionContext' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/convert' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/createConversionContext' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/Entity' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/findIdentifiers' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/firstPassVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/getTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/hasTypeAnnotations' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/index' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/loadFlowConfig' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/patternMatchVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/preTransformVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/symbols' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/transform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/transformVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/typeAnnotationIterator' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/lib/util' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/100-typed-object-spread' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/123-extend-interface' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/135-quoted-property-keys' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/137-support-$Values' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultArrowFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultClassNoName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultFunctionNoName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/140-reexport-flow-type' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/141-symbol-type' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/159-quoted-interface-method-names' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/159-quoted-property-names-in-object-literal' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/24-allow-import-star-react' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/24-allow-import-star' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/28-decorate-with-export-default' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/38-intersection-object' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/46-static-properties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/47-arguments-hoisting' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/49-invalid-transform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/56-indexer-no-identifier' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/65-arrow-function-name' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/67-async-destructuring-with-multiple' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/67-async-destructuring' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/72-generators' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/77-generator-transform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/78-support-$Exact' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/constTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/generatorFunctions' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/missingNode' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/stringPropertyKeys' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/tdzExportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importClashName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntime' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntimeReify' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntimeReifyNoDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/shorthandImportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/simplestExportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/simplestImportType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/arrayPatternWithRest' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedMultipleRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestMatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedRestMatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithClashingArgs' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithClashingVars' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithMultipleArgs' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithUnion' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleArrayPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleMatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleMatchNoDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleObjectPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplePattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplePatternNoDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplestRestPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaIgnore' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaOptInStrict' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarn' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarnAndDecorate' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarnClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressComment' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressCommentClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressCommentIfBlock' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/specialForms/classAnnotation' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/arrays/arrayOfArrays' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/arrays/numberArray' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/builtins/date' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/builtins/map' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/defaultTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithAnonymousParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleOptionalParams' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleParams' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithOptionalParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithRestParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithTrailingRestParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestBoundTypeParameterizedFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestTypeParameterizedFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/typeParameterizedFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/hoistedNestedType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/hoistedType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/mutualRecursion' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleCallProperties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleIndexers' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleProperties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithOptionalProperties' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithPropertiesCallPropertiesIndexers' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/personObjectWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestExactObject' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObject' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectCallProperty' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectIndexer' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/boolean' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/booleanLiteral' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/number' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/numericLiteral' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/string' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/stringLiteral' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/selfReferentialType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/simplestParameterizedType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/simplestTypeParameterApplication' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/tuples/tuple' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/unions/numberStringUnion' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithInterfaceAndConstructor' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithMultipleInterfacesAndSuper' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithTypeParametersAndStaticMethods' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassNoDefaults' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithAccessors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithComputedProperty' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithInterface' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethod' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethodWithDefaultArg' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMultipleInterface' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithParent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithStatics' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/thisTypeAnnotation' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/typeParametersWithInheritance' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/arrayPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/boundTypeParameter' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/defaultParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/delegatingGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/functionReturnsPromise' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/multipleParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/multipleTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nestedAsyncFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nestedFunctionWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nextGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPatternLastParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPatternWithDefault' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/optionalObjectPattern' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/optionalParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/restParams' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/returningGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestAsyncFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithParam' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestGeneratorFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/modules/simplestExport' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/modules/simplestImport' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactClassWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportComponent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportComponentWithAlias' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportPureComponent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactPureComponent' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/simplestReactClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/tryCatch/simplestTryCatch' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/inlineTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/repeatedTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/simplestTypeCast' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/typeCastMemberExpression' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/qualifiedTypeOf' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/simplestTypeOf' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/typeQualifiedTypeOf' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/constDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithAssignment' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithMultipleAssignments' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/patternDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/varDeclaration' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/varDeclarationWithAssignment' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/awaitAndPromise' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithConcreteSuper' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithSuperTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/simplestClass' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/simplestClassWithSuper' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/functions/simplestFunction' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModule' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleExports' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleWithStringName' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/types/simplestType' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/vars/simplestVar' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/vars/simplestVarWithAnnotation' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/fixtures' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/pragmaOptInOnly.test' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/testTransform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/__tests__/transform.test' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/annotateVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/attachImport' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/collectProgramOptions' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/ConversionContext' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/convert' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/createConversionContext' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/Entity' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/findIdentifiers' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/firstPassVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/getTypeParameters' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/hasTypeAnnotations' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/index' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/loadFlowConfig' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/patternMatchVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/preTransformVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/symbols' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/transform' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/transformVisitors' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/typeAnnotationIterator' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/src/util' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/test-polyfill' { declare module.exports: any; } declare module 'babel-plugin-flow-runtime/tools/makeFixturesJSON' { declare module.exports: any; } // Filename aliases declare module 'babel-plugin-flow-runtime/babel-plugin-flow-runtime.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/babel-plugin-flow-runtime'>; } declare module 'babel-plugin-flow-runtime/config/eslint.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/config/eslint'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/cli_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/cli_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/core_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/core_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/generator_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/generator_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/helper-plugin-utils_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/helper-plugin-utils_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/parser_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/parser_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-class-properties_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-class-properties_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-decorators_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-decorators_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-object-rest-spread_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/plugin-proposal-object-rest-spread_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/polyfill_v7.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/polyfill_v7.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-env_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-env_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-flow_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-flow_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-react_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/preset-react_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/register_v7.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/register_v7.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/@babel/traverse_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/@babel/traverse_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/babel-eslint_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/babel-eslint_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/camelcase_v3.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/camelcase_v3.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/dedent_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/dedent_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/eslint_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-babel_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-babel_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-flowtype_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-flowtype_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-import_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-import_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-jsx-a11y_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-jsx-a11y_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-react_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/eslint-plugin-react_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/flow-bin_v0.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/flow-bin_v0.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/flow-config-parser_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/flow-config-parser_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/json-loader_vx.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/json-loader_vx.x.x'>; } declare module 'babel-plugin-flow-runtime/flow-typed/npm/mocha_v5.x.x.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/flow-typed/npm/mocha_v5.x.x'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/100-typed-object-spread.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/100-typed-object-spread'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/123-extend-interface.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/123-extend-interface'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/135-quoted-property-keys.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/135-quoted-property-keys'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/137-support-$Values.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/137-support-$Values'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultArrowFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultArrowFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultClassNoName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultClassNoName'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultFunctionNoName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/14-exportDefaultFunctionNoName'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/140-reexport-flow-type.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/140-reexport-flow-type'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/141-symbol-type.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/141-symbol-type'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/159-quoted-interface-method-names.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/159-quoted-interface-method-names'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/159-quoted-property-names-in-object-literal.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/159-quoted-property-names-in-object-literal'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/24-allow-import-star-react.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/24-allow-import-star-react'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/24-allow-import-star.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/24-allow-import-star'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/28-decorate-with-export-default.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/28-decorate-with-export-default'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/38-intersection-object.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/38-intersection-object'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/46-static-properties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/46-static-properties'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/47-arguments-hoisting.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/47-arguments-hoisting'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/49-invalid-transform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/49-invalid-transform'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/56-indexer-no-identifier.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/56-indexer-no-identifier'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/65-arrow-function-name.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/65-arrow-function-name'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/67-async-destructuring-with-multiple.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/67-async-destructuring-with-multiple'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/67-async-destructuring.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/67-async-destructuring'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/72-generators.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/72-generators'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/77-generator-transform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/77-generator-transform'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/78-support-$Exact.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/78-support-$Exact'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/constTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/constTypeCast'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/generatorFunctions.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/generatorFunctions'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/missingNode.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/missingNode'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/stringPropertyKeys.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/stringPropertyKeys'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/tdzExportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/bugs/tdzExportType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importClashName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importClashName'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntime.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntime'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntimeReify.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntimeReify'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntimeReifyNoDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/importFlowRuntimeReifyNoDefault'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/shorthandImportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/shorthandImportType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/simplestExportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/simplestExportType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/simplestImportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/importsExports/simplestImportType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/arrayPatternWithRest.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/arrayPatternWithRest'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedMultipleRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedMultipleRestPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestMatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestMatch'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedRestMatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedRestMatch'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/mixedRestPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithClashingArgs.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithClashingArgs'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithClashingVars.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithClashingVars'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithMultipleArgs.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithMultipleArgs'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithUnion.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/patternWithUnion'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleArrayPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleArrayPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleMatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleMatch'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleMatchNoDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleMatchNoDefault'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleObjectPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simpleObjectPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplePattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplePattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplePatternNoDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplePatternNoDefault'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplestRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/patternMatching/simplestRestPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaIgnore.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaIgnore'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaOptInStrict.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaOptInStrict'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarn.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarn'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarnAndDecorate.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarnAndDecorate'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarnClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/pragmaWarnClass'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressComment.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressComment'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressCommentClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressCommentClass'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressCommentIfBlock.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressCommentIfBlock'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/pragma/suppressType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/specialForms/classAnnotation.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/specialForms/classAnnotation'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/arrays/arrayOfArrays.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/arrays/arrayOfArrays'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/arrays/numberArray.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/arrays/numberArray'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/builtins/date.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/builtins/date'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/builtins/map.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/builtins/map'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/defaultTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/defaultTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithAnonymousParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithAnonymousParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleOptionalParams.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleOptionalParams'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleParams.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleParams'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithOptionalParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithOptionalParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithRestParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithRestParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithTrailingRestParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/functionWithTrailingRestParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestBoundTypeParameterizedFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestBoundTypeParameterizedFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestTypeParameterizedFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/simplestTypeParameterizedFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/typeParameterizedFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/functions/typeParameterizedFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/hoistedNestedType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/hoistedNestedType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/hoistedType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/hoistedType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/mutualRecursion.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/mutualRecursion'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleCallProperties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleCallProperties'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleIndexers.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleIndexers'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleProperties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleProperties'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithOptionalProperties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithOptionalProperties'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithPropertiesCallPropertiesIndexers.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/objectWithPropertiesCallPropertiesIndexers'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/personObjectWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/personObjectWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestExactObject.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestExactObject'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObject.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObject'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectCallProperty.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectCallProperty'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectIndexer.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectIndexer'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/objects/simplestObjectWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/boolean.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/boolean'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/booleanLiteral.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/booleanLiteral'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/number.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/number'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/numericLiteral.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/numericLiteral'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/string.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/string'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/stringLiteral.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/primitives/stringLiteral'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/selfReferentialType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/selfReferentialType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/simplestParameterizedType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/simplestParameterizedType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/simplestTypeParameterApplication.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/simplestTypeParameterApplication'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/tuples/tuple.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/tuples/tuple'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/unions/numberStringUnion.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAliases/unions/numberStringUnion'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithInterfaceAndConstructor.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithInterfaceAndConstructor'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithMultipleInterfacesAndSuper.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithMultipleInterfacesAndSuper'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithTypeParametersAndStaticMethods.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/classWithTypeParametersAndStaticMethods'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClass'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassNoDefaults.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassNoDefaults'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithAccessors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithAccessors'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithComputedProperty.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithComputedProperty'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithInterface.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithInterface'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethod.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethod'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethodWithDefaultArg.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethodWithDefaultArg'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMultipleInterface.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMultipleInterface'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithParent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithParent'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithStatics.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithStatics'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/thisTypeAnnotation.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/thisTypeAnnotation'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/typeParametersWithInheritance.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/classes/typeParametersWithInheritance'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/arrayPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/arrayPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/boundTypeParameter.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/boundTypeParameter'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/defaultParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/defaultParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/delegatingGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/delegatingGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/functionReturnsPromise.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/functionReturnsPromise'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/multipleParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/multipleParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/multipleTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/multipleTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nestedAsyncFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nestedAsyncFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nestedFunctionWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nestedFunctionWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nextGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/nextGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPatternLastParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPatternLastParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPatternWithDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/objectPatternWithDefault'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/optionalObjectPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/optionalObjectPattern'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/optionalParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/optionalParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/restParams.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/restParams'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/returningGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/returningGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestAsyncFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestAsyncFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithParam'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/functions/simplestGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/modules/simplestExport.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/modules/simplestExport'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/modules/simplestImport.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/modules/simplestImport'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactClassWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactClassWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportComponent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportComponent'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportComponentWithAlias.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportComponentWithAlias'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportPureComponent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactImportPureComponent'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactPureComponent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/reactPureComponent'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/simplestReactClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/react/simplestReactClass'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/tryCatch/simplestTryCatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/tryCatch/simplestTryCatch'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/inlineTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/inlineTypeCast'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/repeatedTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/repeatedTypeCast'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/simplestTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/simplestTypeCast'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/typeCastMemberExpression.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typecasts/typeCastMemberExpression'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/qualifiedTypeOf.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/qualifiedTypeOf'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/simplestTypeOf.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/simplestTypeOf'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/typeQualifiedTypeOf.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/typeOf/typeQualifiedTypeOf'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/constDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/constDeclaration'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclaration'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithAssignment.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithAssignment'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithMultipleAssignments.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithMultipleAssignments'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/patternDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/patternDeclaration'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/varDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/varDeclaration'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/varDeclarationWithAssignment.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeAssertions/variables/varDeclarationWithAssignment'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/awaitAndPromise.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/awaitAndPromise'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithConcreteSuper.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithConcreteSuper'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithSuperTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithSuperTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/classWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/simplestClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/simplestClass'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/simplestClassWithSuper.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/classes/simplestClassWithSuper'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/functions/simplestFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/functions/simplestFunction'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModule.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModule'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleExports.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleExports'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleWithStringName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleWithStringName'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/types/simplestType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/types/simplestType'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/vars/simplestVar.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/vars/simplestVar'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/vars/simplestVarWithAnnotation.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/__fixtures__/typeDeclarations/vars/simplestVarWithAnnotation'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/fixtures.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/fixtures'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/pragmaOptInOnly.test.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/pragmaOptInOnly.test'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/testTransform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/testTransform'>; } declare module 'babel-plugin-flow-runtime/lib/__tests__/transform.test.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/__tests__/transform.test'>; } declare module 'babel-plugin-flow-runtime/lib/annotateVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/annotateVisitors'>; } declare module 'babel-plugin-flow-runtime/lib/attachImport.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/attachImport'>; } declare module 'babel-plugin-flow-runtime/lib/collectProgramOptions.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/collectProgramOptions'>; } declare module 'babel-plugin-flow-runtime/lib/ConversionContext.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/ConversionContext'>; } declare module 'babel-plugin-flow-runtime/lib/convert.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/convert'>; } declare module 'babel-plugin-flow-runtime/lib/createConversionContext.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/createConversionContext'>; } declare module 'babel-plugin-flow-runtime/lib/Entity.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/Entity'>; } declare module 'babel-plugin-flow-runtime/lib/findIdentifiers.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/findIdentifiers'>; } declare module 'babel-plugin-flow-runtime/lib/firstPassVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/firstPassVisitors'>; } declare module 'babel-plugin-flow-runtime/lib/getTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/getTypeParameters'>; } declare module 'babel-plugin-flow-runtime/lib/hasTypeAnnotations.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/hasTypeAnnotations'>; } declare module 'babel-plugin-flow-runtime/lib/index.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/index'>; } declare module 'babel-plugin-flow-runtime/lib/loadFlowConfig.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/loadFlowConfig'>; } declare module 'babel-plugin-flow-runtime/lib/patternMatchVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/patternMatchVisitors'>; } declare module 'babel-plugin-flow-runtime/lib/preTransformVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/preTransformVisitors'>; } declare module 'babel-plugin-flow-runtime/lib/symbols.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/symbols'>; } declare module 'babel-plugin-flow-runtime/lib/transform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/transform'>; } declare module 'babel-plugin-flow-runtime/lib/transformVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/transformVisitors'>; } declare module 'babel-plugin-flow-runtime/lib/typeAnnotationIterator.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/typeAnnotationIterator'>; } declare module 'babel-plugin-flow-runtime/lib/util.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/lib/util'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/100-typed-object-spread.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/100-typed-object-spread'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/123-extend-interface.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/123-extend-interface'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/135-quoted-property-keys.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/135-quoted-property-keys'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/137-support-$Values.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/137-support-$Values'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultArrowFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultArrowFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultClassNoName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultClassNoName'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultFunctionNoName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/14-exportDefaultFunctionNoName'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/140-reexport-flow-type.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/140-reexport-flow-type'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/141-symbol-type.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/141-symbol-type'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/159-quoted-interface-method-names.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/159-quoted-interface-method-names'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/159-quoted-property-names-in-object-literal.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/159-quoted-property-names-in-object-literal'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/24-allow-import-star-react.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/24-allow-import-star-react'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/24-allow-import-star.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/24-allow-import-star'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/28-decorate-with-export-default.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/28-decorate-with-export-default'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/38-intersection-object.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/38-intersection-object'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/46-static-properties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/46-static-properties'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/47-arguments-hoisting.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/47-arguments-hoisting'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/49-invalid-transform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/49-invalid-transform'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/56-indexer-no-identifier.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/56-indexer-no-identifier'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/65-arrow-function-name.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/65-arrow-function-name'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/67-async-destructuring-with-multiple.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/67-async-destructuring-with-multiple'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/67-async-destructuring.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/67-async-destructuring'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/72-generators.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/72-generators'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/77-generator-transform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/77-generator-transform'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/78-support-$Exact.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/78-support-$Exact'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/constTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/constTypeCast'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/generatorFunctions.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/generatorFunctions'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/missingNode.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/missingNode'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/stringPropertyKeys.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/stringPropertyKeys'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/tdzExportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/bugs/tdzExportType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importClashName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importClashName'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntime.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntime'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntimeReify.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntimeReify'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntimeReifyNoDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/importFlowRuntimeReifyNoDefault'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/shorthandImportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/shorthandImportType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/simplestExportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/simplestExportType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/simplestImportType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/importsExports/simplestImportType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/arrayPatternWithRest.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/arrayPatternWithRest'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedMultipleRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedMultipleRestPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestMatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestMatch'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedPositionMultipleRestPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedRestMatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedRestMatch'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/mixedRestPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithClashingArgs.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithClashingArgs'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithClashingVars.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithClashingVars'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithMultipleArgs.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithMultipleArgs'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithUnion.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/patternWithUnion'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleArrayPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleArrayPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleMatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleMatch'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleMatchNoDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleMatchNoDefault'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleObjectPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simpleObjectPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplePattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplePattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplePatternNoDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplePatternNoDefault'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplestRestPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/patternMatching/simplestRestPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaIgnore.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaIgnore'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaOptInStrict.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaOptInStrict'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarn.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarn'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarnAndDecorate.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarnAndDecorate'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarnClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/pragmaWarnClass'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressComment.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressComment'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressCommentClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressCommentClass'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressCommentIfBlock.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressCommentIfBlock'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/pragma/suppressType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/specialForms/classAnnotation.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/specialForms/classAnnotation'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/arrays/arrayOfArrays.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/arrays/arrayOfArrays'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/arrays/numberArray.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/arrays/numberArray'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/builtins/date.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/builtins/date'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/builtins/map.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/builtins/map'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/defaultTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/defaultTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithAnonymousParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithAnonymousParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleOptionalParams.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleOptionalParams'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleParams.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithMultipleParams'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithOptionalParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithOptionalParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithRestParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithRestParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithTrailingRestParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/functionWithTrailingRestParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestBoundTypeParameterizedFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestBoundTypeParameterizedFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestTypeParameterizedFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/simplestTypeParameterizedFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/typeParameterizedFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/functions/typeParameterizedFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/hoistedNestedType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/hoistedNestedType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/hoistedType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/hoistedType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/mutualRecursion.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/mutualRecursion'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleCallProperties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleCallProperties'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleIndexers.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleIndexers'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleProperties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithMultipleProperties'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithOptionalProperties.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithOptionalProperties'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithPropertiesCallPropertiesIndexers.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/objectWithPropertiesCallPropertiesIndexers'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/personObjectWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/personObjectWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestExactObject.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestExactObject'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObject.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObject'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectCallProperty.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectCallProperty'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectIndexer.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectIndexer'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/objects/simplestObjectWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/boolean.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/boolean'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/booleanLiteral.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/booleanLiteral'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/number.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/number'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/numericLiteral.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/numericLiteral'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/string.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/string'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/stringLiteral.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/primitives/stringLiteral'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/selfReferentialType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/selfReferentialType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/simplestParameterizedType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/simplestParameterizedType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/simplestTypeParameterApplication.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/simplestTypeParameterApplication'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/tuples/tuple.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/tuples/tuple'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/unions/numberStringUnion.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAliases/unions/numberStringUnion'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithInterfaceAndConstructor.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithInterfaceAndConstructor'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithMultipleInterfacesAndSuper.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithMultipleInterfacesAndSuper'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithTypeParametersAndStaticMethods.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/classWithTypeParametersAndStaticMethods'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClass'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassNoDefaults.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassNoDefaults'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithAccessors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithAccessors'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithComputedProperty.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithComputedProperty'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithInterface.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithInterface'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethod.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethod'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethodWithDefaultArg.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMethodWithDefaultArg'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMultipleInterface.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithMultipleInterface'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithParent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithParent'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithStatics.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithStatics'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/simplestClassWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/thisTypeAnnotation.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/thisTypeAnnotation'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/typeParametersWithInheritance.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/classes/typeParametersWithInheritance'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/arrayPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/arrayPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/boundTypeParameter.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/boundTypeParameter'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/defaultParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/defaultParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/delegatingGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/delegatingGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/functionReturnsPromise.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/functionReturnsPromise'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/multipleParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/multipleParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/multipleTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/multipleTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nestedAsyncFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nestedAsyncFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nestedFunctionWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nestedFunctionWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nextGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/nextGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPatternLastParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPatternLastParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPatternWithDefault.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/objectPatternWithDefault'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/optionalObjectPattern.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/optionalObjectPattern'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/optionalParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/optionalParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/restParams.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/restParams'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/returningGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/returningGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestAsyncFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestAsyncFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithParam.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithParam'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestFunctionWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestGeneratorFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/functions/simplestGeneratorFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/modules/simplestExport.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/modules/simplestExport'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/modules/simplestImport.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/modules/simplestImport'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactClassWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactClassWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportComponent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportComponent'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportComponentWithAlias.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportComponentWithAlias'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportPureComponent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactImportPureComponent'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactPureComponent.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/reactPureComponent'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/simplestReactClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/react/simplestReactClass'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/tryCatch/simplestTryCatch.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/tryCatch/simplestTryCatch'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/inlineTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/inlineTypeCast'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/repeatedTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/repeatedTypeCast'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/simplestTypeCast.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/simplestTypeCast'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/typeCastMemberExpression.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typecasts/typeCastMemberExpression'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/qualifiedTypeOf.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/qualifiedTypeOf'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/simplestTypeOf.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/simplestTypeOf'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/typeQualifiedTypeOf.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/typeOf/typeQualifiedTypeOf'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/constDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/constDeclaration'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclaration'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithAssignment.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithAssignment'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithMultipleAssignments.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/letDeclarationWithMultipleAssignments'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/patternDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/patternDeclaration'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/varDeclaration.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/varDeclaration'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/varDeclarationWithAssignment.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeAssertions/variables/varDeclarationWithAssignment'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/awaitAndPromise.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/awaitAndPromise'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithConcreteSuper.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithConcreteSuper'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithSuperTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithSuperTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/classWithTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/simplestClass.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/simplestClass'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/simplestClassWithSuper.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/classes/simplestClassWithSuper'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/functions/simplestFunction.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/functions/simplestFunction'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModule.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModule'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleExports.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleExports'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleWithStringName.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/modules/simplestModuleWithStringName'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/types/simplestType.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/types/simplestType'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/vars/simplestVar.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/vars/simplestVar'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/vars/simplestVarWithAnnotation.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/__fixtures__/typeDeclarations/vars/simplestVarWithAnnotation'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/fixtures.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/fixtures'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/pragmaOptInOnly.test.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/pragmaOptInOnly.test'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/testTransform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/testTransform'>; } declare module 'babel-plugin-flow-runtime/src/__tests__/transform.test.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/__tests__/transform.test'>; } declare module 'babel-plugin-flow-runtime/src/annotateVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/annotateVisitors'>; } declare module 'babel-plugin-flow-runtime/src/attachImport.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/attachImport'>; } declare module 'babel-plugin-flow-runtime/src/collectProgramOptions.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/collectProgramOptions'>; } declare module 'babel-plugin-flow-runtime/src/ConversionContext.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/ConversionContext'>; } declare module 'babel-plugin-flow-runtime/src/convert.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/convert'>; } declare module 'babel-plugin-flow-runtime/src/createConversionContext.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/createConversionContext'>; } declare module 'babel-plugin-flow-runtime/src/Entity.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/Entity'>; } declare module 'babel-plugin-flow-runtime/src/findIdentifiers.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/findIdentifiers'>; } declare module 'babel-plugin-flow-runtime/src/firstPassVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/firstPassVisitors'>; } declare module 'babel-plugin-flow-runtime/src/getTypeParameters.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/getTypeParameters'>; } declare module 'babel-plugin-flow-runtime/src/hasTypeAnnotations.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/hasTypeAnnotations'>; } declare module 'babel-plugin-flow-runtime/src/index.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/index'>; } declare module 'babel-plugin-flow-runtime/src/loadFlowConfig.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/loadFlowConfig'>; } declare module 'babel-plugin-flow-runtime/src/patternMatchVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/patternMatchVisitors'>; } declare module 'babel-plugin-flow-runtime/src/preTransformVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/preTransformVisitors'>; } declare module 'babel-plugin-flow-runtime/src/symbols.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/symbols'>; } declare module 'babel-plugin-flow-runtime/src/transform.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/transform'>; } declare module 'babel-plugin-flow-runtime/src/transformVisitors.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/transformVisitors'>; } declare module 'babel-plugin-flow-runtime/src/typeAnnotationIterator.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/typeAnnotationIterator'>; } declare module 'babel-plugin-flow-runtime/src/util.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/src/util'>; } declare module 'babel-plugin-flow-runtime/test-polyfill.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/test-polyfill'>; } declare module 'babel-plugin-flow-runtime/tools/makeFixturesJSON.js' { declare module.exports: $Exports<'babel-plugin-flow-runtime/tools/makeFixturesJSON'>; }
src/components/common/svg-icons/image/crop-din.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCropDin = (props) => ( <SvgIcon {...props}> <path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/> </SvgIcon> ); ImageCropDin = pure(ImageCropDin); ImageCropDin.displayName = 'ImageCropDin'; ImageCropDin.muiName = 'SvgIcon'; export default ImageCropDin;
test/CollapsibleMixinSpec.js
IveWong/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import CollapsibleMixin from '../src/CollapsibleMixin'; import classNames from 'classnames'; describe('CollapsibleMixin', function () { let Component, instance; beforeEach(function(){ Component = React.createClass({ mixins: [CollapsibleMixin], getCollapsibleDOMNode(){ return React.findDOMNode(this.refs.panel); }, getCollapsibleDimensionValue(){ return 15; }, render(){ let styles = this.getCollapsibleClassSet(); return ( <div> <div ref="panel" className={classNames(styles)}> {this.props.children} </div> </div> ); } }); }); afterEach(()=> { if (console.warn.calledWithMatch('CollapsibleMixin is deprecated')){ console.warn.reset(); } }); describe('getInitialState', function(){ it('Should check defaultExpanded', function () { instance = ReactTestUtils.renderIntoDocument( <Component defaultExpanded>Panel content</Component> ); let state = instance.getInitialState(); assert.ok(state.expanded === true); }); it('Should default collapsing to false', function () { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); let state = instance.getInitialState(); assert.ok(state.collapsing === false); }); }); describe('collapsed', function(){ it('Should have collapse class', function () { instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse')); }); }); describe('from collapsed to expanded', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); }); it('Should have collapsing class', function () { instance.setProps({expanded:true}); let node = instance.getCollapsibleDOMNode(); assert.equal(node.className, 'collapsing'); }); it('Should set initial 0px height', function () { let node = instance.getCollapsibleDOMNode(); assert.equal(node.style.height, ''); instance._afterWillUpdate = function(){ assert.equal(node.style.height, '0px'); }; instance.setProps({expanded:true}); }); it('Should set transition to height', function () { let node = instance.getCollapsibleDOMNode(); assert.equal(node.styled, undefined); instance.setProps({expanded:true}); assert.equal(node.style.height, '15px'); }); it('Should transition from collapsing to not collapsing', function (done) { instance._addEndEventListener = function(node, complete){ setTimeout(function(){ complete(); assert.ok(!instance.state.collapsing); done(); }, 100); }; instance.setProps({expanded:true}); assert.ok(instance.state.collapsing); }); it('Should clear height after transition complete', function (done) { let node = instance.getCollapsibleDOMNode(); instance._addEndEventListener = function(nodeInner, complete){ setTimeout(function(){ complete(); assert.equal(nodeInner.style.height, ''); done(); }, 100); }; assert.equal(node.style.height, ''); instance.setProps({expanded:true}); assert.equal(node.style.height, '15px'); }); }); describe('from expanded to collapsed', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component defaultExpanded>Panel content</Component> ); }); it('Should have collapsing class', function () { instance.setProps({expanded:false}); let node = instance.getCollapsibleDOMNode(); assert.equal(node.className, 'collapsing'); }); it('Should set initial height', function () { let node = instance.getCollapsibleDOMNode(); instance._afterWillUpdate = function(){ assert.equal(node.style.height, '15px'); }; assert.equal(node.style.height, ''); instance.setProps({expanded:false}); }); it('Should set transition to height', function () { let node = instance.getCollapsibleDOMNode(); assert.equal(node.style.height, ''); instance.setProps({expanded:false}); assert.equal(node.style.height, '0px'); }); it('Should transition from collapsing to not collapsing', function (done) { instance._addEndEventListener = function(node, complete){ setTimeout(function(){ complete(); assert.ok(!instance.state.collapsing); done(); }, 100); }; instance.setProps({expanded:false}); assert.ok(instance.state.collapsing); }); it('Should have 0px height after transition complete', function (done) { let node = instance.getCollapsibleDOMNode(); instance._addEndEventListener = function(nodeInner, complete){ setTimeout(function(){ complete(); assert.ok(nodeInner.style.height === '0px'); done(); }, 100); }; assert.equal(node.style.height, ''); instance.setProps({expanded:false}); assert.equal(node.style.height, '0px'); }); }); describe('expanded', function(){ it('Should have collapse and in class', function () { instance = ReactTestUtils.renderIntoDocument( <Component expanded={true}>Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse in')); }); it('Should have collapse and in class with defaultExpanded', function () { instance = ReactTestUtils.renderIntoDocument( <Component defaultExpanded>Panel content</Component> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'collapse in')); }); }); describe('dimension', function(){ beforeEach(function(){ instance = ReactTestUtils.renderIntoDocument( <Component>Panel content</Component> ); }); it('Defaults to height', function(){ assert.equal(instance.dimension(), 'height'); }); it('Uses getCollapsibleDimension if exists', function(){ instance.getCollapsibleDimension = function(){ return 'whatevs'; }; assert.equal(instance.dimension(), 'whatevs'); }); }); });
source/client/components/UserLogin.js
achobanov/ReactJS-Fundamentals-lab
import React from 'react'; import UserActions from '../actions/UserActions'; import FormActions from '../actions/FormActions'; import FormStore from '../stores/FormStore'; import Form from './form/Form'; import TextGroup from './form/TextGroup'; import Submit from './form/Submit'; export default class UserLogin extends React.Component { constructor(props) { super(props); this.state = FormStore.getState(); this.onChange = this.onChange.bind(this); } onChange(state) { this.setState(state); } componentDidMount() { FormStore.listen(this.onChange); } componentWillUnmount() { FormStore.unlisten(this.onChange); } handleSubmit(e) { e.preventDefault(); let username = this.state.username; let password = this.state.password; if (!username) { FormActions.usernameValidationFail(); return; } if (!password) { FormActions.passwordValidationFail(); return; } UserActions.loginUser({ username, password }); } render() { return( <Form title="Login" handleSubmit={ this.handleSubmit.bind(this) } submitState={ this.state.formSubmitState } message={ this.state.message }> <TextGroup type="text" value={ this.state.username } label="Username" handleChange={ FormActions.handleUsernameChange } validationState={ this.state.usernameValidationState } /> <TextGroup type="password" value={ this.state.password } label="Password" handleChange={ FormActions.handlePasswordChange } validationState={ this.state.passwordValidationState } /> <Submit type="btn-primary" value="Login" /> </Form> ) } }
packages/icons/src/md/action/Toll.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdToll(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M6 24c0-5.22 3.34-9.65 8-11.3V8.52C7.1 10.3 2 16.55 2 24c0 7.45 5.1 13.7 12 15.48V35.3C9.34 33.65 6 29.22 6 24zM30 8c8.84 0 16 7.16 16 16s-7.16 16-16 16-16-7.16-16-16S21.16 8 30 8zm0 28c6.63 0 12-5.37 12-12s-5.37-12-12-12-12 5.37-12 12 5.37 12 12 12z" /> </IconBase> ); } export default MdToll;
clients/packages/admin-client/src/community/components/dns/dns-preview/subdomain-preview.js
nossas/bonde-client
import PropTypes from 'prop-types' import React from 'react' const SubdomainPreview = ({ subdomain, menuComponent: MenuComponent, checked }) => ( <div className='table-row'> <div className='wrapper'> <div className='text' style={{ width: 30 }}> <span className={`circle${checked ? ' checked' : ''}`}> {checked ? <i className='fa fa-check' /> : <i className='fa fa-close' />} </span> </div> </div> <div className='wrapper' style={{ flex: 1 }}> <div className='text'> {subdomain.name.replace('\\052', '*')} </div> </div> <div className='wrapper' style={{ width: 100, padding: '0 20px', textAlign: 'center' }}> <div className='text'> {subdomain.record_type} </div> </div> <div className='wrapper' style={{ flex: 1 }}> <div className='text'> <div className={`body ${subdomain.record_type.toLowerCase()}`}> {subdomain.record_type === 'NS' || subdomain.record_type === 'MX' ? ( <ul> {subdomain.value.split('\n').map((ns, index) => ( <li key={`ns-${index}`} style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }} > {ns} </li> ))} </ul> ) : ( <p style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}> {subdomain.value} </p> )} </div> </div> </div> <div className='wrapper' style={{ width: 60 }}> <div className='text'> {MenuComponent && ( <div className='menu--preview'> {MenuComponent} </div> )} </div> </div> </div> ) SubdomainPreview.propTypes = { subdomain: PropTypes.object, checked: PropTypes.bool, menuComponent: PropTypes.element } SubdomainPreview.defaultProps = { checked: true } export default SubdomainPreview
app/javascript/mastodon/components/autosuggest_input.js
yukimochi/mastodon
import React from 'react'; import AutosuggestAccountContainer from '../features/compose/containers/autosuggest_account_container'; import AutosuggestEmoji from './autosuggest_emoji'; import AutosuggestHashtag from './autosuggest_hashtag'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import ImmutablePureComponent from 'react-immutable-pure-component'; import classNames from 'classnames'; const textAtCursorMatchesToken = (str, caretPosition, searchTokens) => { let word; let left = str.slice(0, caretPosition).search(/\S+$/); let right = str.slice(caretPosition).search(/\s/); if (right < 0) { word = str.slice(left); } else { word = str.slice(left, right + caretPosition); } if (!word || word.trim().length < 3 || searchTokens.indexOf(word[0]) === -1) { return [null, null]; } word = word.trim().toLowerCase(); if (word.length > 0) { return [left + 1, word]; } else { return [null, null]; } }; export default class AutosuggestInput extends ImmutablePureComponent { static propTypes = { value: PropTypes.string, suggestions: ImmutablePropTypes.list, disabled: PropTypes.bool, placeholder: PropTypes.string, onSuggestionSelected: PropTypes.func.isRequired, onSuggestionsClearRequested: PropTypes.func.isRequired, onSuggestionsFetchRequested: PropTypes.func.isRequired, onChange: PropTypes.func.isRequired, onKeyUp: PropTypes.func, onKeyDown: PropTypes.func, autoFocus: PropTypes.bool, className: PropTypes.string, id: PropTypes.string, searchTokens: PropTypes.arrayOf(PropTypes.string), maxLength: PropTypes.number, }; static defaultProps = { autoFocus: true, searchTokens: ['@', ':', '#'], }; state = { suggestionsHidden: true, focused: false, selectedSuggestion: 0, lastToken: null, tokenStart: 0, }; onChange = (e) => { const [ tokenStart, token ] = textAtCursorMatchesToken(e.target.value, e.target.selectionStart, this.props.searchTokens); if (token !== null && this.state.lastToken !== token) { this.setState({ lastToken: token, selectedSuggestion: 0, tokenStart }); this.props.onSuggestionsFetchRequested(token); } else if (token === null) { this.setState({ lastToken: null }); this.props.onSuggestionsClearRequested(); } this.props.onChange(e); } onKeyDown = (e) => { const { suggestions, disabled } = this.props; const { selectedSuggestion, suggestionsHidden } = this.state; if (disabled) { e.preventDefault(); return; } if (e.which === 229 || e.isComposing) { // Ignore key events during text composition // e.key may be a name of the physical key even in this case (e.x. Safari / Chrome on Mac) return; } switch(e.key) { case 'Escape': if (suggestions.size === 0 || suggestionsHidden) { document.querySelector('.ui').parentElement.focus(); } else { e.preventDefault(); this.setState({ suggestionsHidden: true }); } break; case 'ArrowDown': if (suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); this.setState({ selectedSuggestion: Math.min(selectedSuggestion + 1, suggestions.size - 1) }); } break; case 'ArrowUp': if (suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); this.setState({ selectedSuggestion: Math.max(selectedSuggestion - 1, 0) }); } break; case 'Enter': case 'Tab': // Select suggestion if (this.state.lastToken !== null && suggestions.size > 0 && !suggestionsHidden) { e.preventDefault(); e.stopPropagation(); this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestions.get(selectedSuggestion)); } break; } if (e.defaultPrevented || !this.props.onKeyDown) { return; } this.props.onKeyDown(e); } onBlur = () => { this.setState({ suggestionsHidden: true, focused: false }); } onFocus = () => { this.setState({ focused: true }); } onSuggestionClick = (e) => { const suggestion = this.props.suggestions.get(e.currentTarget.getAttribute('data-index')); e.preventDefault(); this.props.onSuggestionSelected(this.state.tokenStart, this.state.lastToken, suggestion); this.input.focus(); } componentWillReceiveProps (nextProps) { if (nextProps.suggestions !== this.props.suggestions && nextProps.suggestions.size > 0 && this.state.suggestionsHidden && this.state.focused) { this.setState({ suggestionsHidden: false }); } } setInput = (c) => { this.input = c; } renderSuggestion = (suggestion, i) => { const { selectedSuggestion } = this.state; let inner, key; if (suggestion.type === 'emoji') { inner = <AutosuggestEmoji emoji={suggestion} />; key = suggestion.id; } else if (suggestion.type ==='hashtag') { inner = <AutosuggestHashtag tag={suggestion} />; key = suggestion.name; } else if (suggestion.type === 'account') { inner = <AutosuggestAccountContainer id={suggestion.id} />; key = suggestion.id; } return ( <div role='button' tabIndex='0' key={key} data-index={i} className={classNames('autosuggest-textarea__suggestions__item', { selected: i === selectedSuggestion })} onMouseDown={this.onSuggestionClick}> {inner} </div> ); } render () { const { value, suggestions, disabled, placeholder, onKeyUp, autoFocus, className, id, maxLength } = this.props; const { suggestionsHidden } = this.state; return ( <div className='autosuggest-input'> <label> <span style={{ display: 'none' }}>{placeholder}</span> <input type='text' ref={this.setInput} disabled={disabled} placeholder={placeholder} autoFocus={autoFocus} value={value} onChange={this.onChange} onKeyDown={this.onKeyDown} onKeyUp={onKeyUp} onFocus={this.onFocus} onBlur={this.onBlur} dir='auto' aria-autocomplete='list' id={id} className={className} maxLength={maxLength} /> </label> <div className={`autosuggest-textarea__suggestions ${suggestionsHidden || suggestions.isEmpty() ? '' : 'autosuggest-textarea__suggestions--visible'}`}> {suggestions.map(this.renderSuggestion)} </div> </div> ); } }
index.android.js
githubhaohao/DevNews
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Navigator, BackAndroid, ToastAndroid, StatusBar, } from 'react-native'; import Home from './components/Home.js'; import News from './components/News.js'; import NewsDetail from './components/NewsDetail.js'; var navigator,lastBackPress; export default class DevNews extends Component { render() { let initialRoute = {name:'home'}; return ( <View style={styles.container}> <StatusBar backgroundColor='transparent' translucent/> <Navigator style={styles.container} initialRoute={initialRoute} configureScene={() => Navigator.SceneConfigs.FadeAndroid} renderScene={(route, navigationOperations, onComponentRef) => this.routeMapper(route, navigationOperations, onComponentRef)} > </Navigator> </View> ); } componentWillMount() { BackAndroid.addEventListener('hardwareBackPress', this.backListener.bind(this)); } backListener(){ if (navigator && navigator.getCurrentRoutes().length > 1) { navigator.pop(); return true; } else if (lastBackPress && lastBackPress + 2000 > Date.now()) { return false; } else { lastBackPress = Date.now(); ToastAndroid.show('在按一次退出DevNews',ToastAndroid.SHORT); return true; } } componentWillUnMount() { BackAndroid.addEventListener('hardwareBackPress', this.backListener.bind(this)); } routeMapper(route, navigationOperations, onComponentRef){ navigator = navigationOperations; if(route.name == 'home'){ return ( <Home navigator={navigationOperations}/> ) } else if (route.name == 'news') { return ( <News navigator={navigationOperations} news={route.news}/> ) } else if (route.name == 'detail') { return ( <NewsDetail navigator={navigationOperations} url={route.url} title={route.title} /> ); } //} else if (route.name == 'favorite') { // return ( // <FavoriteStoryView navigator={navigationOperations}/> // ) //} } } const styles = StyleSheet.create({ container: { flex: 1, }, }); AppRegistry.registerComponent('DevNews', () => DevNews);
lib/components/chrome/ChromePointerCircle.js
shaunstanislaus/react-color
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = require('react'); var ReactCSS = require('reactcss'); var ChromePointerCircle = (function (_ReactCSS$Component) { _inherits(ChromePointerCircle, _ReactCSS$Component); function ChromePointerCircle() { _classCallCheck(this, ChromePointerCircle); _get(Object.getPrototypeOf(ChromePointerCircle.prototype), 'constructor', this).apply(this, arguments); } _createClass(ChromePointerCircle, [{ key: 'classes', value: function classes() { return { 'default': { picker: { width: '12px', height: '12px', borderRadius: '6px', boxShadow: 'inset 0 0 0 1px #fff', transform: 'translate(-6px, -6px)' } } }; } }, { key: 'render', value: function render() { return React.createElement('div', { style: this.styles().picker }); } }]); return ChromePointerCircle; })(ReactCSS.Component); module.exports = ChromePointerCircle;
ajax/libs/react-router/0.9.4/react-router.js
ematsusaka/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Actions that modify the URL. */ var LocationActions = { /** * Indicates a new location is being pushed to the history stack. */ PUSH: 'push', /** * Indicates the current location should be replaced. */ REPLACE: 'replace', /** * Indicates the most recent entry should be removed from the history stack. */ POP: 'pop' }; module.exports = LocationActions; },{}],2:[function(_dereq_,module,exports){ var LocationActions = _dereq_('../actions/LocationActions'); /** * A scroll behavior that attempts to imitate the default behavior * of modern browsers. */ var ImitateBrowserBehavior = { updateScrollPosition: function (position, actionType) { switch (actionType) { case LocationActions.PUSH: case LocationActions.REPLACE: window.scrollTo(0, 0); break; case LocationActions.POP: if (position) { window.scrollTo(position.x, position.y); } else { window.scrollTo(0, 0); } break; } } }; module.exports = ImitateBrowserBehavior; },{"../actions/LocationActions":1}],3:[function(_dereq_,module,exports){ /** * A scroll behavior that always scrolls to the top of the page * after a transition. */ var ScrollToTopBehavior = { updateScrollPosition: function () { window.scrollTo(0, 0); } }; module.exports = ScrollToTopBehavior; },{}],4:[function(_dereq_,module,exports){ var merge = _dereq_('react/lib/merge'); var Route = _dereq_('./Route'); /** * A <DefaultRoute> component is a special kind of <Route> that * renders when its parent matches but none of its siblings do. * Only one such route may be used at any given level in the * route hierarchy. */ function DefaultRoute(props) { return Route( merge(props, { path: null, isDefault: true }) ); } module.exports = DefaultRoute; },{"./Route":8,"react/lib/merge":71}],5:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var classSet = _dereq_('react/lib/cx'); var merge = _dereq_('react/lib/merge'); var ActiveState = _dereq_('../mixins/ActiveState'); var Navigation = _dereq_('../mixins/Navigation'); function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * <Link> components are used to create an <a> element that links to a route. * When that route is active, the link gets an "active" class name (or the * value of its `activeClassName` prop). * * For example, assuming you have the following route: * * <Route name="showPost" path="/posts/:postID" handler={Post}/> * * You could use the following component to link to that route: * * <Link to="showPost" params={{ postID: "123" }} /> * * In addition to params, links may pass along query string parameters * using the `query` prop. * * <Link to="showPost" params={{ postID: "123" }} query={{ show:true }}/> */ var Link = React.createClass({ displayName: 'Link', mixins: [ ActiveState, Navigation ], propTypes: { activeClassName: React.PropTypes.string.isRequired, to: React.PropTypes.string.isRequired, params: React.PropTypes.object, query: React.PropTypes.object, onClick: React.PropTypes.func }, getDefaultProps: function () { return { activeClassName: 'active' }; }, handleClick: function (event) { var allowTransition = true; var clickResult; if (this.props.onClick) clickResult = this.props.onClick(event); if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; if (clickResult === false || event.defaultPrevented === true) allowTransition = false; event.preventDefault(); if (allowTransition) this.transitionTo(this.props.to, this.props.params, this.props.query); }, /** * Returns the value of the "href" attribute to use on the DOM element. */ getHref: function () { return this.makeHref(this.props.to, this.props.params, this.props.query); }, /** * Returns the value of the "class" attribute to use on the DOM element, which contains * the value of the activeClassName property when this <Link> is active. */ getClassName: function () { var classNames = {}; if (this.props.className) classNames[this.props.className] = true; if (this.isActive(this.props.to, this.props.params, this.props.query)) classNames[this.props.activeClassName] = true; return classSet(classNames); }, render: function () { var props = merge(this.props, { href: this.getHref(), className: this.getClassName(), onClick: this.handleClick }); return React.DOM.a(props, this.props.children); } }); module.exports = Link; },{"../mixins/ActiveState":15,"../mixins/Navigation":18,"react/lib/cx":61,"react/lib/merge":71}],6:[function(_dereq_,module,exports){ var merge = _dereq_('react/lib/merge'); var Route = _dereq_('./Route'); /** * A <NotFoundRoute> is a special kind of <Route> that * renders when the beginning of its parent's path matches * but none of its siblings do, including any <DefaultRoute>. * Only one such route may be used at any given level in the * route hierarchy. */ function NotFoundRoute(props) { return Route( merge(props, { path: null, catchAll: true }) ); } module.exports = NotFoundRoute; },{"./Route":8,"react/lib/merge":71}],7:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var Route = _dereq_('./Route'); function createRedirectHandler(to, _params, _query) { return React.createClass({ statics: { willTransitionTo: function (transition, params, query) { transition.redirect(to, _params || params, _query || query); } }, render: function () { return null; } }); } /** * A <Redirect> component is a special kind of <Route> that always * redirects to another route when it matches. */ function Redirect(props) { return Route({ name: props.name, path: props.from || props.path || '*', handler: createRedirectHandler(props.to, props.params, props.query) }); } module.exports = Redirect; },{"./Route":8}],8:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var withoutProperties = _dereq_('../utils/withoutProperties'); /** * A map of <Route> component props that are reserved for use by the * router and/or React. All other props are considered "static" and * are passed through to the route handler. */ var RESERVED_PROPS = { handler: true, path: true, defaultRoute: true, notFoundRoute: true, paramNames: true, children: true // ReactChildren }; /** * <Route> components specify components that are rendered to the page when the * URL matches a given pattern. * * Routes are arranged in a nested tree structure. When a new URL is requested, * the tree is searched depth-first to find a route whose path matches the URL. * When one is found, all routes in the tree that lead to it are considered * "active" and their components are rendered into the DOM, nested in the same * order as they are in the tree. * * The preferred way to configure a router is using JSX. The XML-like syntax is * a great way to visualize how routes are laid out in an application. * * React.renderComponent(( * <Routes handler={App}> * <Route name="login" handler={Login}/> * <Route name="logout" handler={Logout}/> * <Route name="about" handler={About}/> * </Routes> * ), document.body); * * If you don't use JSX, you can also assemble a Router programmatically using * the standard React component JavaScript API. * * React.renderComponent(( * Routes({ handler: App }, * Route({ name: 'login', handler: Login }), * Route({ name: 'logout', handler: Logout }), * Route({ name: 'about', handler: About }) * ) * ), document.body); * * Handlers for Route components that contain children can render their active * child route using the activeRouteHandler prop. * * var App = React.createClass({ * render: function () { * return ( * <div class="application"> * {this.props.activeRouteHandler()} * </div> * ); * } * }); */ var Route = React.createClass({ displayName: 'Route', statics: { getUnreservedProps: function (props) { return withoutProperties(props, RESERVED_PROPS); } }, propTypes: { handler: React.PropTypes.any.isRequired, path: React.PropTypes.string, name: React.PropTypes.string }, render: function () { throw new Error( 'The <Route> component should not be rendered directly. You may be ' + 'missing a <Routes> wrapper around your list of routes.' ); } }); module.exports = Route; },{"../utils/withoutProperties":30}],9:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var warning = _dereq_('react/lib/warning'); var invariant = _dereq_('react/lib/invariant'); var copyProperties = _dereq_('react/lib/copyProperties'); var HashLocation = _dereq_('../locations/HashLocation'); var ActiveContext = _dereq_('../mixins/ActiveContext'); var LocationContext = _dereq_('../mixins/LocationContext'); var RouteContext = _dereq_('../mixins/RouteContext'); var ScrollContext = _dereq_('../mixins/ScrollContext'); var reversedArray = _dereq_('../utils/reversedArray'); var Transition = _dereq_('../utils/Transition'); var Redirect = _dereq_('../utils/Redirect'); var Path = _dereq_('../utils/Path'); var Route = _dereq_('./Route'); function makeMatch(route, params) { return { route: route, params: params }; } function getRootMatch(matches) { return matches[matches.length - 1]; } function findMatches(path, routes, defaultRoute, notFoundRoute) { var matches = null, route, params; for (var i = 0, len = routes.length; i < len; ++i) { route = routes[i]; // Check the subtree first to find the most deeply-nested match. matches = findMatches(path, route.props.children, route.props.defaultRoute, route.props.notFoundRoute); if (matches != null) { var rootParams = getRootMatch(matches).params; params = route.props.paramNames.reduce(function (params, paramName) { params[paramName] = rootParams[paramName]; return params; }, {}); matches.unshift(makeMatch(route, params)); return matches; } // No routes in the subtree matched, so check this route. params = Path.extractParams(route.props.path, path); if (params) return [ makeMatch(route, params) ]; } // No routes matched, so try the default route if there is one. if (defaultRoute && (params = Path.extractParams(defaultRoute.props.path, path))) return [ makeMatch(defaultRoute, params) ]; // Last attempt: does the "not found" route match? if (notFoundRoute && (params = Path.extractParams(notFoundRoute.props.path, path))) return [ makeMatch(notFoundRoute, params) ]; return matches; } function hasMatch(matches, match) { return matches.some(function (m) { if (m.route !== match.route) return false; for (var property in m.params) if (m.params[property] !== match.params[property]) return false; return true; }); } /** * Calls the willTransitionFrom hook of all handlers in the given matches * serially in reverse with the transition object and the current instance of * the route's handler, so that the deepest nested handlers are called first. * Calls callback(error) when finished. */ function runTransitionFromHooks(matches, transition, callback) { var hooks = reversedArray(matches).map(function (match) { return function () { var handler = match.route.props.handler; if (!transition.isAborted && handler.willTransitionFrom) return handler.willTransitionFrom(transition, match.component); var promise = transition.promise; delete transition.promise; return promise; }; }); runHooks(hooks, callback); } /** * Calls the willTransitionTo hook of all handlers in the given matches * serially with the transition object and any params that apply to that * handler. Calls callback(error) when finished. */ function runTransitionToHooks(matches, transition, query, callback) { var hooks = matches.map(function (match) { return function () { var handler = match.route.props.handler; if (!transition.isAborted && handler.willTransitionTo) handler.willTransitionTo(transition, match.params, query); var promise = transition.promise; delete transition.promise; return promise; }; }); runHooks(hooks, callback); } /** * Runs all hook functions serially and calls callback(error) when finished. * A hook may return a promise if it needs to execute asynchronously. */ function runHooks(hooks, callback) { try { var promise = hooks.reduce(function (promise, hook) { // The first hook to use transition.wait makes the rest // of the transition async from that point forward. return promise ? promise.then(hook) : hook(); }, null); } catch (error) { return callback(error); // Sync error. } if (promise) { // Use setTimeout to break the promise chain. promise.then(function () { setTimeout(callback); }, function (error) { setTimeout(function () { callback(error); }); }); } else { callback(); } } function updateMatchComponents(matches, refs) { var match; for (var i = 0, len = matches.length; i < len; ++i) { match = matches[i]; match.component = refs.__activeRoute__; if (match.component == null) break; // End of the tree. refs = match.component.refs; } } function returnNull() { return null; } function routeIsActive(activeRoutes, routeName) { return activeRoutes.some(function (route) { return route.props.name === routeName; }); } function paramsAreActive(activeParams, params) { for (var property in params) if (String(activeParams[property]) !== String(params[property])) return false; return true; } function queryIsActive(activeQuery, query) { for (var property in query) if (String(activeQuery[property]) !== String(query[property])) return false; return true; } function defaultTransitionErrorHandler(error) { // Throw so we don't silently swallow async errors. throw error; // This error probably originated in a transition hook. } /** * The <Routes> component configures the route hierarchy and renders the * route matching the current location when rendered into a document. * * See the <Route> component for more details. */ var Routes = React.createClass({ displayName: 'Routes', mixins: [ RouteContext, ActiveContext, LocationContext, ScrollContext ], propTypes: { initialPath: React.PropTypes.string, initialMatches: React.PropTypes.array, onChange: React.PropTypes.func, onError: React.PropTypes.func.isRequired }, getDefaultProps: function () { return { initialPath: null, initialMatches: [], onError: defaultTransitionErrorHandler }; }, getInitialState: function () { return { path: this.props.initialPath, matches: this.props.initialMatches }; }, componentDidMount: function () { warning( this._owner == null, '<Routes> should be rendered directly using React.renderComponent, not ' + 'inside some other component\'s render method' ); if (this._handleStateChange) { this._handleStateChange(); delete this._handleStateChange; } }, componentDidUpdate: function () { if (this._handleStateChange) { this._handleStateChange(); delete this._handleStateChange; } }, /** * Performs a depth-first search for the first route in the tree that matches on * the given path. Returns an array of all routes in the tree leading to the one * that matched in the format { route, params } where params is an object that * contains the URL parameters relevant to that route. Returns null if no route * in the tree matches the path. * * React.renderComponent( * <Routes> * <Route handler={App}> * <Route name="posts" handler={Posts}/> * <Route name="post" path="/posts/:id" handler={Post}/> * </Route> * </Routes> * ).match('/posts/123'); => [ { route: <AppRoute>, params: {} }, * { route: <PostRoute>, params: { id: '123' } } ] */ match: function (path) { var routes = this.getRoutes(); return findMatches(Path.withoutQuery(path), routes, this.props.defaultRoute, this.props.notFoundRoute); }, updateLocation: function (path, actionType) { if (this.state.path === path) return; // Nothing to do! if (this.state.path) this.recordScroll(this.state.path); this.dispatch(path, function (error, abortReason, nextState) { if (error) { this.props.onError.call(this, error); } else if (abortReason instanceof Redirect) { this.replaceWith(abortReason.to, abortReason.params, abortReason.query); } else if (abortReason) { this.goBack(); } else { this._handleStateChange = this.handleStateChange.bind(this, path, actionType); this.setState(nextState); } }); }, handleStateChange: function (path, actionType) { updateMatchComponents(this.state.matches, this.refs); this.updateScroll(path, actionType); if (this.props.onChange) this.props.onChange.call(this); }, /** * Performs a transition to the given path and calls callback(error, abortReason, nextState) * when the transition is finished. If there was an error, the first argument will not be null. * Otherwise, if the transition was aborted for some reason, it will be given in the second arg. * * In a transition, the router first determines which routes are involved by beginning with the * current route, up the route tree to the first parent route that is shared with the destination * route, and back down the tree to the destination route. The willTransitionFrom hook is invoked * on all route handlers we're transitioning away from, in reverse nesting order. Likewise, the * willTransitionTo hook is invoked on all route handlers we're transitioning to. * * Both willTransitionFrom and willTransitionTo hooks may either abort or redirect the transition. * To resolve asynchronously, they may use transition.wait(promise). If no hooks wait, the * transition will be synchronous. */ dispatch: function (path, callback) { var transition = new Transition(this, path); var currentMatches = this.state ? this.state.matches : []; // No state server-side. var nextMatches = this.match(path) || []; warning( nextMatches.length, 'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your <Routes>', path, path ); var fromMatches, toMatches; if (currentMatches.length) { fromMatches = currentMatches.filter(function (match) { return !hasMatch(nextMatches, match); }); toMatches = nextMatches.filter(function (match) { return !hasMatch(currentMatches, match); }); } else { fromMatches = []; toMatches = nextMatches; } var callbackScope = this; var query = Path.extractQuery(path) || {}; runTransitionFromHooks(fromMatches, transition, function (error) { if (error || transition.isAborted) return callback.call(callbackScope, error, transition.abortReason); runTransitionToHooks(toMatches, transition, query, function (error) { if (error || transition.isAborted) return callback.call(callbackScope, error, transition.abortReason); var matches = currentMatches.slice(0, currentMatches.length - fromMatches.length).concat(toMatches); var rootMatch = getRootMatch(matches); var params = (rootMatch && rootMatch.params) || {}; var routes = matches.map(function (match) { return match.route; }); callback.call(callbackScope, null, null, { path: path, matches: matches, activeRoutes: routes, activeParams: params, activeQuery: query }); }); }); }, /** * Returns the props that should be used for the top-level route handler. */ getHandlerProps: function () { var matches = this.state.matches; var query = this.state.activeQuery; var handler = returnNull; var props = { ref: null, params: null, query: null, activeRouteHandler: handler, key: null }; reversedArray(matches).forEach(function (match) { var route = match.route; props = Route.getUnreservedProps(route.props); props.ref = '__activeRoute__'; props.params = match.params; props.query = query; props.activeRouteHandler = handler; // TODO: Can we remove addHandlerKey? if (route.props.addHandlerKey) props.key = Path.injectParams(route.props.path, match.params); handler = function (props, addedProps) { if (arguments.length > 2 && typeof arguments[2] !== 'undefined') throw new Error('Passing children to a route handler is not supported'); return route.props.handler( copyProperties(props, addedProps) ); }.bind(this, props); }); return props; }, /** * Returns a reference to the active route handler's component instance. */ getActiveComponent: function () { return this.refs.__activeRoute__; }, /** * Returns the current URL path. */ getCurrentPath: function () { return this.state.path; }, /** * Returns an absolute URL path created from the given route * name, URL parameters, and query values. */ makePath: function (to, params, query) { var path; if (Path.isAbsolute(to)) { path = Path.normalize(to); } else { var namedRoutes = this.getNamedRoutes(); var route = namedRoutes[to]; invariant( route, 'Unable to find a route named "%s". Make sure you have <Route name="%s"> somewhere in your <Routes>', to, to ); path = route.props.path; } return Path.withQuery(Path.injectParams(path, params), query); }, /** * Returns a string that may safely be used as the href of a * link to the route with the given name. */ makeHref: function (to, params, query) { var path = this.makePath(to, params, query); if (this.getLocation() === HashLocation) return '#' + path; return path; }, /** * Transitions to the URL specified in the arguments by pushing * a new URL onto the history stack. */ transitionTo: function (to, params, query) { var location = this.getLocation(); invariant( location, 'You cannot use transitionTo without a location' ); location.push(this.makePath(to, params, query)); }, /** * Transitions to the URL specified in the arguments by replacing * the current URL in the history stack. */ replaceWith: function (to, params, query) { var location = this.getLocation(); invariant( location, 'You cannot use replaceWith without a location' ); location.replace(this.makePath(to, params, query)); }, /** * Transitions to the previous URL. */ goBack: function () { var location = this.getLocation(); invariant( location, 'You cannot use goBack without a location' ); location.pop(); }, /** * Returns true if the given route, params, and query are active. */ isActive: function (to, params, query) { if (Path.isAbsolute(to)) return to === this.getCurrentPath(); return routeIsActive(this.getActiveRoutes(), to) && paramsAreActive(this.getActiveParams(), params) && (query == null || queryIsActive(this.getActiveQuery(), query)); }, render: function () { var match = this.state.matches[0]; if (match == null) return null; return match.route.props.handler( this.getHandlerProps() ); }, childContextTypes: { currentPath: React.PropTypes.string, makePath: React.PropTypes.func.isRequired, makeHref: React.PropTypes.func.isRequired, transitionTo: React.PropTypes.func.isRequired, replaceWith: React.PropTypes.func.isRequired, goBack: React.PropTypes.func.isRequired, isActive: React.PropTypes.func.isRequired }, getChildContext: function () { return { currentPath: this.getCurrentPath(), makePath: this.makePath, makeHref: this.makeHref, transitionTo: this.transitionTo, replaceWith: this.replaceWith, goBack: this.goBack, isActive: this.isActive }; } }); module.exports = Routes; },{"../locations/HashLocation":11,"../mixins/ActiveContext":14,"../mixins/LocationContext":17,"../mixins/RouteContext":19,"../mixins/ScrollContext":20,"../utils/Path":22,"../utils/Redirect":24,"../utils/Transition":26,"../utils/reversedArray":28,"./Route":8,"react/lib/copyProperties":60,"react/lib/invariant":66,"react/lib/warning":76}],10:[function(_dereq_,module,exports){ exports.DefaultRoute = _dereq_('./components/DefaultRoute'); exports.Link = _dereq_('./components/Link'); exports.NotFoundRoute = _dereq_('./components/NotFoundRoute'); exports.Redirect = _dereq_('./components/Redirect'); exports.Route = _dereq_('./components/Route'); exports.Routes = _dereq_('./components/Routes'); exports.ActiveState = _dereq_('./mixins/ActiveState'); exports.CurrentPath = _dereq_('./mixins/CurrentPath'); exports.Navigation = _dereq_('./mixins/Navigation'); exports.renderRoutesToString = _dereq_('./utils/ServerRendering').renderRoutesToString; exports.renderRoutesToStaticMarkup = _dereq_('./utils/ServerRendering').renderRoutesToStaticMarkup; },{"./components/DefaultRoute":4,"./components/Link":5,"./components/NotFoundRoute":6,"./components/Redirect":7,"./components/Route":8,"./components/Routes":9,"./mixins/ActiveState":15,"./mixins/CurrentPath":16,"./mixins/Navigation":18,"./utils/ServerRendering":25}],11:[function(_dereq_,module,exports){ var LocationActions = _dereq_('../actions/LocationActions'); var getWindowPath = _dereq_('../utils/getWindowPath'); function getHashPath() { return window.location.hash.substr(1); } var _actionType; function ensureSlash() { var path = getHashPath(); if (path.charAt(0) === '/') return true; HashLocation.replace('/' + path); return false; } var _onChange; function onHashChange() { if (ensureSlash()) { var path = getHashPath(); _onChange({ // If we don't have an _actionType then all we know is the hash // changed. It was probably caused by the user clicking the Back // button, but may have also been the Forward button or manual // manipulation. So just guess 'pop'. type: _actionType || LocationActions.POP, path: getHashPath() }); _actionType = null; } } /** * A Location that uses `window.location.hash`. */ var HashLocation = { setup: function (onChange) { _onChange = onChange; // Do this BEFORE listening for hashchange. ensureSlash(); if (window.addEventListener) { window.addEventListener('hashchange', onHashChange, false); } else { window.attachEvent('onhashchange', onHashChange); } }, teardown: function () { if (window.removeEventListener) { window.removeEventListener('hashchange', onHashChange, false); } else { window.detachEvent('onhashchange', onHashChange); } }, push: function (path) { _actionType = LocationActions.PUSH; window.location.hash = path; }, replace: function (path) { _actionType = LocationActions.REPLACE; window.location.replace(getWindowPath() + '#' + path); }, pop: function () { _actionType = LocationActions.POP; window.history.back(); }, getCurrentPath: getHashPath, toString: function () { return '<HashLocation>'; } }; module.exports = HashLocation; },{"../actions/LocationActions":1,"../utils/getWindowPath":27}],12:[function(_dereq_,module,exports){ var LocationActions = _dereq_('../actions/LocationActions'); var getWindowPath = _dereq_('../utils/getWindowPath'); var _onChange; function onPopState() { _onChange({ type: LocationActions.POP, path: getWindowPath() }); } /** * A Location that uses HTML5 history. */ var HistoryLocation = { setup: function (onChange) { _onChange = onChange; if (window.addEventListener) { window.addEventListener('popstate', onPopState, false); } else { window.attachEvent('popstate', onPopState); } }, teardown: function () { if (window.removeEventListener) { window.removeEventListener('popstate', onPopState, false); } else { window.detachEvent('popstate', onPopState); } }, push: function (path) { window.history.pushState({ path: path }, '', path); _onChange({ type: LocationActions.PUSH, path: getWindowPath() }); }, replace: function (path) { window.history.replaceState({ path: path }, '', path); _onChange({ type: LocationActions.REPLACE, path: getWindowPath() }); }, pop: function () { window.history.back(); }, getCurrentPath: getWindowPath, toString: function () { return '<HistoryLocation>'; } }; module.exports = HistoryLocation; },{"../actions/LocationActions":1,"../utils/getWindowPath":27}],13:[function(_dereq_,module,exports){ var getWindowPath = _dereq_('../utils/getWindowPath'); /** * A Location that uses full page refreshes. This is used as * the fallback for HistoryLocation in browsers that do not * support the HTML5 history API. */ var RefreshLocation = { push: function (path) { window.location = path; }, replace: function (path) { window.location.replace(path); }, pop: function () { window.history.back(); }, getCurrentPath: getWindowPath, toString: function () { return '<RefreshLocation>'; } }; module.exports = RefreshLocation; },{"../utils/getWindowPath":27}],14:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var copyProperties = _dereq_('react/lib/copyProperties'); /** * A mixin for components that store the active state of routes, * URL parameters, and query. */ var ActiveContext = { propTypes: { initialActiveRoutes: React.PropTypes.array.isRequired, initialActiveParams: React.PropTypes.object.isRequired, initialActiveQuery: React.PropTypes.object.isRequired }, getDefaultProps: function () { return { initialActiveRoutes: [], initialActiveParams: {}, initialActiveQuery: {} }; }, getInitialState: function () { return { activeRoutes: this.props.initialActiveRoutes, activeParams: this.props.initialActiveParams, activeQuery: this.props.initialActiveQuery }; }, /** * Returns a read-only array of the currently active routes. */ getActiveRoutes: function () { return this.state.activeRoutes.slice(0); }, /** * Returns a read-only object of the currently active URL parameters. */ getActiveParams: function () { return copyProperties({}, this.state.activeParams); }, /** * Returns a read-only object of the currently active query parameters. */ getActiveQuery: function () { return copyProperties({}, this.state.activeQuery); }, childContextTypes: { activeRoutes: React.PropTypes.array.isRequired, activeParams: React.PropTypes.object.isRequired, activeQuery: React.PropTypes.object.isRequired }, getChildContext: function () { return { activeRoutes: this.getActiveRoutes(), activeParams: this.getActiveParams(), activeQuery: this.getActiveQuery() }; } }; module.exports = ActiveContext; },{"react/lib/copyProperties":60}],15:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); /** * A mixin for components that need to know the routes, URL * params and query that are currently active. * * Example: * * var AboutLink = React.createClass({ * mixins: [ Router.ActiveState ], * render: function () { * var className = this.props.className; * * if (this.isActive('about')) * className += ' is-active'; * * return React.DOM.a({ className: className }, this.props.children); * } * }); */ var ActiveState = { contextTypes: { activeRoutes: React.PropTypes.array.isRequired, activeParams: React.PropTypes.object.isRequired, activeQuery: React.PropTypes.object.isRequired, isActive: React.PropTypes.func.isRequired }, /** * Returns an array of the routes that are currently active. */ getActiveRoutes: function () { return this.context.activeRoutes; }, /** * Returns an object of the URL params that are currently active. */ getActiveParams: function () { return this.context.activeParams; }, /** * Returns an object of the query params that are currently active. */ getActiveQuery: function () { return this.context.activeQuery; }, /** * A helper method to determine if a given route, params, and query * are active. */ isActive: function (to, params, query) { return this.context.isActive(to, params, query); } }; module.exports = ActiveState; },{}],16:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); /** * A mixin for components that need to know the current URL path. * * Example: * * var ShowThePath = React.createClass({ * mixins: [ Router.CurrentPath ], * render: function () { * return ( * <div>The current path is: {this.getCurrentPath()}</div> * ); * } * }); */ var CurrentPath = { contextTypes: { currentPath: React.PropTypes.string.isRequired }, /** * Returns the current URL path. */ getCurrentPath: function () { return this.context.currentPath; } }; module.exports = CurrentPath; },{}],17:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var invariant = _dereq_('react/lib/invariant'); var canUseDOM = _dereq_('react/lib/ExecutionEnvironment').canUseDOM; var HashLocation = _dereq_('../locations/HashLocation'); var HistoryLocation = _dereq_('../locations/HistoryLocation'); var RefreshLocation = _dereq_('../locations/RefreshLocation'); var PathStore = _dereq_('../stores/PathStore'); var supportsHistory = _dereq_('../utils/supportsHistory'); /** * A hash of { name: location } pairs. */ var NAMED_LOCATIONS = { none: null, hash: HashLocation, history: HistoryLocation, refresh: RefreshLocation }; /** * A mixin for components that manage location. */ var LocationContext = { propTypes: { location: function (props, propName, componentName) { var location = props[propName]; if (typeof location === 'string' && !(location in NAMED_LOCATIONS)) return new Error('Unknown location "' + location + '", see ' + componentName); } }, getDefaultProps: function () { return { location: canUseDOM ? HashLocation : null }; }, componentWillMount: function () { var location = this.getLocation(); invariant( location == null || canUseDOM, 'Cannot use location without a DOM' ); if (location) { PathStore.setup(location); PathStore.addChangeListener(this.handlePathChange); if (this.updateLocation) this.updateLocation(PathStore.getCurrentPath(), PathStore.getCurrentActionType()); } }, componentWillUnmount: function () { if (this.getLocation()) PathStore.removeChangeListener(this.handlePathChange); }, handlePathChange: function () { if (this.updateLocation) this.updateLocation(PathStore.getCurrentPath(), PathStore.getCurrentActionType()); }, /** * Returns the location object this component uses. */ getLocation: function () { if (this._location == null) { var location = this.props.location; if (typeof location === 'string') location = NAMED_LOCATIONS[location]; // Automatically fall back to full page refreshes in // browsers that do not support HTML5 history. if (location === HistoryLocation && !supportsHistory()) location = RefreshLocation; this._location = location; } return this._location; }, childContextTypes: { location: React.PropTypes.object // Not required on the server. }, getChildContext: function () { return { location: this.getLocation() }; } }; module.exports = LocationContext; },{"../locations/HashLocation":11,"../locations/HistoryLocation":12,"../locations/RefreshLocation":13,"../stores/PathStore":21,"../utils/supportsHistory":29,"react/lib/ExecutionEnvironment":42,"react/lib/invariant":66}],18:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); /** * A mixin for components that modify the URL. */ var Navigation = { contextTypes: { makePath: React.PropTypes.func.isRequired, makeHref: React.PropTypes.func.isRequired, transitionTo: React.PropTypes.func.isRequired, replaceWith: React.PropTypes.func.isRequired, goBack: React.PropTypes.func.isRequired }, /** * Returns an absolute URL path created from the given route * name, URL parameters, and query values. */ makePath: function (to, params, query) { return this.context.makePath(to, params, query); }, /** * Returns a string that may safely be used as the href of a * link to the route with the given name. */ makeHref: function (to, params, query) { return this.context.makeHref(to, params, query); }, /** * Transitions to the URL specified in the arguments by pushing * a new URL onto the history stack. */ transitionTo: function (to, params, query) { this.context.transitionTo(to, params, query); }, /** * Transitions to the URL specified in the arguments by replacing * the current URL in the history stack. */ replaceWith: function (to, params, query) { this.context.replaceWith(to, params, query); }, /** * Transitions to the previous URL. */ goBack: function () { this.context.goBack(); } }; module.exports = Navigation; },{}],19:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var invariant = _dereq_('react/lib/invariant'); var Path = _dereq_('../utils/Path'); /** * Performs some normalization and validation on a <Route> component and * all of its children. */ function processRoute(route, container, namedRoutes) { // Note: parentRoute may be a <Route> _or_ a <Routes>. var props = route.props; invariant( React.isValidClass(props.handler), 'The handler for the "%s" route must be a valid React class', props.name || props.path ); var parentPath = (container && container.props.path) || '/'; if ((props.path || props.name) && !props.isDefault && !props.catchAll) { var path = props.path || props.name; // Relative paths extend their parent. if (!Path.isAbsolute(path)) path = Path.join(parentPath, path); props.path = Path.normalize(path); } else { props.path = parentPath; if (props.catchAll) props.path += '*'; } props.paramNames = Path.extractParamNames(props.path); // Make sure the route's path has all params its parent needs. if (container && Array.isArray(container.props.paramNames)) { container.props.paramNames.forEach(function (paramName) { invariant( props.paramNames.indexOf(paramName) !== -1, 'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"', props.path, paramName, container.props.path ); }); } // Make sure the route can be looked up by <Link>s. if (props.name) { var existingRoute = namedRoutes[props.name]; invariant( !existingRoute || route === existingRoute, 'You cannot use the name "%s" for more than one route', props.name ); namedRoutes[props.name] = route; } // Handle <NotFoundRoute>. if (props.catchAll) { invariant( container, '<NotFoundRoute> must have a parent <Route>' ); invariant( container.props.notFoundRoute == null, 'You may not have more than one <NotFoundRoute> per <Route>' ); container.props.notFoundRoute = route; return null; } // Handle <DefaultRoute>. if (props.isDefault) { invariant( container, '<DefaultRoute> must have a parent <Route>' ); invariant( container.props.defaultRoute == null, 'You may not have more than one <DefaultRoute> per <Route>' ); container.props.defaultRoute = route; return null; } // Make sure children is an array. props.children = processRoutes(props.children, route, namedRoutes); return route; } /** * Processes many children <Route>s at once, always returning an array. */ function processRoutes(children, container, namedRoutes) { var routes = []; React.Children.forEach(children, function (child) { // Exclude <DefaultRoute>s and <NotFoundRoute>s. if (child = processRoute(child, container, namedRoutes)) routes.push(child); }); return routes; } /** * A mixin for components that have <Route> children. */ var RouteContext = { _processRoutes: function () { this._namedRoutes = {}; this._routes = processRoutes(this.props.children, this, this._namedRoutes); }, /** * Returns an array of <Route>s in this container. */ getRoutes: function () { if (this._routes == null) this._processRoutes(); return this._routes; }, /** * Returns a hash { name: route } of all named <Route>s in this container. */ getNamedRoutes: function () { if (this._namedRoutes == null) this._processRoutes(); return this._namedRoutes; }, /** * Returns the route with the given name. */ getRouteByName: function (routeName) { var namedRoutes = this.getNamedRoutes(); return namedRoutes[routeName] || null; }, childContextTypes: { routes: React.PropTypes.array.isRequired, namedRoutes: React.PropTypes.object.isRequired }, getChildContext: function () { return { routes: this.getRoutes(), namedRoutes: this.getNamedRoutes(), }; } }; module.exports = RouteContext; },{"../utils/Path":22,"react/lib/invariant":66}],20:[function(_dereq_,module,exports){ var React = (typeof window !== "undefined" ? window.React : typeof global !== "undefined" ? global.React : null); var invariant = _dereq_('react/lib/invariant'); var canUseDOM = _dereq_('react/lib/ExecutionEnvironment').canUseDOM; var ImitateBrowserBehavior = _dereq_('../behaviors/ImitateBrowserBehavior'); var ScrollToTopBehavior = _dereq_('../behaviors/ScrollToTopBehavior'); function getWindowScrollPosition() { invariant( canUseDOM, 'Cannot get current scroll position without a DOM' ); return { x: window.scrollX, y: window.scrollY }; } /** * A hash of { name: scrollBehavior } pairs. */ var NAMED_SCROLL_BEHAVIORS = { none: null, browser: ImitateBrowserBehavior, imitateBrowser: ImitateBrowserBehavior, scrollToTop: ScrollToTopBehavior }; /** * A mixin for components that manage scroll position. */ var ScrollContext = { propTypes: { scrollBehavior: function (props, propName, componentName) { var behavior = props[propName]; if (typeof behavior === 'string' && !(behavior in NAMED_SCROLL_BEHAVIORS)) return new Error('Unknown scroll behavior "' + behavior + '", see ' + componentName); } }, getDefaultProps: function () { return { scrollBehavior: canUseDOM ? ImitateBrowserBehavior : null }; }, componentWillMount: function () { invariant( this.getScrollBehavior() == null || canUseDOM, 'Cannot use scroll behavior without a DOM' ); }, recordScroll: function (path) { var positions = this.getScrollPositions(); positions[path] = getWindowScrollPosition(); }, updateScroll: function (path, actionType) { var behavior = this.getScrollBehavior(); var position = this.getScrollPosition(path) || null; if (behavior) behavior.updateScrollPosition(position, actionType); }, /** * Returns the scroll behavior object this component uses. */ getScrollBehavior: function () { if (this._scrollBehavior == null) { var behavior = this.props.scrollBehavior; if (typeof behavior === 'string') behavior = NAMED_SCROLL_BEHAVIORS[behavior]; this._scrollBehavior = behavior; } return this._scrollBehavior; }, /** * Returns a hash of URL paths to their last known scroll positions. */ getScrollPositions: function () { if (this._scrollPositions == null) this._scrollPositions = {}; return this._scrollPositions; }, /** * Returns the last known scroll position for the given URL path. */ getScrollPosition: function (path) { var positions = this.getScrollPositions(); return positions[path]; }, childContextTypes: { scrollBehavior: React.PropTypes.object // Not required on the server. }, getChildContext: function () { return { scrollBehavior: this.getScrollBehavior() }; } }; module.exports = ScrollContext; },{"../behaviors/ImitateBrowserBehavior":2,"../behaviors/ScrollToTopBehavior":3,"react/lib/ExecutionEnvironment":42,"react/lib/invariant":66}],21:[function(_dereq_,module,exports){ var invariant = _dereq_('react/lib/invariant'); var EventEmitter = _dereq_('events').EventEmitter; var LocationActions = _dereq_('../actions/LocationActions'); var CHANGE_EVENT = 'change'; var _events = new EventEmitter; function notifyChange() { _events.emit(CHANGE_EVENT); } var _currentLocation, _currentActionType; var _currentPath = '/'; function handleLocationChangeAction(action) { if (_currentPath !== action.path) { _currentPath = action.path; _currentActionType = action.type; notifyChange(); } } /** * The PathStore keeps track of the current URL path. */ var PathStore = { addChangeListener: function (listener) { _events.addListener(CHANGE_EVENT, listener); }, removeChangeListener: function (listener) { _events.removeListener(CHANGE_EVENT, listener); }, removeAllChangeListeners: function () { _events.removeAllListeners(CHANGE_EVENT); }, /** * Setup the PathStore to use the given location. */ setup: function (location) { invariant( _currentLocation == null || _currentLocation === location, 'You cannot use %s and %s on the same page', _currentLocation, location ); if (_currentLocation !== location) { if (location.setup) location.setup(handleLocationChangeAction); _currentPath = location.getCurrentPath(); } _currentLocation = location; }, /** * Tear down the PathStore. Really only used for testing. */ teardown: function () { if (_currentLocation && _currentLocation.teardown) _currentLocation.teardown(); _currentLocation = _currentActionType = null; _currentPath = '/'; PathStore.removeAllChangeListeners(); }, /** * Returns the current URL path. */ getCurrentPath: function () { return _currentPath; }, /** * Returns the type of the action that changed the URL. */ getCurrentActionType: function () { return _currentActionType; } }; module.exports = PathStore; },{"../actions/LocationActions":1,"events":31,"react/lib/invariant":66}],22:[function(_dereq_,module,exports){ var invariant = _dereq_('react/lib/invariant'); var merge = _dereq_('qs/lib/utils').merge; var qs = _dereq_('qs'); function encodeURL(url) { return encodeURIComponent(url).replace(/%20/g, '+'); } function decodeURL(url) { return decodeURIComponent(url.replace(/\+/g, ' ')); } function encodeURLPath(path) { return String(path).split('/').map(encodeURL).join('/'); } var paramCompileMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g; var paramInjectMatcher = /:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g; var paramInjectTrailingSlashMatcher = /\/\/\?|\/\?/g; var queryMatcher = /\?(.+)/; var _compiledPatterns = {}; function compilePattern(pattern) { if (!(pattern in _compiledPatterns)) { var paramNames = []; var source = pattern.replace(paramCompileMatcher, function (match, paramName) { if (paramName) { paramNames.push(paramName); return '([^/?#]+)'; } else if (match === '*') { paramNames.push('splat'); return '(.*?)'; } else { return '\\' + match; } }); _compiledPatterns[pattern] = { matcher: new RegExp('^' + source + '$', 'i'), paramNames: paramNames }; } return _compiledPatterns[pattern]; } var Path = { /** * Returns an array of the names of all parameters in the given pattern. */ extractParamNames: function (pattern) { return compilePattern(pattern).paramNames; }, /** * Extracts the portions of the given URL path that match the given pattern * and returns an object of param name => value pairs. Returns null if the * pattern does not match the given path. */ extractParams: function (pattern, path) { var object = compilePattern(pattern); var match = decodeURL(path).match(object.matcher); if (!match) return null; var params = {}; object.paramNames.forEach(function (paramName, index) { params[paramName] = match[index + 1]; }); return params; }, /** * Returns a version of the given route path with params interpolated. Throws * if there is a dynamic segment of the route path for which there is no param. */ injectParams: function (pattern, params) { params = params || {}; var splatIndex = 0; return pattern.replace(paramInjectMatcher, function (match, paramName) { paramName = paramName || 'splat'; // If param is optional don't check for existence if (paramName.slice(-1) !== '?') { invariant( params[paramName] != null, 'Missing "' + paramName + '" parameter for path "' + pattern + '"' ); } else { paramName = paramName.slice(0, -1) if (params[paramName] == null) { return ''; } } var segment; if (paramName === 'splat' && Array.isArray(params[paramName])) { segment = params[paramName][splatIndex++]; invariant( segment != null, 'Missing splat # ' + splatIndex + ' for path "' + pattern + '"' ); } else { segment = params[paramName]; } return encodeURLPath(segment); }).replace(paramInjectTrailingSlashMatcher, '/'); }, /** * Returns an object that is the result of parsing any query string contained * in the given path, null if the path contains no query string. */ extractQuery: function (path) { var match = path.match(queryMatcher); return match && qs.parse(match[1]); }, /** * Returns a version of the given path without the query string. */ withoutQuery: function (path) { return path.replace(queryMatcher, ''); }, /** * Returns a version of the given path with the parameters in the given * query merged into the query string. */ withQuery: function (path, query) { var existingQuery = Path.extractQuery(path); if (existingQuery) query = query ? merge(existingQuery, query) : existingQuery; var queryString = query && qs.stringify(query); if (queryString) return Path.withoutQuery(path) + '?' + queryString; return path; }, /** * Returns true if the given path is absolute. */ isAbsolute: function (path) { return path.charAt(0) === '/'; }, /** * Returns a normalized version of the given path. */ normalize: function (path, parentRoute) { return path.replace(/^\/*/, '/'); }, /** * Joins two URL paths together. */ join: function (a, b) { return a.replace(/\/*$/, '/') + b; } }; module.exports = Path; },{"qs":32,"qs/lib/utils":36,"react/lib/invariant":66}],23:[function(_dereq_,module,exports){ var Promise = _dereq_('when/lib/Promise'); // TODO: Use process.env.NODE_ENV check + envify to enable // when's promise monitor here when in dev. module.exports = Promise; },{"when/lib/Promise":77}],24:[function(_dereq_,module,exports){ /** * Encapsulates a redirect to the given route. */ function Redirect(to, params, query) { this.to = to; this.params = params; this.query = query; } module.exports = Redirect; },{}],25:[function(_dereq_,module,exports){ var ReactDescriptor = _dereq_('react/lib/ReactDescriptor'); var ReactInstanceHandles = _dereq_('react/lib/ReactInstanceHandles'); var ReactMarkupChecksum = _dereq_('react/lib/ReactMarkupChecksum'); var ReactServerRenderingTransaction = _dereq_('react/lib/ReactServerRenderingTransaction'); var cloneWithProps = _dereq_('react/lib/cloneWithProps'); var copyProperties = _dereq_('react/lib/copyProperties'); var instantiateReactComponent = _dereq_('react/lib/instantiateReactComponent'); var invariant = _dereq_('react/lib/invariant'); function cloneRoutesForServerRendering(routes) { return cloneWithProps(routes, { location: 'none', scrollBehavior: 'none' }); } function mergeStateIntoInitialProps(state, props) { copyProperties(props, { initialPath: state.path, initialMatches: state.matches, initialActiveRoutes: state.activeRoutes, initialActiveParams: state.activeParams, initialActiveQuery: state.activeQuery }); } /** * Renders a <Routes> component to a string of HTML at the given URL * path and calls callback(error, abortReason, html) when finished. * * If there was an error during the transition, it is passed to the * callback. Otherwise, if the transition was aborted for some reason, * it is given in the abortReason argument (with the exception of * internal redirects which are transparently handled for you). * * TODO: <NotFoundRoute> should be handled specially so servers know * to use a 404 status code. */ function renderRoutesToString(routes, path, callback) { invariant( ReactDescriptor.isValidDescriptor(routes), 'You must pass a valid ReactComponent to renderRoutesToString' ); var component = instantiateReactComponent( cloneRoutesForServerRendering(routes) ); component.dispatch(path, function (error, abortReason, nextState) { if (error || abortReason) return callback(error, abortReason); mergeStateIntoInitialProps(nextState, component.props); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); transaction.perform(function () { var markup = component.mountComponent(id, transaction, 0); callback(null, null, ReactMarkupChecksum.addChecksumToMarkup(markup)); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } }); } /** * Renders a <Routes> component to static markup at the given URL * path and calls callback(error, abortReason, markup) when finished. */ function renderRoutesToStaticMarkup(routes, path, callback) { invariant( ReactDescriptor.isValidDescriptor(routes), 'You must pass a valid ReactComponent to renderRoutesToStaticMarkup' ); var component = instantiateReactComponent( cloneRoutesForServerRendering(routes) ); component.dispatch(path, function (error, abortReason, nextState) { if (error || abortReason) return callback(error, abortReason); mergeStateIntoInitialProps(nextState, component.props); var transaction; try { var id = ReactInstanceHandles.createReactRootID(); transaction = ReactServerRenderingTransaction.getPooled(false); transaction.perform(function () { callback(null, null, component.mountComponent(id, transaction, 0)); }, null); } finally { ReactServerRenderingTransaction.release(transaction); } }); } module.exports = { renderRoutesToString: renderRoutesToString, renderRoutesToStaticMarkup: renderRoutesToStaticMarkup }; },{"react/lib/ReactDescriptor":47,"react/lib/ReactInstanceHandles":49,"react/lib/ReactMarkupChecksum":50,"react/lib/ReactServerRenderingTransaction":54,"react/lib/cloneWithProps":59,"react/lib/copyProperties":60,"react/lib/instantiateReactComponent":65,"react/lib/invariant":66}],26:[function(_dereq_,module,exports){ var mixInto = _dereq_('react/lib/mixInto'); var Promise = _dereq_('./Promise'); var Redirect = _dereq_('./Redirect'); /** * Encapsulates a transition to a given path. * * The willTransitionTo and willTransitionFrom handlers receive * an instance of this class as their first argument. */ function Transition(routesComponent, path) { this.routesComponent = routesComponent; this.path = path; this.abortReason = null; this.isAborted = false; } mixInto(Transition, { abort: function (reason) { this.abortReason = reason; this.isAborted = true; }, redirect: function (to, params, query) { this.abort(new Redirect(to, params, query)); }, wait: function (value) { this.promise = Promise.resolve(value); }, retry: function () { this.routesComponent.replaceWith(this.path); } }); module.exports = Transition; },{"./Promise":23,"./Redirect":24,"react/lib/mixInto":74}],27:[function(_dereq_,module,exports){ /** * Returns the current URL path from `window.location`, including query string */ function getWindowPath() { return window.location.pathname + window.location.search; } module.exports = getWindowPath; },{}],28:[function(_dereq_,module,exports){ function reversedArray(array) { return array.slice(0).reverse(); } module.exports = reversedArray; },{}],29:[function(_dereq_,module,exports){ function supportsHistory() { /*! taken from modernizr * https://github.com/Modernizr/Modernizr/blob/master/LICENSE * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js */ var ua = navigator.userAgent; if ((ua.indexOf('Android 2.') !== -1 || (ua.indexOf('Android 4.0') !== -1)) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1) { return false; } return (window.history && 'pushState' in window.history); } module.exports = supportsHistory; },{}],30:[function(_dereq_,module,exports){ function withoutProperties(object, properties) { var result = {}; for (var property in object) { if (object.hasOwnProperty(property) && !properties[property]) result[property] = object[property]; } return result; } module.exports = withoutProperties; },{}],31:[function(_dereq_,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; } },{}],32:[function(_dereq_,module,exports){ module.exports = _dereq_('./lib'); },{"./lib":33}],33:[function(_dereq_,module,exports){ // Load modules var Stringify = _dereq_('./stringify'); var Parse = _dereq_('./parse'); // Declare internals var internals = {}; module.exports = { stringify: Stringify, parse: Parse }; },{"./parse":34,"./stringify":35}],34:[function(_dereq_,module,exports){ // Load modules var Utils = _dereq_('./utils'); // Declare internals var internals = { delimiter: '&', depth: 5, arrayLimit: 20, parameterLimit: 1000 }; internals.parseValues = function (str, options) { var obj = {}; var parts = str.split(options.delimiter, options.parameterLimit === Infinity ? undefined : options.parameterLimit); for (var i = 0, il = parts.length; i < il; ++i) { var part = parts[i]; var pos = part.indexOf(']=') === -1 ? part.indexOf('=') : part.indexOf(']=') + 1; if (pos === -1) { obj[Utils.decode(part)] = ''; } else { var key = Utils.decode(part.slice(0, pos)); var val = Utils.decode(part.slice(pos + 1)); if (!obj[key]) { obj[key] = val; } else { obj[key] = [].concat(obj[key]).concat(val); } } } return obj; }; internals.parseObject = function (chain, val, options) { if (!chain.length) { return val; } var root = chain.shift(); var obj = {}; if (root === '[]') { obj = []; obj = obj.concat(internals.parseObject(chain, val, options)); } else { var cleanRoot = root[0] === '[' && root[root.length - 1] === ']' ? root.slice(1, root.length - 1) : root; var index = parseInt(cleanRoot, 10); if (!isNaN(index) && root !== cleanRoot && index <= options.arrayLimit) { obj = []; obj[index] = internals.parseObject(chain, val, options); } else { obj[cleanRoot] = internals.parseObject(chain, val, options); } } return obj; }; internals.parseKeys = function (key, val, options) { if (!key) { return; } // The regex chunks var parent = /^([^\[\]]*)/; var child = /(\[[^\[\]]*\])/g; // Get the parent var segment = parent.exec(key); // Don't allow them to overwrite object prototype properties if (Object.prototype.hasOwnProperty(segment[1])) { return; } // Stash the parent if it exists var keys = []; if (segment[1]) { keys.push(segment[1]); } // Loop through children appending to the array until we hit depth var i = 0; while ((segment = child.exec(key)) !== null && i < options.depth) { ++i; if (!Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g, ''))) { keys.push(segment[1]); } } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return internals.parseObject(keys, val, options); }; module.exports = function (str, options) { if (str === '' || str === null || typeof str === 'undefined') { return {}; } options = options || {}; options.delimiter = typeof options.delimiter === 'string' || Utils.isRegExp(options.delimiter) ? options.delimiter : internals.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : internals.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : internals.arrayLimit; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : internals.parameterLimit; var tempObj = typeof str === 'string' ? internals.parseValues(str, options) : str; var obj = {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0, il = keys.length; i < il; ++i) { var key = keys[i]; var newObj = internals.parseKeys(key, tempObj[key], options); obj = Utils.merge(obj, newObj); } return Utils.compact(obj); }; },{"./utils":36}],35:[function(_dereq_,module,exports){ // Load modules var Utils = _dereq_('./utils'); // Declare internals var internals = { delimiter: '&' }; internals.stringify = function (obj, prefix) { if (Utils.isBuffer(obj)) { obj = obj.toString(); } else if (obj instanceof Date) { obj = obj.toISOString(); } else if (obj === null) { obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') { return [encodeURIComponent(prefix) + '=' + encodeURIComponent(obj)]; } var values = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { values = values.concat(internals.stringify(obj[key], prefix + '[' + key + ']')); } } return values; }; module.exports = function (obj, options) { options = options || {}; var delimiter = typeof options.delimiter === 'undefined' ? internals.delimiter : options.delimiter; var keys = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { keys = keys.concat(internals.stringify(obj[key], key)); } } return keys.join(delimiter); }; },{"./utils":36}],36:[function(_dereq_,module,exports){ // Load modules // Declare internals var internals = {}; exports.arrayToObject = function (source) { var obj = {}; for (var i = 0, il = source.length; i < il; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; exports.merge = function (target, source) { if (!source) { return target; } if (Array.isArray(source)) { for (var i = 0, il = source.length; i < il; ++i) { if (typeof source[i] !== 'undefined') { if (typeof target[i] === 'object') { target[i] = exports.merge(target[i], source[i]); } else { target[i] = source[i]; } } } return target; } if (Array.isArray(target)) { if (typeof source !== 'object') { target.push(source); return target; } else { target = exports.arrayToObject(target); } } var keys = Object.keys(source); for (var k = 0, kl = keys.length; k < kl; ++k) { var key = keys[k]; var value = source[key]; if (value && typeof value === 'object') { if (!target[key]) { target[key] = value; } else { target[key] = exports.merge(target[key], value); } } else { target[key] = value; } } return target; }; exports.decode = function (str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; exports.compact = function (obj, refs) { if (typeof obj !== 'object' || obj === null) { return obj; } refs = refs || []; var lookup = refs.indexOf(obj); if (lookup !== -1) { return refs[lookup]; } refs.push(obj); if (Array.isArray(obj)) { var compacted = []; for (var i = 0, l = obj.length; i < l; ++i) { if (typeof obj[i] !== 'undefined') { compacted.push(obj[i]); } } return compacted; } var keys = Object.keys(obj); for (var i = 0, il = keys.length; i < il; ++i) { var key = keys[i]; obj[key] = exports.compact(obj[key], refs); } return obj; }; exports.isRegExp = function (obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; exports.isBuffer = function (obj) { if (typeof Buffer !== 'undefined') { return Buffer.isBuffer(obj); } else { return false; } }; },{}],37:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule CallbackQueue */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var invariant = _dereq_("./invariant"); var mixInto = _dereq_("./mixInto"); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } mixInto(CallbackQueue, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function(callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function() { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { ("production" !== "production" ? invariant( callbacks.length === contexts.length, "Mismatched list of contexts in callback queue" ) : invariant(callbacks.length === contexts.length)); this._callbacks = null; this._contexts = null; for (var i = 0, l = callbacks.length; i < l; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, /** * Resets the internal queue. * * @internal */ reset: function() { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; },{"./PooledClass":43,"./invariant":66,"./mixInto":74}],38:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventConstants */ "use strict"; var keyMirror = _dereq_("./keyMirror"); var PropagationPhases = keyMirror({bubbled: null, captured: null}); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topBlur: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topError: null, topFocus: null, topInput: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topReset: null, topScroll: null, topSelectionChange: null, topSubmit: null, topTextInput: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; },{"./keyMirror":69}],39:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventPluginHub */ "use strict"; var EventPluginRegistry = _dereq_("./EventPluginRegistry"); var EventPluginUtils = _dereq_("./EventPluginUtils"); var accumulate = _dereq_("./accumulate"); var forEachAccumulated = _dereq_("./forEachAccumulated"); var invariant = _dereq_("./invariant"); var isEventSupported = _dereq_("./isEventSupported"); var monitorCodeUse = _dereq_("./monitorCodeUse"); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @private */ var executeDispatchesAndRelease = function(event) { if (event) { var executeDispatch = EventPluginUtils.executeDispatch; // Plugins can provide custom behavior when dispatching events. var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event); if (PluginModule && PluginModule.executeDispatch) { executeDispatch = PluginModule.executeDispatch; } EventPluginUtils.executeDispatchesInOrder(event, executeDispatch); if (!event.isPersistent()) { event.constructor.release(event); } } }; /** * - `InstanceHandle`: [required] Module that performs logical traversals of DOM * hierarchy given ids of the logical DOM elements involved. */ var InstanceHandle = null; function validateInstanceHandle() { var invalid = !InstanceHandle|| !InstanceHandle.traverseTwoPhase || !InstanceHandle.traverseEnterLeave; if (invalid) { throw new Error('InstanceHandle not injected before use!'); } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {object} InjectedMount * @public */ injectMount: EventPluginUtils.injection.injectMount, /** * @param {object} InjectedInstanceHandle * @public */ injectInstanceHandle: function(InjectedInstanceHandle) { InstanceHandle = InjectedInstanceHandle; if ("production" !== "production") { validateInstanceHandle(); } }, getInstanceHandle: function() { if ("production" !== "production") { validateInstanceHandle(); } return InstanceHandle; }, /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs, registrationNameModules: EventPluginRegistry.registrationNameModules, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {?function} listener The callback to store. */ putListener: function(id, registrationName, listener) { ("production" !== "production" ? invariant( !listener || typeof listener === 'function', 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener ) : invariant(!listener || typeof listener === 'function')); if ("production" !== "production") { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. if (registrationName === 'onScroll' && !isEventSupported('scroll', true)) { monitorCodeUse('react_no_scroll_event'); console.warn('This browser doesn\'t support the `onScroll` event'); } } var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[id] = listener; }, /** * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[id]; }, /** * Deletes a listener from the registration bank. * * @param {string} id ID of the DOM element. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function(id, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; if (bankForRegistrationName) { delete bankForRegistrationName[id]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {string} id ID of the DOM element. */ deleteAllListeners: function(id) { for (var registrationName in listenerBank) { delete listenerBank[registrationName][id]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @param {string} topLevelType Record from `EventConstants`. * @param {DOMEventTarget} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native browser event. * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0, l = plugins.length; i < l; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); if (extractedEvents) { events = accumulate(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function(events) { if (events) { eventQueue = accumulate(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function() { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; forEachAccumulated(processingEventQueue, executeDispatchesAndRelease); ("production" !== "production" ? invariant( !eventQueue, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.' ) : invariant(!eventQueue)); }, /** * These are needed for tests only. Do not use! */ __purge: function() { listenerBank = {}; }, __getListenerBank: function() { return listenerBank; } }; module.exports = EventPluginHub; },{"./EventPluginRegistry":40,"./EventPluginUtils":41,"./accumulate":57,"./forEachAccumulated":63,"./invariant":66,"./isEventSupported":67,"./monitorCodeUse":75}],40:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventPluginRegistry * @typechecks static-only */ "use strict"; var invariant = _dereq_("./invariant"); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); ("production" !== "production" ? invariant( pluginIndex > -1, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName ) : invariant(pluginIndex > -1)); if (EventPluginRegistry.plugins[pluginIndex]) { continue; } ("production" !== "production" ? invariant( PluginModule.extractEvents, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName ) : invariant(PluginModule.extractEvents)); EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { ("production" !== "production" ? invariant( publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ), 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName ) : invariant(publishEventForPlugin( publishedEvents[eventName], PluginModule, eventName ))); } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { ("production" !== "production" ? invariant( !EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName), 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName ) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName))); EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName( phasedRegistrationName, PluginModule, eventName ); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName( dispatchConfig.registrationName, PluginModule, eventName ); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { ("production" !== "production" ? invariant( !EventPluginRegistry.registrationNameModules[registrationName], 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName ) : invariant(!EventPluginRegistry.registrationNameModules[registrationName])); EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function(InjectedEventPluginOrder) { ("production" !== "production" ? invariant( !EventPluginOrder, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.' ) : invariant(!EventPluginOrder)); // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function(injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { ("production" !== "production" ? invariant( !namesToPlugins[pluginName], 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName ) : invariant(!namesToPlugins[pluginName])); namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function(event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[ dispatchConfig.registrationName ] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[ dispatchConfig.phasedRegistrationNames[phase] ]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function() { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } } }; module.exports = EventPluginRegistry; },{"./invariant":66}],41:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule EventPluginUtils */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var invariant = _dereq_("./invariant"); /** * Injected dependencies: */ /** * - `Mount`: [required] Module that can convert between React dom IDs and * actual node references. */ var injection = { Mount: null, injectMount: function(InjectedMount) { injection.Mount = InjectedMount; if ("production" !== "production") { ("production" !== "production" ? invariant( InjectedMount && InjectedMount.getNode, 'EventPluginUtils.injection.injectMount(...): Injected Mount module ' + 'is missing getNode.' ) : invariant(InjectedMount && InjectedMount.getNode)); } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if ("production" !== "production") { validateEventDispatches = function(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; var listenersIsArr = Array.isArray(dispatchListeners); var idsIsArr = Array.isArray(dispatchIDs); var IDsLen = idsIsArr ? dispatchIDs.length : dispatchIDs ? 1 : 0; var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; ("production" !== "production" ? invariant( idsIsArr === listenersIsArr && IDsLen === listenersLen, 'EventPluginUtils: Invalid `event`.' ) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen)); }; } /** * Invokes `cb(event, listener, id)`. Avoids using call if no scope is * provided. The `(listener,id)` pair effectively forms the "dispatch" but are * kept separate to conserve memory. */ function forEachEventDispatch(event, cb) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "production") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. cb(event, dispatchListeners[i], dispatchIDs[i]); } } else if (dispatchListeners) { cb(event, dispatchListeners, dispatchIDs); } } /** * Default implementation of PluginModule.executeDispatch(). * @param {SyntheticEvent} SyntheticEvent to handle * @param {function} Application-level callback * @param {string} domID DOM id to pass to the callback. */ function executeDispatch(event, listener, domID) { event.currentTarget = injection.Mount.getNode(domID); var returnValue = listener(event, domID); event.currentTarget = null; return returnValue; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, executeDispatch) { forEachEventDispatch(event, executeDispatch); event._dispatchListeners = null; event._dispatchIDs = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return id of the first dispatch execution who's listener returns true, or * null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchIDs = event._dispatchIDs; if ("production" !== "production") { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and IDs are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchIDs[i])) { return dispatchIDs[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchIDs)) { return dispatchIDs; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchIDs = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if ("production" !== "production") { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchID = event._dispatchIDs; ("production" !== "production" ? invariant( !Array.isArray(dispatchListener), 'executeDirectDispatch(...): Invalid `event`.' ) : invariant(!Array.isArray(dispatchListener))); var res = dispatchListener ? dispatchListener(event, dispatchID) : null; event._dispatchListeners = null; event._dispatchIDs = null; return res; } /** * @param {SyntheticEvent} event * @return {bool} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatch: executeDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, injection: injection, useTouchEvents: false }; module.exports = EventPluginUtils; },{"./EventConstants":38,"./invariant":66}],42:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ExecutionEnvironment */ /*jslint evil: true */ "use strict"; var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; },{}],43:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule PooledClass */ "use strict"; var invariant = _dereq_("./invariant"); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function(copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function(a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function(a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fiveArgumentPooler = function(a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function(instance) { var Klass = this; ("production" !== "production" ? invariant( instance instanceof Klass, 'Trying to release an instance into a pool of a different type.' ) : invariant(instance instanceof Klass)); if (instance.destructor) { instance.destructor(); } if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function(CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; },{"./invariant":66}],44:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactBrowserEventEmitter * @typechecks static-only */ "use strict"; var EventConstants = _dereq_("./EventConstants"); var EventPluginHub = _dereq_("./EventPluginHub"); var EventPluginRegistry = _dereq_("./EventPluginRegistry"); var ReactEventEmitterMixin = _dereq_("./ReactEventEmitterMixin"); var ViewportMetrics = _dereq_("./ViewportMetrics"); var isEventSupported = _dereq_("./isEventSupported"); var merge = _dereq_("./merge"); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topBlur: 'blur', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTextInput: 'textInput', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = "_reactListenersID" + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = merge(ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function(ReactEventListener) { ReactEventListener.setHandleTopLevel( ReactBrowserEventEmitter.handleTopLevel ); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function(enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function() { return !!( ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled() ); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function(registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry. registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0, l = dependencies.length; i < l; i++) { var dependency = dependencies[i]; if (!( isListening.hasOwnProperty(dependency) && isListening[dependency] )) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'wheel', mountAt ); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'mousewheel', mountAt ); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topWheel, 'DOMMouseScroll', mountAt ); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topScroll, 'scroll', mountAt ); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE ); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topFocus, 'focus', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelTypes.topBlur, 'blur', mountAt ); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topFocus, 'focusin', mountAt ); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelTypes.topBlur, 'focusout', mountAt ); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( dependency, topEventMapping[dependency], mountAt ); } isListening[dependency] = true; } } }, trapBubbledEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent( topLevelType, handlerBaseName, handle ); }, trapCapturedEvent: function(topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent( topLevelType, handlerBaseName, handle ); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function(){ if (!isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } }, eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs, registrationNameModules: EventPluginHub.registrationNameModules, putListener: EventPluginHub.putListener, getListener: EventPluginHub.getListener, deleteListener: EventPluginHub.deleteListener, deleteAllListeners: EventPluginHub.deleteAllListeners }); module.exports = ReactBrowserEventEmitter; },{"./EventConstants":38,"./EventPluginHub":39,"./EventPluginRegistry":40,"./ReactEventEmitterMixin":48,"./ViewportMetrics":56,"./isEventSupported":67,"./merge":71}],45:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactContext */ "use strict"; var merge = _dereq_("./merge"); /** * Keeps track of the current context. * * The context is automatically passed down the component ownership hierarchy * and is accessible via `this.context` on ReactCompositeComponents. */ var ReactContext = { /** * @internal * @type {object} */ current: {}, /** * Temporarily extends the current context while executing scopedCallback. * * A typical use case might look like * * render: function() { * var children = ReactContext.withContext({foo: 'foo'} () => ( * * )); * return <div>{children}</div>; * } * * @param {object} newContext New context to merge into the existing context * @param {function} scopedCallback Callback to run with the new context * @return {ReactComponent|array<ReactComponent>} */ withContext: function(newContext, scopedCallback) { var result; var previousContext = ReactContext.current; ReactContext.current = merge(previousContext, newContext); try { result = scopedCallback(); } finally { ReactContext.current = previousContext; } return result; } }; module.exports = ReactContext; },{"./merge":71}],46:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactCurrentOwner */ "use strict"; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. * * The depth indicate how many composite components are above this render level. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; },{}],47:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactDescriptor */ "use strict"; var ReactContext = _dereq_("./ReactContext"); var ReactCurrentOwner = _dereq_("./ReactCurrentOwner"); var merge = _dereq_("./merge"); var warning = _dereq_("./warning"); /** * Warn for mutations. * * @internal * @param {object} object * @param {string} key */ function defineWarningProperty(object, key) { Object.defineProperty(object, key, { configurable: false, enumerable: true, get: function() { if (!this._store) { return null; } return this._store[key]; }, set: function(value) { ("production" !== "production" ? warning( false, 'Don\'t set the ' + key + ' property of the component. ' + 'Mutate the existing props object instead.' ) : null); this._store[key] = value; } }); } /** * This is updated to true if the membrane is successfully created. */ var useMutationMembrane = false; /** * Warn for mutations. * * @internal * @param {object} descriptor */ function defineMutationMembrane(prototype) { try { var pseudoFrozenProperties = { props: true }; for (var key in pseudoFrozenProperties) { defineWarningProperty(prototype, key); } useMutationMembrane = true; } catch (x) { // IE will fail on defineProperty } } /** * Transfer static properties from the source to the target. Functions are * rebound to have this reflect the original source. */ function proxyStaticMethods(target, source) { if (typeof source !== 'function') { return; } for (var key in source) { if (source.hasOwnProperty(key)) { var value = source[key]; if (typeof value === 'function') { var bound = value.bind(source); // Copy any properties defined on the function, such as `isRequired` on // a PropTypes validator. (mergeInto refuses to work on functions.) for (var k in value) { if (value.hasOwnProperty(k)) { bound[k] = value[k]; } } target[key] = bound; } else { target[key] = value; } } } } /** * Base constructor for all React descriptors. This is only used to make this * work with a dynamic instanceof check. Nothing should live on this prototype. * * @param {*} type * @internal */ var ReactDescriptor = function() {}; if ("production" !== "production") { defineMutationMembrane(ReactDescriptor.prototype); } ReactDescriptor.createFactory = function(type) { var descriptorPrototype = Object.create(ReactDescriptor.prototype); var factory = function(props, children) { // For consistency we currently allocate a new object for every descriptor. // This protects the descriptor from being mutated by the original props // object being mutated. It also protects the original props object from // being mutated by children arguments and default props. This behavior // comes with a performance cost and could be deprecated in the future. // It could also be optimized with a smarter JSX transform. if (props == null) { props = {}; } else if (typeof props === 'object') { props = merge(props); } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 1; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 1]; } props.children = childArray; } // Initialize the descriptor object var descriptor = Object.create(descriptorPrototype); // Record the component responsible for creating this descriptor. descriptor._owner = ReactCurrentOwner.current; // TODO: Deprecate withContext, and then the context becomes accessible // through the owner. descriptor._context = ReactContext.current; if ("production" !== "production") { // The validation flag and props are currently mutative. We put them on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. descriptor._store = { validated: false, props: props }; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing // store. if (useMutationMembrane) { Object.freeze(descriptor); return descriptor; } } descriptor.props = props; return descriptor; }; // Currently we expose the prototype of the descriptor so that // <Foo /> instanceof Foo works. This is controversial pattern. factory.prototype = descriptorPrototype; // Expose the type on the factory and the prototype so that it can be // easily accessed on descriptors. E.g. <Foo />.type === Foo.type and for // static methods like <Foo />.type.staticMethod(); // This should not be named constructor since this may not be the function // that created the descriptor, and it may not even be a constructor. factory.type = type; descriptorPrototype.type = type; proxyStaticMethods(factory, type); // Expose a unique constructor on the prototype is that this works with type // systems that compare constructor properties: <Foo />.constructor === Foo // This may be controversial since it requires a known factory function. descriptorPrototype.constructor = factory; return factory; }; ReactDescriptor.cloneAndReplaceProps = function(oldDescriptor, newProps) { var newDescriptor = Object.create(oldDescriptor.constructor.prototype); // It's important that this property order matches the hidden class of the // original descriptor to maintain perf. newDescriptor._owner = oldDescriptor._owner; newDescriptor._context = oldDescriptor._context; if ("production" !== "production") { newDescriptor._store = { validated: oldDescriptor._store.validated, props: newProps }; if (useMutationMembrane) { Object.freeze(newDescriptor); return newDescriptor; } } newDescriptor.props = newProps; return newDescriptor; }; /** * Checks if a value is a valid descriptor constructor. * * @param {*} * @return {boolean} * @public */ ReactDescriptor.isValidFactory = function(factory) { return typeof factory === 'function' && factory.prototype instanceof ReactDescriptor; }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactDescriptor.isValidDescriptor = function(object) { return object instanceof ReactDescriptor; }; module.exports = ReactDescriptor; },{"./ReactContext":45,"./ReactCurrentOwner":46,"./merge":71,"./warning":76}],48:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactEventEmitterMixin */ "use strict"; var EventPluginHub = _dereq_("./EventPluginHub"); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} topLevelTarget The listening component root node. * @param {string} topLevelTargetID ID of `topLevelTarget`. * @param {object} nativeEvent Native environment event. */ handleTopLevel: function( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent) { var events = EventPluginHub.extractEvents( topLevelType, topLevelTarget, topLevelTargetID, nativeEvent ); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; },{"./EventPluginHub":39}],49:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactInstanceHandles * @typechecks static-only */ "use strict"; var ReactRootIndex = _dereq_("./ReactRootIndex"); var invariant = _dereq_("./invariant"); var SEPARATOR = '.'; var SEPARATOR_LENGTH = SEPARATOR.length; /** * Maximum depth of traversals before we consider the possibility of a bad ID. */ var MAX_TREE_DEPTH = 100; /** * Creates a DOM ID prefix to use when mounting React components. * * @param {number} index A unique integer * @return {string} React root ID. * @internal */ function getReactRootIDString(index) { return SEPARATOR + index.toString(36); } /** * Checks if a character in the supplied ID is a separator or the end. * * @param {string} id A React DOM ID. * @param {number} index Index of the character to check. * @return {boolean} True if the character is a separator or end of the ID. * @private */ function isBoundary(id, index) { return id.charAt(index) === SEPARATOR || index === id.length; } /** * Checks if the supplied string is a valid React DOM ID. * * @param {string} id A React DOM ID, maybe. * @return {boolean} True if the string is a valid React DOM ID. * @private */ function isValidID(id) { return id === '' || ( id.charAt(0) === SEPARATOR && id.charAt(id.length - 1) !== SEPARATOR ); } /** * Checks if the first ID is an ancestor of or equal to the second ID. * * @param {string} ancestorID * @param {string} descendantID * @return {boolean} True if `ancestorID` is an ancestor of `descendantID`. * @internal */ function isAncestorIDOf(ancestorID, descendantID) { return ( descendantID.indexOf(ancestorID) === 0 && isBoundary(descendantID, ancestorID.length) ); } /** * Gets the parent ID of the supplied React DOM ID, `id`. * * @param {string} id ID of a component. * @return {string} ID of the parent, or an empty string. * @private */ function getParentID(id) { return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : ''; } /** * Gets the next DOM ID on the tree path from the supplied `ancestorID` to the * supplied `destinationID`. If they are equal, the ID is returned. * * @param {string} ancestorID ID of an ancestor node of `destinationID`. * @param {string} destinationID ID of the destination node. * @return {string} Next ID on the path from `ancestorID` to `destinationID`. * @private */ function getNextDescendantID(ancestorID, destinationID) { ("production" !== "production" ? invariant( isValidID(ancestorID) && isValidID(destinationID), 'getNextDescendantID(%s, %s): Received an invalid React DOM ID.', ancestorID, destinationID ) : invariant(isValidID(ancestorID) && isValidID(destinationID))); ("production" !== "production" ? invariant( isAncestorIDOf(ancestorID, destinationID), 'getNextDescendantID(...): React has made an invalid assumption about ' + 'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.', ancestorID, destinationID ) : invariant(isAncestorIDOf(ancestorID, destinationID))); if (ancestorID === destinationID) { return ancestorID; } // Skip over the ancestor and the immediate separator. Traverse until we hit // another separator or we reach the end of `destinationID`. var start = ancestorID.length + SEPARATOR_LENGTH; for (var i = start; i < destinationID.length; i++) { if (isBoundary(destinationID, i)) { break; } } return destinationID.substr(0, i); } /** * Gets the nearest common ancestor ID of two IDs. * * Using this ID scheme, the nearest common ancestor ID is the longest common * prefix of the two IDs that immediately preceded a "marker" in both strings. * * @param {string} oneID * @param {string} twoID * @return {string} Nearest common ancestor ID, or the empty string if none. * @private */ function getFirstCommonAncestorID(oneID, twoID) { var minLength = Math.min(oneID.length, twoID.length); if (minLength === 0) { return ''; } var lastCommonMarkerIndex = 0; // Use `<=` to traverse until the "EOL" of the shorter string. for (var i = 0; i <= minLength; i++) { if (isBoundary(oneID, i) && isBoundary(twoID, i)) { lastCommonMarkerIndex = i; } else if (oneID.charAt(i) !== twoID.charAt(i)) { break; } } var longestCommonID = oneID.substr(0, lastCommonMarkerIndex); ("production" !== "production" ? invariant( isValidID(longestCommonID), 'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s', oneID, twoID, longestCommonID ) : invariant(isValidID(longestCommonID))); return longestCommonID; } /** * Traverses the parent path between two IDs (either up or down). The IDs must * not be the same, and there must exist a parent path between them. If the * callback returns `false`, traversal is stopped. * * @param {?string} start ID at which to start traversal. * @param {?string} stop ID at which to end traversal. * @param {function} cb Callback to invoke each ID with. * @param {?boolean} skipFirst Whether or not to skip the first node. * @param {?boolean} skipLast Whether or not to skip the last node. * @private */ function traverseParentPath(start, stop, cb, arg, skipFirst, skipLast) { start = start || ''; stop = stop || ''; ("production" !== "production" ? invariant( start !== stop, 'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.', start ) : invariant(start !== stop)); var traverseUp = isAncestorIDOf(stop, start); ("production" !== "production" ? invariant( traverseUp || isAncestorIDOf(start, stop), 'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' + 'not have a parent path.', start, stop ) : invariant(traverseUp || isAncestorIDOf(start, stop))); // Traverse from `start` to `stop` one depth at a time. var depth = 0; var traverse = traverseUp ? getParentID : getNextDescendantID; for (var id = start; /* until break */; id = traverse(id, stop)) { var ret; if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) { ret = cb(id, traverseUp, arg); } if (ret === false || id === stop) { // Only break //after// visiting `stop`. break; } ("production" !== "production" ? invariant( depth++ < MAX_TREE_DEPTH, 'traverseParentPath(%s, %s, ...): Detected an infinite loop while ' + 'traversing the React DOM ID tree. This may be due to malformed IDs: %s', start, stop ) : invariant(depth++ < MAX_TREE_DEPTH)); } } /** * Manages the IDs assigned to DOM representations of React components. This * uses a specific scheme in order to traverse the DOM efficiently (e.g. in * order to simulate events). * * @internal */ var ReactInstanceHandles = { /** * Constructs a React root ID * @return {string} A React root ID. */ createReactRootID: function() { return getReactRootIDString(ReactRootIndex.createReactRootIndex()); }, /** * Constructs a React ID by joining a root ID with a name. * * @param {string} rootID Root ID of a parent component. * @param {string} name A component's name (as flattened children). * @return {string} A React ID. * @internal */ createReactID: function(rootID, name) { return rootID + name; }, /** * Gets the DOM ID of the React component that is the root of the tree that * contains the React component with the supplied DOM ID. * * @param {string} id DOM ID of a React component. * @return {?string} DOM ID of the React component that is the root. * @internal */ getReactRootIDFromNodeID: function(id) { if (id && id.charAt(0) === SEPARATOR && id.length > 1) { var index = id.indexOf(SEPARATOR, 1); return index > -1 ? id.substr(0, index) : id; } return null; }, /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * NOTE: Does not invoke the callback on the nearest common ancestor because * nothing "entered" or "left" that element. * * @param {string} leaveID ID being left. * @param {string} enterID ID being entered. * @param {function} cb Callback to invoke on each entered/left ID. * @param {*} upArg Argument to invoke the callback with on left IDs. * @param {*} downArg Argument to invoke the callback with on entered IDs. * @internal */ traverseEnterLeave: function(leaveID, enterID, cb, upArg, downArg) { var ancestorID = getFirstCommonAncestorID(leaveID, enterID); if (ancestorID !== leaveID) { traverseParentPath(leaveID, ancestorID, cb, upArg, false, true); } if (ancestorID !== enterID) { traverseParentPath(ancestorID, enterID, cb, downArg, true, false); } }, /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseTwoPhase: function(targetID, cb, arg) { if (targetID) { traverseParentPath('', targetID, cb, arg, true, false); traverseParentPath(targetID, '', cb, arg, false, true); } }, /** * Traverse a node ID, calling the supplied `cb` for each ancestor ID. For * example, passing `.0.$row-0.1` would result in `cb` getting called * with `.0`, `.0.$row-0`, and `.0.$row-0.1`. * * NOTE: This traversal happens on IDs without touching the DOM. * * @param {string} targetID ID of the target node. * @param {function} cb Callback to invoke. * @param {*} arg Argument to invoke the callback with. * @internal */ traverseAncestors: function(targetID, cb, arg) { traverseParentPath('', targetID, cb, arg, true, false); }, /** * Exposed for unit testing. * @private */ _getFirstCommonAncestorID: getFirstCommonAncestorID, /** * Exposed for unit testing. * @private */ _getNextDescendantID: getNextDescendantID, isAncestorIDOf: isAncestorIDOf, SEPARATOR: SEPARATOR }; module.exports = ReactInstanceHandles; },{"./ReactRootIndex":53,"./invariant":66}],50:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactMarkupChecksum */ "use strict"; var adler32 = _dereq_("./adler32"); var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function(markup) { var checksum = adler32(markup); return markup.replace( '>', ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '">' ); }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function(markup, element) { var existingChecksum = element.getAttribute( ReactMarkupChecksum.CHECKSUM_ATTR_NAME ); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; },{"./adler32":58}],51:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactPropTransferer */ "use strict"; var emptyFunction = _dereq_("./emptyFunction"); var invariant = _dereq_("./invariant"); var joinClasses = _dereq_("./joinClasses"); var merge = _dereq_("./merge"); /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return merge(b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Never transfer the `key` prop. */ key: emptyFunction, /** * Never transfer the `ref` prop. */ ref: emptyFunction, /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { TransferStrategies: TransferStrategies, /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(merge(oldProps), newProps); }, /** * @lends {ReactPropTransferer.prototype} */ Mixin: { /** * Transfer props from this component to a target component. * * Props that do not have an explicit transfer strategy will be transferred * only if the target component does not already have the prop set. * * This is usually used to pass down props to a returned root component. * * @param {ReactDescriptor} descriptor Component receiving the properties. * @return {ReactDescriptor} The supplied `component`. * @final * @protected */ transferPropsTo: function(descriptor) { ("production" !== "production" ? invariant( descriptor._owner === this, '%s: You can\'t call transferPropsTo() on a component that you ' + 'don\'t own, %s. This usually means you are calling ' + 'transferPropsTo() on a component passed in as props or children.', this.constructor.displayName, descriptor.type.displayName ) : invariant(descriptor._owner === this)); // Because descriptors are immutable we have to merge into the existing // props object rather than clone it. transferInto(descriptor.props, this.props); return descriptor; } } }; module.exports = ReactPropTransferer; },{"./emptyFunction":62,"./invariant":66,"./joinClasses":68,"./merge":71}],52:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactPutListenerQueue */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter"); var mixInto = _dereq_("./mixInto"); function ReactPutListenerQueue() { this.listenersToPut = []; } mixInto(ReactPutListenerQueue, { enqueuePutListener: function(rootNodeID, propKey, propValue) { this.listenersToPut.push({ rootNodeID: rootNodeID, propKey: propKey, propValue: propValue }); }, putListeners: function() { for (var i = 0; i < this.listenersToPut.length; i++) { var listenerToPut = this.listenersToPut[i]; ReactBrowserEventEmitter.putListener( listenerToPut.rootNodeID, listenerToPut.propKey, listenerToPut.propValue ); } }, reset: function() { this.listenersToPut.length = 0; }, destructor: function() { this.reset(); } }); PooledClass.addPoolingTo(ReactPutListenerQueue); module.exports = ReactPutListenerQueue; },{"./PooledClass":43,"./ReactBrowserEventEmitter":44,"./mixInto":74}],53:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactRootIndex * @typechecks */ "use strict"; var ReactRootIndexInjection = { /** * @param {function} _createReactRootIndex */ injectCreateReactRootIndex: function(_createReactRootIndex) { ReactRootIndex.createReactRootIndex = _createReactRootIndex; } }; var ReactRootIndex = { createReactRootIndex: null, injection: ReactRootIndexInjection }; module.exports = ReactRootIndex; },{}],54:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ReactServerRenderingTransaction * @typechecks */ "use strict"; var PooledClass = _dereq_("./PooledClass"); var CallbackQueue = _dereq_("./CallbackQueue"); var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue"); var Transaction = _dereq_("./Transaction"); var emptyFunction = _dereq_("./emptyFunction"); var mixInto = _dereq_("./mixInto"); /** * Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks * during the performing of the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function() { this.reactMountReady.reset(); }, close: emptyFunction }; var PUT_LISTENER_QUEUEING = { initialize: function() { this.putListenerQueue.reset(); }, close: emptyFunction }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [ PUT_LISTENER_QUEUEING, ON_DOM_READY_QUEUEING ]; /** * @class ReactServerRenderingTransaction * @param {boolean} renderToStaticMarkup */ function ReactServerRenderingTransaction(renderToStaticMarkup) { this.reinitializeTransaction(); this.renderToStaticMarkup = renderToStaticMarkup; this.reactMountReady = CallbackQueue.getPooled(null); this.putListenerQueue = ReactPutListenerQueue.getPooled(); } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array} Empty list of operation wrap proceedures. */ getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function() { return this.reactMountReady; }, getPutListenerQueue: function() { return this.putListenerQueue; }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be resused. */ destructor: function() { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; ReactPutListenerQueue.release(this.putListenerQueue); this.putListenerQueue = null; } }; mixInto(ReactServerRenderingTransaction, Transaction.Mixin); mixInto(ReactServerRenderingTransaction, Mixin); PooledClass.addPoolingTo(ReactServerRenderingTransaction); module.exports = ReactServerRenderingTransaction; },{"./CallbackQueue":37,"./PooledClass":43,"./ReactPutListenerQueue":52,"./Transaction":55,"./emptyFunction":62,"./mixInto":74}],55:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule Transaction */ "use strict"; var invariant = _dereq_("./invariant"); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM upates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function() { this.transactionWrappers = this.getTransactionWrappers(); if (!this.wrapperInitData) { this.wrapperInitData = []; } else { this.wrapperInitData.length = 0; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function() { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} args... Arguments to pass to the method (optional). * Helps prevent need to bind in many cases. * @return Return value from `method`. */ perform: function(method, scope, a, b, c, d, e, f) { ("production" !== "production" ? invariant( !this.isInTransaction(), 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.' ) : invariant(!this.isInTransaction())); var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) { } } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function(startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) { } } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function(startIndex) { ("production" !== "production" ? invariant( this.isInTransaction(), 'Transaction.closeAll(): Cannot close transaction when none are open.' ) : invariant(this.isInTransaction())); var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR) { wrapper.close && wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) { } } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occured. */ OBSERVED_ERROR: {} }; module.exports = Transaction; },{"./invariant":66}],56:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule ViewportMetrics */ "use strict"; var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition"); var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function() { var scrollPosition = getUnboundedScrollPosition(window); ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; },{"./getUnboundedScrollPosition":64}],57:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule accumulate */ "use strict"; var invariant = _dereq_("./invariant"); /** * Accumulates items that must not be null or undefined. * * This is used to conserve memory by avoiding array allocations. * * @return {*|array<*>} An accumulation of items. */ function accumulate(current, next) { ("production" !== "production" ? invariant( next != null, 'accumulate(...): Accumulated items must be not be null or undefined.' ) : invariant(next != null)); if (current == null) { return next; } else { // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray) { return current.concat(next); } else { if (nextIsArray) { return [current].concat(next); } else { return [current, next]; } } } } module.exports = accumulate; },{"./invariant":66}],58:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule adler32 */ /* jslint bitwise:true */ "use strict"; var MOD = 65521; // This is a clean-room implementation of adler32 designed for detecting // if markup is not what we expect it to be. It does not need to be // cryptographically strong, only reasonable good at detecting if markup // generated on the server is different than that on the client. function adler32(data) { var a = 1; var b = 0; for (var i = 0; i < data.length; i++) { a = (a + data.charCodeAt(i)) % MOD; b = (b + a) % MOD; } return a | (b << 16); } module.exports = adler32; },{}],59:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @typechecks * @providesModule cloneWithProps */ "use strict"; var ReactPropTransferer = _dereq_("./ReactPropTransferer"); var keyOf = _dereq_("./keyOf"); var warning = _dereq_("./warning"); var CHILDREN_PROP = keyOf({children: null}); /** * Sometimes you want to change the props of a child passed to you. Usually * this is to add a CSS class. * * @param {object} child child component you'd like to clone * @param {object} props props you'd like to modify. They will be merged * as if you used `transferPropsTo()`. * @return {object} a clone of child with props merged in. */ function cloneWithProps(child, props) { if ("production" !== "production") { ("production" !== "production" ? warning( !child.props.ref, 'You are calling cloneWithProps() on a child with a ref. This is ' + 'dangerous because you\'re creating a new child which will not be ' + 'added as a ref to its parent.' ) : null); } var newProps = ReactPropTransferer.mergeProps(props, child.props); // Use `child.props.children` if it is provided. if (!newProps.hasOwnProperty(CHILDREN_PROP) && child.props.hasOwnProperty(CHILDREN_PROP)) { newProps.children = child.props.children; } // The current API doesn't retain _owner and _context, which is why this // doesn't use ReactDescriptor.cloneAndReplaceProps. return child.constructor(newProps); } module.exports = cloneWithProps; },{"./ReactPropTransferer":51,"./keyOf":70,"./warning":76}],60:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule copyProperties */ /** * Copy properties from one or more objects (up to 5) into the first object. * This is a shallow copy. It mutates the first object and also returns it. * * NOTE: `arguments` has a very significant performance penalty, which is why * we don't support unlimited arguments. */ function copyProperties(obj, a, b, c, d, e, f) { obj = obj || {}; if ("production" !== "production") { if (f) { throw new Error('Too many arguments passed to copyProperties'); } } var args = [a, b, c, d, e]; var ii = 0, v; while (args[ii]) { v = args[ii++]; for (var k in v) { obj[k] = v[k]; } // IE ignores toString in object iteration.. See: // webreflection.blogspot.com/2007/07/quick-fix-internet-explorer-and.html if (v.hasOwnProperty && v.hasOwnProperty('toString') && (typeof v.toString != 'undefined') && (obj.toString !== v.toString)) { obj.toString = v.toString; } } return obj; } module.exports = copyProperties; },{}],61:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule cx */ /** * This function is used to mark string literals representing CSS class names * so that they can be transformed statically. This allows for modularization * and minification of CSS class names. * * In static_upstream, this function is actually implemented, but it should * eventually be replaced with something more descriptive, and the transform * that is used in the main stack should be ported for use elsewhere. * * @param string|object className to modularize, or an object of key/values. * In the object case, the values are conditions that * determine if the className keys should be included. * @param [string ...] Variable list of classNames in the string case. * @return string Renderable space-separated CSS className. */ function cx(classNames) { if (typeof classNames == 'object') { return Object.keys(classNames).filter(function(className) { return classNames[className]; }).join(' '); } else { return Array.prototype.join.call(arguments, ' '); } } module.exports = cx; },{}],62:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule emptyFunction */ var copyProperties = _dereq_("./copyProperties"); function makeEmptyFunction(arg) { return function() { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} copyProperties(emptyFunction, { thatReturns: makeEmptyFunction, thatReturnsFalse: makeEmptyFunction(false), thatReturnsTrue: makeEmptyFunction(true), thatReturnsNull: makeEmptyFunction(null), thatReturnsThis: function() { return this; }, thatReturnsArgument: function(arg) { return arg; } }); module.exports = emptyFunction; },{"./copyProperties":60}],63:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule forEachAccumulated */ "use strict"; /** * @param {array} an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; },{}],64:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule getUnboundedScrollPosition * @typechecks */ "use strict"; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; },{}],65:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule instantiateReactComponent * @typechecks static-only */ "use strict"; var invariant = _dereq_("./invariant"); /** * Validate a `componentDescriptor`. This should be exposed publicly in a follow * up diff. * * @param {object} descriptor * @return {boolean} Returns true if this is a valid descriptor of a Component. */ function isValidComponentDescriptor(descriptor) { return ( descriptor && typeof descriptor.type === 'function' && typeof descriptor.type.prototype.mountComponent === 'function' && typeof descriptor.type.prototype.receiveComponent === 'function' ); } /** * Given a `componentDescriptor` create an instance that will actually be * mounted. Currently it just extracts an existing clone from composite * components but this is an implementation detail which will change. * * @param {object} descriptor * @return {object} A new instance of componentDescriptor's constructor. * @protected */ function instantiateReactComponent(descriptor) { // TODO: Make warning // if (__DEV__) { ("production" !== "production" ? invariant( isValidComponentDescriptor(descriptor), 'Only React Components are valid for mounting.' ) : invariant(isValidComponentDescriptor(descriptor))); // } return new descriptor.type(descriptor); } module.exports = instantiateReactComponent; },{"./invariant":66}],66:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule invariant */ "use strict"; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if ("production" !== "production") { if (format === undefined) { throw new Error('invariant requires an error message argument'); } } if (!condition) { var error; if (format === undefined) { error = new Error( 'Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.' ); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error( 'Invariant Violation: ' + format.replace(/%s/g, function() { return args[argIndex++]; }) ); } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } }; module.exports = invariant; },{}],67:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule isEventSupported */ "use strict"; var ExecutionEnvironment = _dereq_("./ExecutionEnvironment"); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; },{"./ExecutionEnvironment":42}],68:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule joinClasses * @typechecks static-only */ "use strict"; /** * Combines multiple className strings into one. * http://jsperf.com/joinclasses-args-vs-array * * @param {...?string} classes * @return {string} */ function joinClasses(className/*, ... */) { if (!className) { className = ''; } var nextClass; var argLength = arguments.length; if (argLength > 1) { for (var ii = 1; ii < argLength; ii++) { nextClass = arguments[ii]; nextClass && (className += ' ' + nextClass); } } return className; } module.exports = joinClasses; },{}],69:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule keyMirror * @typechecks static-only */ "use strict"; var invariant = _dereq_("./invariant"); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function(obj) { var ret = {}; var key; ("production" !== "production" ? invariant( obj instanceof Object && !Array.isArray(obj), 'keyMirror(...): Argument must be an object.' ) : invariant(obj instanceof Object && !Array.isArray(obj))); for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; },{"./invariant":66}],70:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule keyOf */ /** * Allows extraction of a minified key. Let's the build system minify keys * without loosing the ability to dynamically use key strings as values * themselves. Pass in an object with a single key/val pair and it will return * you the string key of that single record. Suppose you want to grab the * value for a key 'className' inside of an object. Key/val minification may * have aliased that key to be 'xa12'. keyOf({className: null}) will return * 'xa12' in that case. Resolve keys you want to use once at startup time, then * reuse those resolutions. */ var keyOf = function(oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; },{}],71:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule merge */ "use strict"; var mergeInto = _dereq_("./mergeInto"); /** * Shallow merges two structures into a return value, without mutating either. * * @param {?object} one Optional object with properties to merge from. * @param {?object} two Optional object with properties to merge from. * @return {object} The shallow extension of one by two. */ var merge = function(one, two) { var result = {}; mergeInto(result, one); mergeInto(result, two); return result; }; module.exports = merge; },{"./mergeInto":73}],72:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule mergeHelpers * * requiresPolyfills: Array.isArray */ "use strict"; var invariant = _dereq_("./invariant"); var keyMirror = _dereq_("./keyMirror"); /** * Maximum number of levels to traverse. Will catch circular structures. * @const */ var MAX_MERGE_DEPTH = 36; /** * We won't worry about edge cases like new String('x') or new Boolean(true). * Functions are considered terminals, and arrays are not. * @param {*} o The item/object/value to test. * @return {boolean} true iff the argument is a terminal. */ var isTerminal = function(o) { return typeof o !== 'object' || o === null; }; var mergeHelpers = { MAX_MERGE_DEPTH: MAX_MERGE_DEPTH, isTerminal: isTerminal, /** * Converts null/undefined values into empty object. * * @param {?Object=} arg Argument to be normalized (nullable optional) * @return {!Object} */ normalizeMergeArg: function(arg) { return arg === undefined || arg === null ? {} : arg; }, /** * If merging Arrays, a merge strategy *must* be supplied. If not, it is * likely the caller's fault. If this function is ever called with anything * but `one` and `two` being `Array`s, it is the fault of the merge utilities. * * @param {*} one Array to merge into. * @param {*} two Array to merge from. */ checkMergeArrayArgs: function(one, two) { ("production" !== "production" ? invariant( Array.isArray(one) && Array.isArray(two), 'Tried to merge arrays, instead got %s and %s.', one, two ) : invariant(Array.isArray(one) && Array.isArray(two))); }, /** * @param {*} one Object to merge into. * @param {*} two Object to merge from. */ checkMergeObjectArgs: function(one, two) { mergeHelpers.checkMergeObjectArg(one); mergeHelpers.checkMergeObjectArg(two); }, /** * @param {*} arg */ checkMergeObjectArg: function(arg) { ("production" !== "production" ? invariant( !isTerminal(arg) && !Array.isArray(arg), 'Tried to merge an object, instead got %s.', arg ) : invariant(!isTerminal(arg) && !Array.isArray(arg))); }, /** * @param {*} arg */ checkMergeIntoObjectArg: function(arg) { ("production" !== "production" ? invariant( (!isTerminal(arg) || typeof arg === 'function') && !Array.isArray(arg), 'Tried to merge into an object, instead got %s.', arg ) : invariant((!isTerminal(arg) || typeof arg === 'function') && !Array.isArray(arg))); }, /** * Checks that a merge was not given a circular object or an object that had * too great of depth. * * @param {number} Level of recursion to validate against maximum. */ checkMergeLevel: function(level) { ("production" !== "production" ? invariant( level < MAX_MERGE_DEPTH, 'Maximum deep merge depth exceeded. You may be attempting to merge ' + 'circular structures in an unsupported way.' ) : invariant(level < MAX_MERGE_DEPTH)); }, /** * Checks that the supplied merge strategy is valid. * * @param {string} Array merge strategy. */ checkArrayStrategy: function(strategy) { ("production" !== "production" ? invariant( strategy === undefined || strategy in mergeHelpers.ArrayStrategies, 'You must provide an array strategy to deep merge functions to ' + 'instruct the deep merge how to resolve merging two arrays.' ) : invariant(strategy === undefined || strategy in mergeHelpers.ArrayStrategies)); }, /** * Set of possible behaviors of merge algorithms when encountering two Arrays * that must be merged together. * - `clobber`: The left `Array` is ignored. * - `indexByIndex`: The result is achieved by recursively deep merging at * each index. (not yet supported.) */ ArrayStrategies: keyMirror({ Clobber: true, IndexByIndex: true }) }; module.exports = mergeHelpers; },{"./invariant":66,"./keyMirror":69}],73:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule mergeInto * @typechecks static-only */ "use strict"; var mergeHelpers = _dereq_("./mergeHelpers"); var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg; var checkMergeIntoObjectArg = mergeHelpers.checkMergeIntoObjectArg; /** * Shallow merges two structures by mutating the first parameter. * * @param {object|function} one Object to be merged into. * @param {?object} two Optional object with properties to merge from. */ function mergeInto(one, two) { checkMergeIntoObjectArg(one); if (two != null) { checkMergeObjectArg(two); for (var key in two) { if (!two.hasOwnProperty(key)) { continue; } one[key] = two[key]; } } } module.exports = mergeInto; },{"./mergeHelpers":72}],74:[function(_dereq_,module,exports){ /** * Copyright 2013-2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule mixInto */ "use strict"; /** * Simply copies properties to the prototype. */ var mixInto = function(constructor, methodBag) { var methodName; for (methodName in methodBag) { if (!methodBag.hasOwnProperty(methodName)) { continue; } constructor.prototype[methodName] = methodBag[methodName]; } }; module.exports = mixInto; },{}],75:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule monitorCodeUse */ "use strict"; var invariant = _dereq_("./invariant"); /** * Provides open-source compatible instrumentation for monitoring certain API * uses before we're ready to issue a warning or refactor. It accepts an event * name which may only contain the characters [a-z0-9_] and an optional data * object with further information. */ function monitorCodeUse(eventName, data) { ("production" !== "production" ? invariant( eventName && !/[^a-z0-9_]/.test(eventName), 'You must provide an eventName using only the characters [a-z0-9_]' ) : invariant(eventName && !/[^a-z0-9_]/.test(eventName))); } module.exports = monitorCodeUse; },{"./invariant":66}],76:[function(_dereq_,module,exports){ /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule warning */ "use strict"; var emptyFunction = _dereq_("./emptyFunction"); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if ("production" !== "production") { warning = function(condition, format ) {var args=Array.prototype.slice.call(arguments,2); if (format === undefined) { throw new Error( '`warning(condition, format, ...args)` requires a warning ' + 'message argument' ); } if (!condition) { var argIndex = 0; console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];})); } }; } module.exports = warning; },{"./emptyFunction":62}],77:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function (_dereq_) { var makePromise = _dereq_('./makePromise'); var Scheduler = _dereq_('./Scheduler'); var async = _dereq_('./async'); return makePromise({ scheduler: new Scheduler(async) }); }); })(typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(_dereq_); }); },{"./Scheduler":79,"./async":80,"./makePromise":81}],78:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { /** * Circular queue * @param {number} capacityPow2 power of 2 to which this queue's capacity * will be set initially. eg when capacityPow2 == 3, queue capacity * will be 8. * @constructor */ function Queue(capacityPow2) { this.head = this.tail = this.length = 0; this.buffer = new Array(1 << capacityPow2); } Queue.prototype.push = function(x) { if(this.length === this.buffer.length) { this._ensureCapacity(this.length * 2); } this.buffer[this.tail] = x; this.tail = (this.tail + 1) & (this.buffer.length - 1); ++this.length; return this.length; }; Queue.prototype.shift = function() { var x = this.buffer[this.head]; this.buffer[this.head] = void 0; this.head = (this.head + 1) & (this.buffer.length - 1); --this.length; return x; }; Queue.prototype._ensureCapacity = function(capacity) { var head = this.head; var buffer = this.buffer; var newBuffer = new Array(capacity); var i = 0; var len; if(head === 0) { len = this.length; for(; i<len; ++i) { newBuffer[i] = buffer[i]; } } else { capacity = buffer.length; len = this.tail; for(; head<capacity; ++i, ++head) { newBuffer[i] = buffer[head]; } for(head=0; head<len; ++i, ++head) { newBuffer[i] = buffer[head]; } } this.buffer = newBuffer; this.head = 0; this.tail = this.length; }; return Queue; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}],79:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { var Queue = _dereq_('./Queue'); // Credit to Twisol (https://github.com/Twisol) for suggesting // this type of extensible queue + trampoline approach for next-tick conflation. /** * Async task scheduler * @param {function} async function to schedule a single async function * @constructor */ function Scheduler(async) { this._async = async; this._queue = new Queue(15); this._afterQueue = new Queue(5); this._running = false; var self = this; this.drain = function() { self._drain(); }; } /** * Enqueue a task * @param {{ run:function }} task */ Scheduler.prototype.enqueue = function(task) { this._add(this._queue, task); }; /** * Enqueue a task to run after the main task queue * @param {{ run:function }} task */ Scheduler.prototype.afterQueue = function(task) { this._add(this._afterQueue, task); }; /** * Drain the handler queue entirely, and then the after queue */ Scheduler.prototype._drain = function() { runQueue(this._queue); this._running = false; runQueue(this._afterQueue); }; /** * Add a task to the q, and schedule drain if not already scheduled * @param {Queue} queue * @param {{run:function}} task * @private */ Scheduler.prototype._add = function(queue, task) { queue.push(task); if(!this._running) { this._running = true; this._async(this.drain); } }; /** * Run all the tasks in the q * @param queue */ function runQueue(queue) { while(queue.length > 0) { queue.shift().run(); } } return Scheduler; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{"./Queue":78}],80:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function(_dereq_) { // Sniff "best" async scheduling option // Prefer process.nextTick or MutationObserver, then check for // vertx and finally fall back to setTimeout /*jshint maxcomplexity:6*/ /*global process,document,setTimeout,MutationObserver,WebKitMutationObserver*/ var nextTick, MutationObs; if (typeof process !== 'undefined' && process !== null && typeof process.nextTick === 'function') { nextTick = function(f) { process.nextTick(f); }; } else if (MutationObs = (typeof MutationObserver === 'function' && MutationObserver) || (typeof WebKitMutationObserver === 'function' && WebKitMutationObserver)) { nextTick = (function (document, MutationObserver) { var scheduled; var el = document.createElement('div'); var o = new MutationObserver(run); o.observe(el, { attributes: true }); function run() { var f = scheduled; scheduled = void 0; f(); } return function (f) { scheduled = f; el.setAttribute('class', 'x'); }; }(document, MutationObs)); } else { nextTick = (function(cjsRequire) { var vertx; try { // vert.x 1.x || 2.x vertx = cjsRequire('vertx'); } catch (ignore) {} if (vertx) { if (typeof vertx.runOnLoop === 'function') { return vertx.runOnLoop; } if (typeof vertx.runOnContext === 'function') { return vertx.runOnContext; } } // capture setTimeout to avoid being caught by fake timers // used in time based tests var capturedSetTimeout = setTimeout; return function (t) { capturedSetTimeout(t, 0); }; }(_dereq_)); } return nextTick; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(_dereq_); })); },{}],81:[function(_dereq_,module,exports){ /** @license MIT License (c) copyright 2010-2014 original author or authors */ /** @author Brian Cavalier */ /** @author John Hann */ (function(define) { 'use strict'; define(function() { return function makePromise(environment) { var tasks = environment.scheduler; var objectCreate = Object.create || function(proto) { function Child() {} Child.prototype = proto; return new Child(); }; /** * Create a promise whose fate is determined by resolver * @constructor * @returns {Promise} promise * @name Promise */ function Promise(resolver, handler) { this._handler = resolver === Handler ? handler : init(resolver); } /** * Run the supplied resolver * @param resolver * @returns {Pending} */ function init(resolver) { var handler = new Pending(); try { resolver(promiseResolve, promiseReject, promiseNotify); } catch (e) { promiseReject(e); } return handler; /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the ultimate fulfillment or rejection * @param {*} x resolution value */ function promiseResolve (x) { handler.resolve(x); } /** * Reject this promise with reason, which will be used verbatim * @param {Error|*} reason rejection reason, strongly suggested * to be an Error type */ function promiseReject (reason) { handler.reject(reason); } /** * Issue a progress event, notifying all progress listeners * @param {*} x progress event payload to pass to all listeners */ function promiseNotify (x) { handler.notify(x); } } // Creation Promise.resolve = resolve; Promise.reject = reject; Promise.never = never; Promise._defer = defer; Promise._handler = getHandler; /** * Returns a trusted promise. If x is already a trusted promise, it is * returned, otherwise returns a new trusted Promise which follows x. * @param {*} x * @return {Promise} promise */ function resolve(x) { return isPromise(x) ? x : new Promise(Handler, new Async(getHandler(x))); } /** * Return a reject promise with x as its reason (x is used verbatim) * @param {*} x * @returns {Promise} rejected promise */ function reject(x) { return new Promise(Handler, new Async(new Rejected(x))); } /** * Return a promise that remains pending forever * @returns {Promise} forever-pending promise. */ function never() { return foreverPendingPromise; // Should be frozen } /** * Creates an internal {promise, resolver} pair * @private * @returns {Promise} */ function defer() { return new Promise(Handler, new Pending()); } // Transformation and flow control /** * Transform this promise's fulfillment value, returning a new Promise * for the transformed result. If the promise cannot be fulfilled, onRejected * is called with the reason. onProgress *may* be called with updates toward * this promise's fulfillment. * @param {function=} onFulfilled fulfillment handler * @param {function=} onRejected rejection handler * @deprecated @param {function=} onProgress progress handler * @return {Promise} new promise */ Promise.prototype.then = function(onFulfilled, onRejected) { var parent = this._handler; var state = parent.join().state(); if ((typeof onFulfilled !== 'function' && state > 0) || (typeof onRejected !== 'function' && state < 0)) { // Short circuit: value will not change, simply share handler return new this.constructor(Handler, parent); } var p = this._beget(); var child = p._handler; parent.chain(child, parent.receiver, onFulfilled, onRejected, arguments.length > 2 ? arguments[2] : void 0); return p; }; /** * If this promise cannot be fulfilled due to an error, call onRejected to * handle the error. Shortcut for .then(undefined, onRejected) * @param {function?} onRejected * @return {Promise} */ Promise.prototype['catch'] = function(onRejected) { return this.then(void 0, onRejected); }; /** * Creates a new, pending promise of the same type as this promise * @private * @returns {Promise} */ Promise.prototype._beget = function() { var parent = this._handler; var child = new Pending(parent.receiver, parent.join().context); return new this.constructor(Handler, child); }; // Array combinators Promise.all = all; Promise.race = race; /** * Return a promise that will fulfill when all promises in the * input array have fulfilled, or will reject when one of the * promises rejects. * @param {array} promises array of promises * @returns {Promise} promise for array of fulfillment values */ function all(promises) { /*jshint maxcomplexity:8*/ var resolver = new Pending(); var pending = promises.length >>> 0; var results = new Array(pending); var i, h, x, s; for (i = 0; i < promises.length; ++i) { x = promises[i]; if (x === void 0 && !(i in promises)) { --pending; continue; } if (maybeThenable(x)) { h = getHandlerMaybeThenable(x); s = h.state(); if (s === 0) { h.fold(settleAt, i, results, resolver); } else if (s > 0) { results[i] = h.value; --pending; } else { unreportRemaining(promises, i+1, h); resolver.become(h); break; } } else { results[i] = x; --pending; } } if(pending === 0) { resolver.become(new Fulfilled(results)); } return new Promise(Handler, resolver); function settleAt(i, x, resolver) { /*jshint validthis:true*/ this[i] = x; if(--pending === 0) { resolver.become(new Fulfilled(this)); } } } function unreportRemaining(promises, start, rejectedHandler) { var i, h, x; for(i=start; i<promises.length; ++i) { x = promises[i]; if(maybeThenable(x)) { h = getHandlerMaybeThenable(x); if(h !== rejectedHandler) { h.visit(h, void 0, h._unreport); } } } } /** * Fulfill-reject competitive race. Return a promise that will settle * to the same state as the earliest input promise to settle. * * WARNING: The ES6 Promise spec requires that race()ing an empty array * must return a promise that is pending forever. This implementation * returns a singleton forever-pending promise, the same singleton that is * returned by Promise.never(), thus can be checked with === * * @param {array} promises array of promises to race * @returns {Promise} if input is non-empty, a promise that will settle * to the same outcome as the earliest input promise to settle. if empty * is empty, returns a promise that will never settle. */ function race(promises) { // Sigh, race([]) is untestable unless we return *something* // that is recognizable without calling .then() on it. if(Object(promises) === promises && promises.length === 0) { return never(); } var h = new Pending(); var i, x; for(i=0; i<promises.length; ++i) { x = promises[i]; if (x !== void 0 && i in promises) { getHandler(x).visit(h, h.resolve, h.reject); } } return new Promise(Handler, h); } // Promise internals // Below this, everything is @private /** * Get an appropriate handler for x, without checking for cycles * @param {*} x * @returns {object} handler */ function getHandler(x) { if(isPromise(x)) { return x._handler.join(); } return maybeThenable(x) ? getHandlerUntrusted(x) : new Fulfilled(x); } /** * Get a handler for thenable x. * NOTE: You must only call this if maybeThenable(x) == true * @param {object|function|Promise} x * @returns {object} handler */ function getHandlerMaybeThenable(x) { return isPromise(x) ? x._handler.join() : getHandlerUntrusted(x); } /** * Get a handler for potentially untrusted thenable x * @param {*} x * @returns {object} handler */ function getHandlerUntrusted(x) { try { var untrustedThen = x.then; return typeof untrustedThen === 'function' ? new Thenable(untrustedThen, x) : new Fulfilled(x); } catch(e) { return new Rejected(e); } } /** * Handler for a promise that is pending forever * @constructor */ function Handler() {} Handler.prototype.when = Handler.prototype.become = Handler.prototype.notify = Handler.prototype.fail = Handler.prototype._unreport = Handler.prototype._report = noop; Handler.prototype._state = 0; Handler.prototype.state = function() { return this._state; }; /** * Recursively collapse handler chain to find the handler * nearest to the fully resolved value. * @returns {object} handler nearest the fully resolved value */ Handler.prototype.join = function() { var h = this; while(h.handler !== void 0) { h = h.handler; } return h; }; Handler.prototype.chain = function(to, receiver, fulfilled, rejected, progress) { this.when({ resolver: to, receiver: receiver, fulfilled: fulfilled, rejected: rejected, progress: progress }); }; Handler.prototype.visit = function(receiver, fulfilled, rejected, progress) { this.chain(failIfRejected, receiver, fulfilled, rejected, progress); }; Handler.prototype.fold = function(f, z, c, to) { this.visit(to, function(x) { f.call(c, z, x, this); }, to.reject, to.notify); }; /** * Handler that invokes fail() on any handler it becomes * @constructor */ function FailIfRejected() {} inherit(Handler, FailIfRejected); FailIfRejected.prototype.become = function(h) { h.fail(); }; var failIfRejected = new FailIfRejected(); /** * Handler that manages a queue of consumers waiting on a pending promise * @constructor */ function Pending(receiver, inheritedContext) { Promise.createContext(this, inheritedContext); this.consumers = void 0; this.receiver = receiver; this.handler = void 0; this.resolved = false; } inherit(Handler, Pending); Pending.prototype._state = 0; Pending.prototype.resolve = function(x) { this.become(getHandler(x)); }; Pending.prototype.reject = function(x) { if(this.resolved) { return; } this.become(new Rejected(x)); }; Pending.prototype.join = function() { if (!this.resolved) { return this; } var h = this; while (h.handler !== void 0) { h = h.handler; if (h === this) { return this.handler = cycle(); } } return h; }; Pending.prototype.run = function() { var q = this.consumers; var handler = this.join(); this.consumers = void 0; for (var i = 0; i < q.length; ++i) { handler.when(q[i]); } }; Pending.prototype.become = function(handler) { if(this.resolved) { return; } this.resolved = true; this.handler = handler; if(this.consumers !== void 0) { tasks.enqueue(this); } if(this.context !== void 0) { handler._report(this.context); } }; Pending.prototype.when = function(continuation) { if(this.resolved) { tasks.enqueue(new ContinuationTask(continuation, this.handler)); } else { if(this.consumers === void 0) { this.consumers = [continuation]; } else { this.consumers.push(continuation); } } }; Pending.prototype.notify = function(x) { if(!this.resolved) { tasks.enqueue(new ProgressTask(x, this)); } }; Pending.prototype.fail = function(context) { var c = typeof context === 'undefined' ? this.context : context; this.resolved && this.handler.join().fail(c); }; Pending.prototype._report = function(context) { this.resolved && this.handler.join()._report(context); }; Pending.prototype._unreport = function() { this.resolved && this.handler.join()._unreport(); }; /** * Wrap another handler and force it into a future stack * @param {object} handler * @constructor */ function Async(handler) { this.handler = handler; } inherit(Handler, Async); Async.prototype.when = function(continuation) { tasks.enqueue(new ContinuationTask(continuation, this)); }; Async.prototype._report = function(context) { this.join()._report(context); }; Async.prototype._unreport = function() { this.join()._unreport(); }; /** * Handler that wraps an untrusted thenable and assimilates it in a future stack * @param {function} then * @param {{then: function}} thenable * @constructor */ function Thenable(then, thenable) { Pending.call(this); tasks.enqueue(new AssimilateTask(then, thenable, this)); } inherit(Pending, Thenable); /** * Handler for a fulfilled promise * @param {*} x fulfillment value * @constructor */ function Fulfilled(x) { Promise.createContext(this); this.value = x; } inherit(Handler, Fulfilled); Fulfilled.prototype._state = 1; Fulfilled.prototype.fold = function(f, z, c, to) { runContinuation3(f, z, this, c, to); }; Fulfilled.prototype.when = function(cont) { runContinuation1(cont.fulfilled, this, cont.receiver, cont.resolver); }; var errorId = 0; /** * Handler for a rejected promise * @param {*} x rejection reason * @constructor */ function Rejected(x) { Promise.createContext(this); this.id = ++errorId; this.value = x; this.handled = false; this.reported = false; this._report(); } inherit(Handler, Rejected); Rejected.prototype._state = -1; Rejected.prototype.fold = function(f, z, c, to) { to.become(this); }; Rejected.prototype.when = function(cont) { if(typeof cont.rejected === 'function') { this._unreport(); } runContinuation1(cont.rejected, this, cont.receiver, cont.resolver); }; Rejected.prototype._report = function(context) { tasks.afterQueue(new ReportTask(this, context)); }; Rejected.prototype._unreport = function() { this.handled = true; tasks.afterQueue(new UnreportTask(this)); }; Rejected.prototype.fail = function(context) { Promise.onFatalRejection(this, context === void 0 ? this.context : context); }; function ReportTask(rejection, context) { this.rejection = rejection; this.context = context; } ReportTask.prototype.run = function() { if(!this.rejection.handled) { this.rejection.reported = true; Promise.onPotentiallyUnhandledRejection(this.rejection, this.context); } }; function UnreportTask(rejection) { this.rejection = rejection; } UnreportTask.prototype.run = function() { if(this.rejection.reported) { Promise.onPotentiallyUnhandledRejectionHandled(this.rejection); } }; // Unhandled rejection hooks // By default, everything is a noop // TODO: Better names: "annotate"? Promise.createContext = Promise.enterContext = Promise.exitContext = Promise.onPotentiallyUnhandledRejection = Promise.onPotentiallyUnhandledRejectionHandled = Promise.onFatalRejection = noop; // Errors and singletons var foreverPendingHandler = new Handler(); var foreverPendingPromise = new Promise(Handler, foreverPendingHandler); function cycle() { return new Rejected(new TypeError('Promise cycle')); } // Task runners /** * Run a single consumer * @constructor */ function ContinuationTask(continuation, handler) { this.continuation = continuation; this.handler = handler; } ContinuationTask.prototype.run = function() { this.handler.join().when(this.continuation); }; /** * Run a queue of progress handlers * @constructor */ function ProgressTask(value, handler) { this.handler = handler; this.value = value; } ProgressTask.prototype.run = function() { var q = this.handler.consumers; if(q === void 0) { return; } for (var c, i = 0; i < q.length; ++i) { c = q[i]; runNotify(c.progress, this.value, this.handler, c.receiver, c.resolver); } }; /** * Assimilate a thenable, sending it's value to resolver * @param {function} then * @param {object|function} thenable * @param {object} resolver * @constructor */ function AssimilateTask(then, thenable, resolver) { this._then = then; this.thenable = thenable; this.resolver = resolver; } AssimilateTask.prototype.run = function() { var h = this.resolver; tryAssimilate(this._then, this.thenable, _resolve, _reject, _notify); function _resolve(x) { h.resolve(x); } function _reject(x) { h.reject(x); } function _notify(x) { h.notify(x); } }; function tryAssimilate(then, thenable, resolve, reject, notify) { try { then.call(thenable, resolve, reject, notify); } catch (e) { reject(e); } } // Other helpers /** * @param {*} x * @returns {boolean} true iff x is a trusted Promise */ function isPromise(x) { return x instanceof Promise; } /** * Test just enough to rule out primitives, in order to take faster * paths in some code * @param {*} x * @returns {boolean} false iff x is guaranteed *not* to be a thenable */ function maybeThenable(x) { return (typeof x === 'object' || typeof x === 'function') && x !== null; } function runContinuation1(f, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject(f, h.value, receiver, next); Promise.exitContext(); } function runContinuation3(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.become(h); } Promise.enterContext(h); tryCatchReject3(f, x, h.value, receiver, next); Promise.exitContext(); } function runNotify(f, x, h, receiver, next) { if(typeof f !== 'function') { return next.notify(x); } Promise.enterContext(h); tryCatchReturn(f, x, receiver, next); Promise.exitContext(); } /** * Return f.call(thisArg, x), or if it throws return a rejected promise for * the thrown exception */ function tryCatchReject(f, x, thisArg, next) { try { next.become(getHandler(f.call(thisArg, x))); } catch(e) { next.become(new Rejected(e)); } } /** * Same as above, but includes the extra argument parameter. */ function tryCatchReject3(f, x, y, thisArg, next) { try { f.call(thisArg, x, y, next); } catch(e) { next.become(new Rejected(e)); } } /** * Return f.call(thisArg, x), or if it throws, *return* the exception */ function tryCatchReturn(f, x, thisArg, next) { try { next.notify(f.call(thisArg, x)); } catch(e) { next.notify(e); } } function inherit(Parent, Child) { Child.prototype = objectCreate(Parent.prototype); Child.prototype.constructor = Child; } function noop() {} return Promise; }; }); }(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); })); },{}]},{},[10]) (10) });
packages/material-ui-icons/legacy/Battery20TwoTone.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z" /><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z" /></React.Fragment> , 'Battery20TwoTone');
app/javascript/mastodon/features/compose/components/upload_progress.js
h3zjp/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import Motion from '../../ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import Icon from 'mastodon/components/icon'; export default class UploadProgress extends React.PureComponent { static propTypes = { active: PropTypes.bool, progress: PropTypes.number, icon: PropTypes.string.isRequired, message: PropTypes.node.isRequired, }; render () { const { active, progress, icon, message } = this.props; if (!active) { return null; } return ( <div className='upload-progress'> <div className='upload-progress__icon'> <Icon id={icon} /> </div> <div className='upload-progress__message'> {message} <div className='upload-progress__backdrop'> <Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}> {({ width }) => <div className='upload-progress__tracker' style={{ width: `${width}%` }} /> } </Motion> </div> </div> </div> ); } }